当前位置:网站首页>System. Csrebot for commandline
System. Csrebot for commandline
2022-07-01 01:33:00 【Dotnet cross platform】
I have implemented one before CSRebot Command line tools , Now use System.CommandLine To achieve , It's much more standardized and convenient , although System.CommandLine Not officially released yet , But its implementation idea is still very good .
The following code simply implements MSSQL Library generation C# Functions of body classes , Entity class generation from other libraries or languages , You can realize it yourself , To become familiar with System.CommandLine Use .
Go straight to the code :
using Microsoft.Data.SqlClient;
using System.CommandLine;
using System.CommandLine.Binding;
using System.Data;
using System.Text;
using System;
// Create root command
var rootCommand = new RootCommand(" This is a paragraph C# Development AIDS ,CSRebot");
rootCommand.SetHandler(() =>
{
Console.WriteLine(" Lao GUI welcomes you to use CSRebot!");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\r\n ___________ ____ __ __ \r\n / ____/ ___// __ \\___ / /_ ____ / /_\r\n / / \\__ \\/ /_/ / _ \\/ __ \\/ __ \\/ __/\r\n/ /___ ___/ / _, _/ __/ /_/ / /_/ / /_ \r\n\\____//____/_/ |_|\\___/_.___/\\____/\\__/ \r\n \r\n");
Console.ResetColor();
Console.WriteLine("help command:csrebot -h");
Console.WriteLine();
});
// Create subcommands show
var dbtoCommand = new Command("dbto", " Generation from database ");
#region Options language
// Create subcommand options language Alias lan
var languageOption = new Option<string>(name: "--language", description: " A language for generating entity classes from a database ")
{
IsRequired = true,
}.FromAmong("c#", "C#", "csharp", "CSharp", "go", "GO", "java", "JAVA");
languageOption.AddAlias("-lan");
languageOption.AddAlias("-l");
// add to language Options to dbto In command
dbtoCommand.AddOption(languageOption);
#endregion
#region connestionString
// Create subcommand options connestionString Alias constr
var connectionStringOption = new Option<string>(name: "--connectionstring", description: " Database connection string ")
{
IsRequired = true,
};
connectionStringOption.AddAlias("-constr");
// add to language Options to dbto In command
dbtoCommand.AddOption(connectionStringOption);
#endregion
#region dbtype
// Create subcommand options connestionString Alias constr
var dbTypeOption = new Option<string>(name: "--dbtype", description: " Database type ")
{
IsRequired = true,
}.FromAmong("mssql", "mysql", "pgsql"); ;
dbTypeOption.AddAlias("-dbt");
dbTypeOption.AddAlias("-t");
// add to language Options to dbto In command
dbtoCommand.AddOption(dbTypeOption);
#endregion
// Set command dbto The action performed , This is to take language Parameters
dbtoCommand.SetHandler(async (string language, string connectionstring, string dbType) =>
{
switch (language.ToLower())
{
case "c#":
case "csharp":
await DBToCSharpAsync(connectionstring, dbType);
break;
case "go":
break;
case "java":
break;
default:
break;
}
}, languageOption, connectionStringOption, dbTypeOption);
// Add command dbto To In the root command
rootCommand.Add(dbtoCommand);
await rootCommand.InvokeAsync(args);
static async Task DBToCSharpAsync(string connectionString, string dbType)
{
switch (dbType.ToLower())
{
case "mssql":
await MSSQLToCSharpAsync(connectionString);
break;
default:
break;
}
}
static async Task MSSQLToCSharpAsync(string connectionString)
{
using var con = new SqlConnection(connectionString);
using var cmd = new SqlCommand("select name from sysobjects where xtype='U'", con);
await con.OpenAsync();
using var reader = await cmd.ExecuteReaderAsync();
var tableNames = new List<string>();
while (reader.Read())
{
tableNames.Add(reader.GetString(0));
}
await reader.CloseAsync();
var dbPath = $"{Environment.CurrentDirectory}\\{con.Database}";
if (!Directory.Exists(dbPath))
{
Directory.CreateDirectory(dbPath);
}
foreach (var tableName in tableNames)
{
using var fileCmd = new SqlCommand("SELECT syscolumns.name,systypes.name as typename FROM syscolumns, systypes WHERE syscolumns.xusertype = systypes.xusertype AND syscolumns.id = object_id(@tablename)", con);
fileCmd.Parameters.Add("tablename", SqlDbType.VarChar).Value = tableName;
using var fileReader = await fileCmd.ExecuteReaderAsync();
var tablefieldses = new List<dynamic>();
while (fileReader.Read())
{
tablefieldses.Add(new { name = fileReader.GetString(0), typename = fileReader.GetString(1) });
}
fileReader.Close();
await fileReader.DisposeAsync();
var csBuilder = new StringBuilder();
csBuilder.AppendLine($"public class {tableName}");
csBuilder.AppendLine("{");
foreach (var tablefields in tablefieldses)
{
var typeName = TypeMap.MSSQLToCSharp[tablefields.typename];
var name = tablefields.name;
csBuilder.AppendLine($" public {typeName} {name}{
{get;set;}}");
}
csBuilder.AppendLine("}");
File.WriteAllText($"{dbPath}\\{tableName}.cs", csBuilder.ToString(), Encoding.UTF8);
}
}
static class TypeMap
{
internal static Dictionary<string, string> MSSQLToCSharp => new Dictionary<string, string>
{
{"bigint","long"},
{"binary","byte[]"},
{"bit","bool"},
{"char","string"},
{"date","DateTime"},
{"datetime","DateTime"},
{"datetime2","DateTime"},
{"datetimeoffset","DateTimeOffset" },
{"decimal","decimal" },
{"float","double" },
{"image","byte[]" },
{"int","int" },
{"money","decimal" },
{"nchar","string" },
{"ntext","string" },
{"numeric","decimal" },
{"nvarchar","string" },
{"real","float" },
{"rowversion","byte[]" },
{"smalldatetime","DateTime" },
{"smallint","short" },
{"smallmoney","decimal" },
{"sql_variant","object"},
{"text","string" },
{"time","TimeSpan" },
{"timestamp","byte[]" },
{"tinyint","byte" },
{"uniqueidentifier","Guid" },
{"varbinary","byte[]" },
{"varchar","string" },
};
internal static Dictionary<string, string> MySQLToCSharp => new Dictionary<string, string>
{
{"","" }
};
internal static Dictionary<string, string> PgSQLToCSharp => new Dictionary<string, string>
{
{"","" }
};
}install CSRebot
After completion , Select items and package , Then enter all folders of the project and execute the tool installation command
dotnet tool install -g --add-source ./nupkg CSRebot
test
csrebot dbto -l C# -constr 'server=localhost;database= Library name ;uid= user name ;pwd= password ;encrypt=true;trustservercertificate=true' -t mssql
边栏推荐
- Green, green the reed. dew and frost gleam.
- [Qt5 basic \u 1] starting from 0, Mr. Detian will study with you - Introduction to the window
- Use of typora
- [problem handled] -nvidia SMI command cannot obtain the GPU process number of its own container and the external GPU process number
- 使用 C# 创造 ASCII 艺术
- Document service design
- 面对产业互联网的时候,甚至还用消费互联网的方式和方法去落地和实践产业互联网
- C# 自定义并动态切换光标
- Uniapp official component clicking item is invalid, solution
- JS方法大全的一个小文档
猜你喜欢

Q play soft large toast to bring more comfortable sleep

Basic knowledge II - Basic definitions related to sta

一站式洞察行业热点,飞瓜数据B站新功能「流量大盘」上线!

流批一体在京东的探索与实践

Construction and beautification of personal blog

gin_gorm
![[network packet loss and network delay? This artifact can help you deal with everything!]](/img/c4/f733b23327458b9266b9cbcccb6f14.png)
[network packet loss and network delay? This artifact can help you deal with everything!]

软件开发完整流程

dc_ Study and summary of labs--lab1

Call the classic architecture and build the model based on the classic
随机推荐
微生物安全與健康,什麼是生物處理?
06. on several ways of redis persistence
The liquor and tourism sector recovers, and Yaduo continues to dream of listing. How far is it from "the first share of the new accommodation economy"?
3dsmax插件开发遍历节点对象和Object获取及INode变换矩阵说明
None of the following candidates is applicable because of a receiver type mismatch
gin 配置文件
[problem handled] -nvidia SMI command cannot obtain the GPU process number of its own container and the external GPU process number
【模拟】922. Sort Array By Parity II
直播商城源码,实现左右联动商品分类页面
DC學習筆記正式篇之零——綜述與基本流程介紹
物业怎么发短信通知给业主?
【队列】933. Number of Recent Calls
Call the classic architecture and build the model based on the classic
6月第4周榜单丨飞瓜数据UP主成长排行榜(哔哩哔哩平台)发布!
使用StrictMode-StrictMode原理(1)
Open3D 点云包围盒
Note d'étude du DC: zéro dans le chapitre officiel - - Aperçu et introduction du processus de base
一站式洞察行业热点,飞瓜数据B站新功能「流量大盘」上线!
Interpreting the scientific and technological literacy contained in maker Education
C语言一点点(未来可会增加)