当前位置:网站首页>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
边栏推荐
- dc_ Study and summary of labs--lab1
- Construction and beautification of personal blog
- Open3d point cloud color rendering
- 【模拟】922. Sort Array By Parity II
- 二季度最后一天
- Install redis database and download redis Desktop Manager in win11
- StrictMode带来的思考-StrictMode原理(5)
- 【Qt5-基础篇_1】从0开始,德天老师和你一起学习——窗口简介
- 基础知识之二——STA相关的基本定义
- Understanding and application of Qt5 layout in creation
猜你喜欢

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"?

未来的 Web3会带来什么?

物业怎么发短信通知给业主?

Neo4j installation, operation, project construction and function realization

Using recyclerreview to show banner is very simple

微研所,微生物检验中常用的生化反应

New opportunities for vr/ar brought by metauniverse

基础知识之一——STA基础概述

编译安装oh-my-zsh

用recyclerReview展示Banner,很简单
随机推荐
Why not two or four TCP handshakes
gin_ gorm
DC學習筆記正式篇之零——綜述與基本流程介紹
Koa koa combine routes sub route management
用recyclerReview展示Banner,很简单
ASCII、Unicode、GBK、UTF-8之间的关系
微研所,微生物检验中常用的生化反应
[problem handled] -nvidia SMI command cannot obtain the GPU process number of its own container and the external GPU process number
Zero of DC learning notes -- overview and basic process introduction
迪赛智慧数——其他图表(平行坐标图):2021年应届专业就业情况
小程序自定义宫格
使用 C# 创造 ASCII 艺术
Introduction and principle analysis of cluster and LVS
The argument type 'function' can't be assigned to the parameter type 'void function()‘
Use strictmode strictmode principle (1)
【Qt5-基础篇】随机数显示屏展示
Why build a personal blog
New opportunities for vr/ar brought by metauniverse
Note d'étude du DC: zéro dans le chapitre officiel - - Aperçu et introduction du processus de base
【模拟】922. Sort Array By Parity II