Here are the examples of the csharp api System.Text.StringBuilder.AppendLine() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3230 Examples
19
View Source File : CelesteNetPlayerListComponent.cs
License : MIT License
Project Creator : 0x0ade
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 : CelesteNetPlayerListComponent.cs
License : MIT License
Project Creator : 0x0ade
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 : ChatCMDHelp.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public string GetCommandPage(ChatCMDEnv env, int page = 0) {
const int pageSize = 8;
string prefix = Chat.Settings.CommandPrefix;
StringBuilder builder = new();
int pages = (int) Math.Ceiling(Chat.Commands.All.Count / (float) pageSize);
if (page < 0 || pages <= page)
throw new Exception("Page out of range.");
for (int i = page * pageSize; i < (page + 1) * pageSize && i < Chat.Commands.All.Count; i++) {
ChatCMD cmd = Chat.Commands.All[i];
builder
.Append(prefix)
.Append(cmd.ID)
.Append(" ")
.Append(cmd.Args)
.AppendLine();
}
builder
.Append("Page ")
.Append(page + 1)
.Append("/")
.Append(pages);
return builder.ToString().Trim();
}
19
View Source File : MainActivity.cs
License : Microsoft Public License
Project Creator : 0x0ade
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 : ChatCMDChannel.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override void ParseAndRun(ChatCMDEnv env) {
CelesteNetPlayerSession? session = env.Session;
if (session == null)
return;
Channels channels = env.Server.Channels;
Channel? c;
if (int.TryParse(env.Text, out int page) ||
string.IsNullOrWhiteSpace(env.Text)) {
if (channels.All.Count == 0) {
env.Send($"No channels. See {Chat.Settings.CommandPrefix}{ID} on how to create one.");
return;
}
const int pageSize = 8;
StringBuilder builder = new();
page--;
int pages = (int) Math.Ceiling(channels.All.Count / (float) pageSize);
if (page < 0 || pages <= page)
throw new Exception("Page out of range.");
if (page == 0)
builder
.Append("You're in ")
.Append(session.Channel.Name)
.AppendLine();
for (int i = page * pageSize; i < (page + 1) * pageSize && i < channels.All.Count; i++) {
c = channels.All[i];
builder
.Append(c.PublicName)
.Append(" - ")
.Append(c.Players.Count)
.Append(" players")
.AppendLine();
}
builder
.Append("Page ")
.Append(page + 1)
.Append("/")
.Append(pages);
env.Send(builder.ToString().Trim());
return;
}
Tuple<Channel, Channel> tuple = channels.Move(session, env.Text);
if (tuple.Item1 == tuple.Item2) {
env.Send($"Already in {tuple.Item2.Name}");
} else {
env.Send($"Moved to {tuple.Item2.Name}");
}
}
19
View Source File : ChatCMDHelp.cs
License : MIT License
Project Creator : 0x0ade
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 : GeneratorClass.cs
License : MIT License
Project Creator : 188867052
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
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
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
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
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 : VBAGenerator.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public string GenerateScript(byte[] serialized_object, string entry_clreplaced_name, string additional_script, RuntimeVersion version, bool enable_debug)
{
string hex_encoded = BitConverter.ToString(serialized_object).Replace("-", "");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hex_encoded.Length; i++)
{
if (i == 0)
{
builder.Append("s = \"");
}
else if (i % 300 == 0)
{
builder.Append("\"");
builder.AppendLine();
builder.Append(" s = s & \"");
}
builder.Append(hex_encoded[i]);
}
builder.Append("\"");
return GetScriptHeader(enable_debug) +
Global_Var.vba_template.Replace(
"%SERIALIZED%",
builder.ToString()
).Replace(
"%CLreplaced%",
entry_clreplaced_name
).Replace(
"%MANIFEST%",
GetManifest(version)
).Replace(
"%ADDEDSCRIPT%",
additional_script
);
}
19
View Source File : VBAGenerator.cs
License : MIT License
Project Creator : 1y0n
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 : VBAGenerator.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static string GetManifest(RuntimeVersion version)
{
StringBuilder builder = new StringBuilder();
string runtimeVersion = (version != RuntimeVersion.v2) ? "v4.0.30319" : "v2.0.50727";
string mscorlibVersion = (version != RuntimeVersion.v2) ? "4.0.0.0" : "2.0.0.0";
string template = Global_Var.manifest_template.Replace(
"%RUNTIMEVERSION%",
runtimeVersion
).Replace(
"%MSCORLIBVERSION%",
mscorlibVersion
);
for (int i = 0; i < template.Length; i++)
{
if (i == 0)
{
builder.Append("manifest = \"");
}
else if (i % 300 == 0)
{
builder.Append("\"");
builder.AppendLine();
builder.Append(" manifest = manifest & \"");
}
builder.Append(template[i]);
if (template[i] == '"') builder.Append('"');
}
builder.Append("\"");
return builder.ToString();
}
19
View Source File : VBScriptGenerator.cs
License : MIT License
Project Creator : 1y0n
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 : TsCreator.cs
License : MIT License
Project Creator : 279328316
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
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
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 : MainForm.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
private void menuExport2SubContent_Click(object sender, EventArgs e)
{
GetLvSelectedIndex();
StringBuilder sb = new StringBuilder();
foreach (int v in lvSelecteds)
{
string url = ShareHandler.GetShareUrl(config, v);
if (Utils.IsNullOrEmpty(url))
{
continue;
}
sb.Append(url);
sb.AppendLine();
}
if (sb.Length > 0)
{
Utils.SetClipboardData(Utils.Base64Encode(sb.ToString()));
UI.Show(UIRes.I18N("BatchExportSubscriptionSuccessfully"));
}
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
private void menuExport2ShareUrl_Click(object sender, EventArgs e)
{
GetLvSelectedIndex();
StringBuilder sb = new StringBuilder();
foreach (int v in lvSelecteds)
{
string url = ShareHandler.GetShareUrl(config, v);
if (Utils.IsNullOrEmpty(url))
{
continue;
}
sb.Append(url);
sb.AppendLine();
}
if (sb.Length > 0)
{
Utils.SetClipboardData(sb.ToString());
AppendText(false, UIRes.I18N("BatchExportURLSuccessfully"));
//UI.Show(UIRes.I18N("BatchExportURLSuccessfully"));
}
}
19
View Source File : CodeGenerate.cs
License : MIT License
Project Creator : 2881099
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 : CodeGenerate.cs
License : MIT License
Project Creator : 2881099
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 : CodeGenerate.cs
License : MIT License
Project Creator : 2881099
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 : SourceStringBuilder.cs
License : MIT License
Project Creator : 31
License : MIT License
Project Creator : 31
public void Line(params string[] parts)
{
if (parts.Length != 0)
{
_sourceBuilder.Append(_indentPrefix);
foreach (var s in parts)
{
_sourceBuilder.Append(s);
}
}
_sourceBuilder.AppendLine();
}
19
View Source File : Helpers.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static System.Text.StringBuilder AppendLine(System.Text.StringBuilder builder)
{
#if CF2
return builder.Append("\r\n");
#elif FX11
return builder.Append(Environment.NewLine);
#else
return builder.AppendLine();
#endif
}
19
View Source File : SimpleJSON.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
{
aSB.Append('[');
int count = m_List.Count;
if (inline)
aMode = JSONTextMode.Compact;
for (int i = 0; i < count; i++)
{
if (i > 0)
aSB.Append(',');
if (aMode == JSONTextMode.Indent)
aSB.AppendLine();
if (aMode == JSONTextMode.Indent)
aSB.Append(' ', aIndent + aIndentInc);
m_List[i].WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode);
}
if (aMode == JSONTextMode.Indent)
aSB.AppendLine().Append(' ', aIndent);
aSB.Append(']');
}
19
View Source File : SimpleJSON.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
{
aSB.Append('{');
bool first = true;
if (inline)
aMode = JSONTextMode.Compact;
foreach (var k in m_Dict)
{
if (!first)
aSB.Append(',');
first = false;
if (aMode == JSONTextMode.Indent)
aSB.AppendLine();
if (aMode == JSONTextMode.Indent)
aSB.Append(' ', aIndent + aIndentInc);
aSB.Append('\"').Append(Escape(k.Key)).Append('\"');
if (aMode == JSONTextMode.Compact)
aSB.Append(':');
else
aSB.Append(" : ");
k.Value.WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode);
}
if (aMode == JSONTextMode.Indent)
aSB.AppendLine().Append(' ', aIndent);
aSB.Append('}');
}
19
View Source File : PlantumlDiagram.cs
License : MIT License
Project Creator : 8T4
License : MIT License
Project Creator : 8T4
public static string ToPumlString(this Diagram diagram, bool useStandardLibrary)
{
var path = GetPumlFilePath(diagram, useStandardLibrary);
var stream = new StringBuilder();
stream.AppendLine($"@startuml {diagram.Slug()}");
stream.AppendLine($"!include {path}");
stream.AppendLine();
if (diagram.LayoutWithLegend && !diagram.ShowLegend)
{
stream.AppendLine("LAYOUT_WITH_LEGEND()");
}
if (diagram.Layoutreplacedketch)
{
stream.AppendLine("LAYOUT_AS_SKETCH()");
}
stream.AppendLine($"{(diagram.FlowVisualization == DiagramLayout.TopDown ? "LAYOUT_TOP_DOWN()" : "LAYOUT_LEFT_RIGHT()")}");
stream.AppendLine();
if (!string.IsNullOrWhiteSpace(diagram.replacedle))
{
stream.AppendLine($"replacedle {diagram.replacedle}");
stream.AppendLine();
}
foreach (var structure in diagram.Structures)
{
stream.AppendLine(structure.ToPumlString());
}
stream.AppendLine();
foreach (var relationship in diagram.Relationships)
{
stream.AppendLine(relationship.ToPumlString());
}
if (diagram.ShowLegend)
{
stream.AppendLine();
stream.AppendLine("SHOW_LEGEND()");
}
stream.AppendLine("@enduml");
return stream.ToString();
}
19
View Source File : PlantumlStructure.cs
License : MIT License
Project Creator : 8T4
License : MIT License
Project Creator : 8T4
private static string ToPumlString(this SoftwareSystemBoundary boundary)
{
var stream = new StringBuilder();
stream.AppendLine();
stream.AppendLine($"System_Boundary({boundary.Alias}, \"{boundary.Label}\") {{");
foreach (var container in boundary.Containers)
{
stream.AppendLine($"{SpaceMethods.Indent()}{container.ToPumlString()}");
}
stream.AppendLine("}");
return stream.ToString();
}
19
View Source File : PlantumlStructure.cs
License : MIT License
Project Creator : 8T4
License : MIT License
Project Creator : 8T4
private static string ToPumlString(this ContainerBoundary boundary)
{
var stream = new StringBuilder();
stream.AppendLine();
stream.AppendLine($"Container_Boundary({boundary.Alias}, \"{boundary.Label}\") {{");
foreach (var component in boundary.Components)
{
stream.AppendLine($"{SpaceMethods.Indent()}{component.ToPumlString()}");
}
if (boundary.Relationships.Any())
{
stream.AppendLine();
foreach (var relationship in boundary.Relationships)
{
stream.AppendLine($"{SpaceMethods.Indent()}{relationship.ToPumlString()}");
}
}
stream.AppendLine("}");
return stream.ToString();
}
19
View Source File : PlantumlStructure.cs
License : MIT License
Project Creator : 8T4
License : MIT License
Project Creator : 8T4
private static string ToPumlString(this DeploymentNode deployment, int concat = 0)
{
var stream = new StringBuilder();
var spaces = SpaceMethods.Indent(concat);
if (concat == 0)
{
stream.AppendLine();
}
if (deployment.Properties != null)
{
foreach (var (key, value) in deployment.Properties)
{
stream.AppendLine($"{spaces}AddProperty(\"{key}\", \"{value}\")");
}
}
stream.AppendLine(deployment.Tags is null
? $"{spaces}Deployment_Node({deployment.Alias}, \"{deployment.Label}\", \"{deployment.Description}\") {{"
: $"{spaces}Deployment_Node({deployment.Alias}, \"{deployment.Label}\", \"{deployment.Description}\", $tags=\"{string.Join(',', deployment.Tags)}\") {{");
if (deployment.Nodes != null)
{
foreach (var node in deployment.Nodes)
{
stream.AppendLine($"{node.ToPumlString(concat + SpaceMethods.TabSize)}");
}
}
if (deployment.Container != null)
{
stream.AppendLine(SpaceMethods.Indent(concat) + deployment.Container.ToPumlString());
}
stream.Append(spaces + "}");
return stream.ToString();
}
19
View Source File : Scenario.cs
License : MIT License
Project Creator : 8T4
License : MIT License
Project Creator : 8T4
private ScenarioResult ExectueMappedParadigms()
{
var result = new StringBuilder();
result.AppendLine();
result.AppendHorizontalLine(60);
foreach (var (key, value) in Paradigms.Syntagmas)
{
try
{
var mapped = MappedParadigms.GetSyntagma(key);
if (mapped.Sign.Signified.Value == null)
{
result.AppendLine(mapped.Metalanguage.Sign.Signifier.Value);
continue;
}
mapped.Sign.Signified.Value.Invoke(Fixture);
result.AppendLine($"{mapped.Metalanguage.Sign.Signifier.Value}".Indent(4));
}
catch (Exception ex)
{
result.AppendLine(Colors.Error(value.Metalanguage.Sign.Signifier.Value.Indent(4)));
result.AppendLine(Colors.Error(ex.Message.Indent(4)));
result.Insert(0, Colors.Error(Description.ToUpper(CultureInfo.InvariantCulture)));
return ScenarioResult.Fail(result.ToString());
}
}
result.Insert(0, Colors.Success(Description.ToUpper(CultureInfo.InvariantCulture)));
return ScenarioResult.Ok(result.ToString());
}
19
View Source File : SessionClientWrapper.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public string GetDescription(ServerInfoType infoType)
{
var sb = new StringBuilder();
sb.AppendLine("****************");
sb.Append("IP: ");
sb.Append(Chanel2Server.IP);
if (Chanel2Server.Port != SessionClient.DefaultPort)
{
sb.Append(":");
sb.Append(Chanel2Server.Port);
}
sb.AppendLine("Hosted by: @Aant");
if (!_sessionClient.IsLogined)
{
return Translator.ErrServerNotAvailable;
}
var serverInfo = _sessionClient.GetInfo(ServerInfoType.FullWithDescription);
if (serverInfo == null)
{
return Translator.ErrServerNotAvailable;
}
sb.AppendLine(serverInfo.Description);
if (infoType != ServerInfoType.FullWithDescription)
{
sb.AppendLine("Difficulty: " + serverInfo.Difficulty);
sb.AppendLine("MapSize: " + serverInfo.MapSize);
sb.AppendLine("PlanetCoverage: " + serverInfo.PlanetCoverage);
sb.AppendLine("Seed:" + serverInfo.Seed);
sb.AppendLine("VersionInfo" + serverInfo.VersionInfo);
sb.AppendLine("VersionNum" + serverInfo.VersionNum);
}
sb.AppendLine("****************");
sb.AppendLine();
sb.AppendLine();
return sb.ToString();
}
19
View Source File : UserModule.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
[Command("help")]
[Description("List of all commands")]
//RU: Выводит список команд
public async Task Helpsync()
{
var sb = new StringBuilder();
foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
{
if (!(type.IsClreplaced && type.IsSubclreplacedOf(typeof(ModuleBase<SocketCommandContext>))))
{
continue;
}
foreach (var method in type.GetMethods().Where(x => x.IsPublic && x.GetCustomAttribute<CommandAttribute>() != null && x.GetCustomAttribute<CommandAttribute>() != null))
{
DescriptionAttribute desc = method.GetCustomAttribute<DescriptionAttribute>();
CommandAttribute cmd = method.GetCustomAttribute<CommandAttribute>();
if (!string.IsNullOrEmpty(desc.Description))
{
// !OC help:
sb.Append(Program.PX + ' ');
sb.Append(cmd.Text);
sb.Append(": ");
sb.Append(desc.Description);
sb.AppendLine();
}
}
}
await ReplyAsync(sb.ToString());
}
19
View Source File : RectangleSelection.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
public override string GetText()
{
StringBuilder b = new StringBuilder();
foreach (ISegment s in this.Segments) {
if (b.Length > 0)
b.AppendLine();
b.Append(doreplacedent.GetText(s));
}
return b.ToString();
}
19
View Source File : AwaiterExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static string GenerateObjectTraceMessage(List<Type> objTrace)
{
var result = new StringBuilder();
foreach (var objType in objTrace)
{
if (result.Length != 0)
{
result.Append(" -> ");
}
result.Append(objType);
}
result.AppendLine();
return $"Unity Coroutine Object Trace: {result}";
}
19
View Source File : TriDiagonalMatrix.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public string ToDisplayString(string fmt = "", string prefix = "")
{
if (this.N > 0)
{
var s = new StringBuilder();
string formatString = "{0" + fmt + "}";
for (int r = 0; r < N; r++)
{
s.Append(prefix);
for (int c = 0; c < N; c++)
{
s.AppendFormat(formatString, this[r, c]);
if (c < N - 1) s.Append(", ");
}
s.AppendLine();
}
return s.ToString();
}
else
{
return prefix + "0x0 Matrix";
}
}
19
View Source File : LanguageCompiler.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static void CompileRule(LanguageRule languageRule,
StringBuilder regex,
ICollection<string> captures,
bool isFirstRule)
{
if (!isFirstRule)
{
regex.AppendLine();
regex.AppendLine();
regex.AppendLine("|");
regex.AppendLine();
}
regex.AppendFormat("(?-xis)(?m)({0})(?x)", languageRule.Regex);
int numberOfCaptures = GetNumberOfCaptures(languageRule.Regex);
for (int i = 0; i <= numberOfCaptures; i++)
{
string scope = null;
foreach (int captureIndex in languageRule.Captures.Keys)
{
if (i == captureIndex)
{
scope = languageRule.Captures[captureIndex];
break;
}
}
captures.Add(scope);
}
}
19
View Source File : CustomTextReporter.cs
License : Microsoft Public License
Project Creator : achimismaili
License : Microsoft Public License
Project Creator : achimismaili
public void Process(Story story)
{
// use this report only for tic tac toe stories
if (story.Metadata == null || !story.Metadata.Type.Name.Contains("TicTacToe"))
return;
var scenario = story.Scenarios.First();
var scenarioReport = new StringBuilder();
scenarioReport.AppendLine(string.Format(" SCENARIO: {0} ", scenario.replacedle));
if (scenario.Result != Result.Preplaceded && scenario.Steps.Any(s => s.Exception != null))
{
scenarioReport.Append(string.Format(" {0} : ", scenario.Result));
scenarioReport.AppendLine(scenario.Steps.First(s => s.Result == scenario.Result).Exception.Message);
}
scenarioReport.AppendLine();
foreach (var step in scenario.Steps)
scenarioReport.AppendLine(string.Format(" [{1}] {0}", step.replacedle, step.Result));
scenarioReport.AppendLine("--------------------------------------------------------------------------------");
scenarioReport.AppendLine();
File.AppendAllText(Path, scenarioReport.ToString());
}
19
View Source File : ExportLog.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
private void AddLogItem(string msg)
{
fullLog.Append(msg).AppendLine();
}
19
View Source File : CmdLineActions.cs
License : MIT License
Project Creator : action-bi-toolkit
License : MIT License
Project Creator : action-bi-toolkit
[ArgActionMethod, ArgShortcut("export-usage"), OmitFromUsageDocs]
public void ExportUsage(
[ArgDescription("The optional path to a file to write into. Prints to console if not provided.")] string outPath
)
{
var sb = new StringBuilder();
var definitions = CmdLineArgumentsDefinitionExtensions.For<CmdLineActions>().RemoveAutoAliases();
sb.AppendLine("## Usage");
sb.AppendLine();
sb.AppendLine($" {definitions.UsageSummary}");
sb.AppendLine();
sb.AppendLine($"_{definitions.Description}_");
sb.AppendLine();
sb.AppendLine("### Actions");
sb.AppendLine();
foreach (var action in definitions.UsageActions)
{
sb.AppendLine($"#### {action.DefaultAlias}");
sb.AppendLine();
sb.AppendLine($" {action.UsageSummary}");
sb.AppendLine();
sb.AppendLine(action.Description);
sb.AppendLine();
if (action.HasArguments)
{
sb.AppendLine("| Option | Default Value | Is Switch | Description |");
sb.AppendLine("| --- | --- | --- | --- |");
foreach (var arg in action.UsageArguments.Where(a => !a.OmitFromUsage))
{
var enumValues = arg.EnumValuesAndDescriptions.Aggregate(new StringBuilder(), (sb, fullDescr) => {
var pos = fullDescr.IndexOf(" - ");
var value = fullDescr.Substring(0, pos);
var descr = fullDescr.Substring(pos);
sb.Append($" <br> `{value}` {descr}");
return sb;
});
sb.AppendLine($"| {arg.DefaultAlias}{(arg.IsRequired ? "*" : "")} | {(arg.HasDefaultValue ? $"`{arg.DefaultValue}`" : "")} | {(arg.ArgumentType == typeof(bool) ? "X" : "")} | {arg.Description}{enumValues} |");
}
sb.AppendLine();
}
if (action.HasExamples)
{
foreach (var example in action.Examples)
{
if (example.Hasreplacedle)
{
sb.AppendLine($"**{example.replacedle}**");
sb.AppendLine();
}
sb.AppendLine($" {example.Example}");
sb.AppendLine();
sb.AppendLine($"_{example.Description}_");
sb.AppendLine();
}
}
}
if (String.IsNullOrEmpty(outPath))
{
using (_appSettings.SuppressConsoleLogs())
{
Console.WriteLine(sb.ToString());
}
}
else
{
using (var writer = File.CreateText(outPath))
{
writer.Write(sb.ToString());
}
}
}
19
View Source File : TemplateUnraveler.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private String DumpState()
{
var result = new StringBuilder();
if (m_current == null)
{
result.AppendLine("State: (null)");
}
else
{
result.AppendLine("State:");
result.AppendLine();
// Push state hierarchy
var stack = new Stack<ReaderState>();
var curr = m_current;
while (curr != null)
{
result.AppendLine(curr.ToString());
curr = curr.Parent;
}
}
return result.ToString();
}
19
View Source File : VBExpressionEditorSyntaxLanguage.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : Actipro
public string GetHeaderText(IEnumerable<ModelItem> variableModels) {
// Inject namespace imports
var headerText = new StringBuilder();
headerText.AppendLine(@"Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Linq");
// NOTE: Automated IntelliPrompt will only show for namespaces and types that are within the imported namespaces...
// Add other namespace imports here if types from other namespaces should be accessible
// Inject a Clreplaced and Sub wrapper
headerText.AppendLine();
headerText.AppendLine(@"Shared Clreplaced Expression
Shared Sub ExpressionValue");
// Append variable declarations so they appear in IntelliPrompt
if (variableModels != null) {
foreach (var variableModel in variableModels) {
if (variableModel != null) {
var variable = variableModel.GetCurrentValue() as LocationReference;
if (variable != null) {
// Build a VB representation of the variable's type name
var variableTypeName = new StringBuilder();
AppendTypeName(variableTypeName, variable.Type);
headerText.Append("Dim ");
headerText.Append(variable.Name);
headerText.Append(" As ");
headerText.Append(variableTypeName.Replace("[", "(").Replace("]", ")"));
headerText.AppendLine();
}
}
}
}
// Since the doreplacedent text is an expression, inject a Return statement start at the end of the header text
headerText.AppendLine();
headerText.Append("Return ");
return headerText.ToString();
}
19
View Source File : DiagnosticVerifier.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private static string FormatDiagnostics(Diagnosticreplacedyzer replacedyzer, params Diagnostic[] diagnostics)
{
var builder = new StringBuilder();
for (int i = 0; i < diagnostics.Length; ++i)
{
builder.AppendLine("// " + diagnostics[i].ToString());
var replacedyzerType = replacedyzer.GetType();
var rules = replacedyzer.SupportedDiagnostics;
foreach (var rule in rules)
{
if (rule != null && rule.Id == diagnostics[i].Id)
{
var location = diagnostics[i].Location;
if (location == Location.None)
{
builder.AppendFormat("GetGlobalResult({0}.{1})", replacedyzerType.Name, rule.Id);
}
else
{
replacedert.True(location.IsInSource,
$"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostics[i]}\r\n");
string resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs") ? "GetCSharpResultAt" : "GetBasicResultAt";
var linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition;
builder.AppendFormat("{0}({1}, {2}, {3}.{4})",
resultMethodName,
linePosition.Line + 1,
linePosition.Character + 1,
replacedyzerType.Name,
rule.Id);
}
if (i != diagnostics.Length - 1)
{
builder.Append(',');
}
builder.AppendLine();
break;
}
}
}
return builder.ToString();
}
19
View Source File : ChildrenCodeTemplate.cs
License : MIT License
Project Creator : adamant
License : MIT License
Project Creator : adamant
public void WriteLine(string textToAppend)
{
this.Write(textToAppend);
this.GenerationEnvironment.AppendLine();
this.endsWithNewline = true;
}
19
View Source File : FileLogEntryTextBuilder.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
protected virtual void AppendLogScopeInfo(StringBuilder sb, IExternalScopeProvider scopeProvider)
{
var initialLength = sb.Length;
scopeProvider.ForEachScope((scope, state) =>
{
(StringBuilder builder, int length) = state;
var first = length == builder.Length;
if (!first)
builder.Append(' ');
AppendLogScope(builder, scope);
}, (sb, initialLength));
if (sb.Length > initialLength)
{
sb.Insert(initialLength, _messagePadding);
sb.AppendLine();
}
}
19
View Source File : FindSquares.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
public static GNFS FindSquares(CancellationToken cancelToken, GNFS gnfs)
{
if (cancelToken.IsCancellationRequested)
{
return gnfs;
}
Logging.LogMessage();
Logging.LogMessage($"# of solution sets: {gnfs.CurrentRelationsProgress.FreeRelations.Count}");
Logging.LogMessage();
BigInteger polyBase = gnfs.PolynomialBase;
List<List<Relation>> freeRelations = gnfs.CurrentRelationsProgress.FreeRelations;
int freeRelationIndex = 0;
bool solutionFound = false;
// Below randomly selects a solution set to try and find a square root of the polynomial in.
// Each time this step is stopped and restarted, it will try a different solution set.
// Previous used sets are tracked with the List<int> triedFreeRelationIndices
while (!solutionFound)
{
if (triedFreeRelationIndices.Count == freeRelations.Count) // If we have exhausted our solution sets, alert the user. Number wont factor for some reason.
{
Logging.LogMessage("ERROR: ALL RELATION SETS HAVE BEEN TRIED...?");
Logging.LogMessage($"If the number of solution sets ({freeRelations.Count}) is low, you may need to sieve some more and then re-run the matrix solving step.");
Logging.LogMessage("If there are many solution sets, and you have tried them all without finding non-trivial factors, then something is wrong...");
Logging.LogMessage();
return gnfs;
}
do
{
freeRelationIndex = StaticRandom.Next(0, freeRelations.Count);
}
while (triedFreeRelationIndices.Contains(freeRelationIndex));
triedFreeRelationIndices.Add(freeRelationIndex); // Add current selection to our list
List<Relation> selectedRelationSet = freeRelations[freeRelationIndex]; // Get the solution set
SquareFinder squareRootFinder = new SquareFinder(gnfs, selectedRelationSet); // If you want to solve for a new solution set, create a new instance
Logging.LogMessage($"Selected solution set # {freeRelationIndex + 1}");
Logging.LogMessage();
Logging.LogMessage($"Selected set (a,b) pairs (count: {selectedRelationSet.Count}): {string.Join(" ", selectedRelationSet.Select(rel => $"({rel.A},{rel.B})"))}");
Logging.LogMessage();
Logging.LogMessage();
Logging.LogMessage();
Logging.LogMessage($"ƒ'(m) = {squareRootFinder.PolynomialDerivative}");
Logging.LogMessage($"ƒ'(m)^2 = {squareRootFinder.PolynomialDerivativeSquared}");
Logging.LogMessage();
Logging.LogMessage("Calculating Rational Square Root.");
Logging.LogMessage("Please wait...");
squareRootFinder.CalculateRationalSide();
Logging.LogMessage("Completed.");
Logging.LogMessage();
Logging.LogMessage($"γ² = {squareRootFinder.RationalProduct} IsSquare? {squareRootFinder.RationalProduct.IsSquare()}");
Logging.LogMessage($"(γ · ƒ'(m))^2 = {squareRootFinder.RationalSquare} IsSquare? {squareRootFinder.RationalSquare.IsSquare()}");
Logging.LogMessage();
Logging.LogMessage();
Logging.LogMessage("Calculating Algebraic Square Root.");
Logging.LogMessage("Please wait...");
Tuple<BigInteger, BigInteger> foundFactors = squareRootFinder.CalculateAlgebraicSide(cancelToken);
BigInteger P = foundFactors.Item1;
BigInteger Q = foundFactors.Item2;
if (cancelToken.IsCancellationRequested && P == 1 && Q == 1)
{
Logging.LogMessage("Square root search aborted!");
return gnfs;
}
bool nonTrivialFactorsFound = (P != 1 || Q != 1);
if (!nonTrivialFactorsFound)
{
Logging.LogMessage();
Logging.LogMessage("Unable to locate a square root in solution set!");
Logging.LogMessage();
Logging.LogMessage("Trying a different solution set...");
Logging.LogMessage();
continue;
}
else
{
solutionFound = true;
}
Logging.LogMessage("NON-TRIVIAL FACTORS FOUND!");
Logging.LogMessage();
Polynomial S = squareRootFinder.S;
Polynomial SRingSquare = squareRootFinder.SRingSquare;
BigInteger prodS = SRingSquare.Evaluate(polyBase);
Polynomial reducedS = Polynomial.Field.Modulus(S, gnfs.N);
BigInteger totalProdS = squareRootFinder.TotalS.Evaluate(polyBase) * squareRootFinder.PolynomialDerivative;
BigInteger totalProdModN = totalProdS % gnfs.N;
BigInteger prodSmodN = prodS % gnfs.N;
List<BigInteger> algebraicNumberFieldSquareRoots = squareRootFinder.AlgebraicResults;
BigInteger rationalSquareRoot = squareRootFinder.RationalSquareRootResidue;
BigInteger algebraicSquareRoot = squareRootFinder.AlgebraicSquareRootResidue;
Logging.LogMessage($"∏ Sᵢ =");
Logging.LogMessage($"{squareRootFinder.TotalS}");
Logging.LogMessage();
Logging.LogMessage($"∏ Sᵢ (mod ƒ) =");
Logging.LogMessage($"{reducedS}");
Logging.LogMessage();
Logging.LogMessage("Polynomial ring:");
Logging.LogMessage($"({string.Join(") * (", squareRootFinder.PolynomialRing.Select(ply => ply.ToString()))})");
Logging.LogMessage();
Logging.LogMessage("Primes:");
Logging.LogMessage($"{string.Join(" * ", squareRootFinder.AlgebraicPrimes)}"); // .RelationsSet.Select(rel => rel.B).Distinct().OrderBy(relB => relB))
Logging.LogMessage();
Logging.LogMessage();
Logging.LogMessage($"X² / ƒ(m) = {squareRootFinder.AlgebraicProductModF} IsSquare? {squareRootFinder.AlgebraicProductModF.IsSquare()}");
Logging.LogMessage();
Logging.LogMessage($"");
Logging.LogMessage($"AlgebraicPrimes: {squareRootFinder.AlgebraicPrimes.FormatString(false)}");
Logging.LogMessage($"AlgebraicResults: {squareRootFinder.AlgebraicResults.FormatString(false)}");
Logging.LogMessage($"");
Logging.LogMessage($"*****************************");
Logging.LogMessage($"");
Logging.LogMessage($"AlgebraicSquareRootResidue: {squareRootFinder.AlgebraicSquareRootResidue}");
Logging.LogMessage($"");
Logging.LogMessage($"AlgebraicNumberFieldSquareRoots: {algebraicNumberFieldSquareRoots.FormatString(false)}");
Logging.LogMessage($"");
Logging.LogMessage($" RationalSquareRoot : {rationalSquareRoot}");
Logging.LogMessage($" AlgebraicSquareRoot: {algebraicSquareRoot} ");
Logging.LogMessage($"");
Logging.LogMessage($"*****************************");
Logging.LogMessage($"S (x) = {prodSmodN} IsSquare? {prodSmodN.IsSquare()}");
Logging.LogMessage();
Logging.LogMessage("Roots of S(x):");
Logging.LogMessage($"{{{string.Join(", ", squareRootFinder.RootsOfS.Select(tup => (tup.Item2 > 1) ? $"{tup.Item1}/{tup.Item2}" : $"{tup.Item1}"))}}}");
Logging.LogMessage();
Logging.LogMessage();
Logging.LogMessage($"TTL: {totalProdS} IsSquare? {totalProdS.IsSquare()}");
Logging.LogMessage($"TTL%N: {totalProdModN} IsSquare? {totalProdModN.IsSquare()}");
//Logging.LogMessage();
//Logging.LogMessage($"∏(a + mb) = {squareRootFinder.RationalProduct}");
//Logging.LogMessage($"∏ƒ(a/b) = {squareRootFinder.AlgebraicProduct}");
Logging.LogMessage("-------------------------------------------");
Logging.LogMessage();
Logging.LogMessage();
Logging.LogMessage($"RationalSquareRootResidue: = {squareRootFinder.RationalSquareRootResidue} IsSquare? {squareRootFinder.RationalSquareRootResidue.IsSquare()}");
Logging.LogMessage($"AlgebraicSquareRootResidue: = {squareRootFinder.AlgebraicSquareRootResidue} IsSquare? {squareRootFinder.RationalSquareRootResidue.IsSquare()}");
Logging.LogMessage();
Logging.LogMessage();
/* Non-trivial factors also recoverable by doing the following:
BigInteger min = BigInteger.Min(squareRootFinder.RationalSquareRootResidue, squareRootFinder.AlgebraicSquareRootResidue);
BigInteger max = BigInteger.Max(squareRootFinder.RationalSquareRootResidue, squareRootFinder.AlgebraicSquareRootResidue);
BigInteger A = max + min;
BigInteger B = max - min;
BigInteger P = GCD.FindGCD(gnfs.N, A);
BigInteger Q = GCD.FindGCD(gnfs.N, B);
*/
StringBuilder sb = new StringBuilder();
sb.AppendLine($"N = {gnfs.N}");
sb.AppendLine();
sb.AppendLine($"P = {BigInteger.Max(P, Q)}");
sb.AppendLine($"Q = {BigInteger.Min(P, Q)}");
sb.AppendLine();
string path = Path.Combine(gnfs.SaveLocations.SaveDirectory, "Solution.txt");
File.WriteAllText(path, sb.ToString());
Logging.LogMessage();
Logging.LogMessage(Environment.NewLine + sb.ToString());
}
return gnfs;
}
19
View Source File : PolyRelationsSieveProgress.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
public override string ToString()
{
if (Relations.FreeRelations.Any())
{
StringBuilder result = new StringBuilder();
List<Relation> relations = Relations.FreeRelations.First();
result.AppendLine(FormatRelations(relations));
BigInteger algebraic = relations.Select(rel => rel.AlgebraicNorm).Product();
BigInteger rational = relations.Select(rel => rel.RationalNorm).Product();
bool isAlgebraicSquare = algebraic.IsSquare();
bool isRationalSquare = rational.IsSquare();
CountDictionary algCountDict = new CountDictionary();
foreach (Relation rel in relations)
{
algCountDict.Combine(rel.AlgebraicFactorization);
}
result.AppendLine("---");
result.AppendLine($"Rational ∏(a+mb): IsSquare? {isRationalSquare} : {rational}");
result.AppendLine($"Algebraic ∏ƒ(a/b): IsSquare? {isAlgebraicSquare} : {algebraic}");
result.AppendLine();
result.AppendLine($"Algebraic factorization (as prime ideals): {algCountDict.FormatStringAsFactorization()}");
result.AppendLine();
result.AppendLine();
result.AppendLine("");
result.AppendLine(string.Join(Environment.NewLine,
relations.Select(rel =>
{
BigInteger f = _gnfs.CurrentPolynomial.Evaluate((BigInteger)rel.A);
if (rel.B == 0)
{
return "";
}
return $"ƒ({rel.A}) ≡ {f} ≡ {(f % rel.B)} (mod {rel.B})";
}
)));
result.AppendLine();
return result.ToString();
}
else
{
return FormatRelations(Relations.SmoothRelations);
}
}
19
View Source File : SquareFinder.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
public override string ToString()
{
StringBuilder result = new StringBuilder();
result.AppendLine($"IsRationalIrreducible ? {IsRationalIrreducible}");
result.AppendLine($"IsAlgebraicIrreducible ? {IsAlgebraicIrreducible}");
result.AppendLine("Square finder, Rational:");
result.AppendLine($"γ² = √( Sᵣ(m) * ƒ'(m)² )");
result.AppendLine($"γ² = √( {RationalProduct} * {PolynomialDerivativeSquared} )");
result.AppendLine($"γ² = √( {RationalSquare} )");
result.AppendLine($"γ = {RationalSquareRootResidue} mod N"); // δ mod N
result.AppendLine();
result.AppendLine();
result.AppendLine("Square finder, Algebraic:");
result.AppendLine($" Sₐ(m) * ƒ'(m) = {AlgebraicProduct} * {PolynomialDerivative}");
result.AppendLine($" Sₐ(m) * ƒ'(m) = {AlgebraicSquare}");
result.AppendLine($"χ = Sₐ(m) * ƒ'(m) mod N = {AlgebraicSquareRootResidue}");
result.AppendLine($"γ = {RationalSquareRootResidue}");
result.AppendLine($"χ = {AlgebraicSquareRootResidue}");
result.AppendLine($"IsRationalSquare ? {IsRationalSquare}");
result.AppendLine($"IsAlgebraicSquare ? {IsAlgebraicSquare}");
BigInteger min = BigInteger.Min(RationalSquareRootResidue, AlgebraicSquareRootResidue);
BigInteger max = BigInteger.Max(RationalSquareRootResidue, AlgebraicSquareRootResidue);
BigInteger add = max + min;
BigInteger sub = max - min;
BigInteger gcdAdd = GCD.FindGCD(N, add);
BigInteger gcdSub = GCD.FindGCD(N, sub);
BigInteger answer = BigInteger.Max(gcdAdd, gcdSub);
result.AppendLine();
result.AppendLine($"GCD(N, γ+χ) = {gcdAdd}");
result.AppendLine($"GCD(N, γ-χ) = {gcdSub}");
result.AppendLine();
result.AppendLine($"Solution? {(answer != 1).ToString().ToUpper()}");
if (answer != 1)
{
result.AppendLine();
result.AppendLine();
result.AppendLine("*********************");
result.AppendLine();
result.AppendLine($" SOLUTION = {answer} ");
result.AppendLine();
result.AppendLine("*********************");
result.AppendLine();
result.AppendLine();
}
result.AppendLine();
return result.ToString();
}
19
View Source File : GNFS.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
public override string ToString()
{
StringBuilder result = new StringBuilder();
result.AppendLine($"N = {N}");
result.AppendLine();
result.AppendLine($"Polynomial(degree: {PolynomialDegree}, base: {PolynomialBase}):");
result.AppendLine("ƒ(m) = " + CurrentPolynomial.ToString());
result.AppendLine();
result.AppendLine("Prime Factor Base Bounds:");
result.AppendLine($"RationalFactorBase : {PrimeFactorBase.RationalFactorBaseMax}");
result.AppendLine($"AlgebraicFactorBase: {PrimeFactorBase.AlgebraicFactorBaseMax}");
result.AppendLine($"QuadraticPrimeBase Range: {PrimeFactorBase.QuadraticFactorBaseMin} - {PrimeFactorBase.QuadraticFactorBaseMax}");
result.AppendLine($"QuadraticPrimeBase Count: {PrimeFactorBase.QuadraticBaseCount}");
result.AppendLine();
result.AppendLine($"RFB - Rational Factor Base - Count: {RationalFactorPairCollection.Count} - Array of (p, m % p) with prime p");
result.AppendLine(RationalFactorPairCollection.ToString(200));
result.AppendLine();
result.AppendLine($"AFB - Algebraic Factor Base - Count: {AlgebraicFactorPairCollection.Count} - Array of (p, r) such that ƒ(r) ≡ 0 (mod p) and p is prime");
result.AppendLine(AlgebraicFactorPairCollection.ToString(200));
result.AppendLine();
result.AppendLine($"QFB - Quadratic Factor Base - Count: {QuadraticFactorPairCollection.Count} - Array of (p, r) such that ƒ(r) ≡ 0 (mod p) and p is prime");
result.AppendLine(QuadraticFactorPairCollection.ToString());
result.AppendLine();
result.AppendLine();
result.AppendLine();
return result.ToString();
}
See More Examples