public string Render(List <LogItem> logs, string title)
        {
            RazorModel model = new RazorModel
            {
                CaptureDate   = DateTime.UtcNow,
                TotalDuration = logs.Count == 0 ? TimeSpan.MinValue : logs.Last().ServerTime - logs.First().ServerTime,
                Title         = title,
                Logs          = logs,
                RequestsCount = logs.Count(l => l is HttpRequestLog)
            };

#if NET452
            RazorEngine <RazorTemplateBase> engine = new RazorEngine <RazorTemplateBase>();
            engine.AddAssembly("System.Web.dll");

            string html = engine.RenderTemplate(Resources.HtmlLogTemplate, model);
            return(html ?? engine.ErrorMessage);
#else
            var engine = new RazorLight.RazorLightEngineBuilder()
                         .UseMemoryCachingProvider()
                         .Build();

            return(engine.CompileRenderAsync("HtmlLog", Resources.HtmlLogTemplateNetStandard, model).Result);
#endif
        }
Пример #2
0
        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()));
            }
        }
Пример #3
0
        public RazorPageRendererTest()
        {
            Series series = new Series();
            Target target1 = new Target { Name = "TargetA" };
            Target target2 = new Target { Name = "TargetB" };
            List<Target> targets = new List<Target>();
            targets.Add(target1);
            targets.Add(target2);

            model = new RazorModel();
            model.Series = series;
            model.Targets = targets;
        }
        public string Render(List <LogItem> logs, string title, IViewRenderService renderservice)
        {
            RazorModel model = new RazorModel
            {
                CaptureDate   = DateTime.UtcNow,
                TotalDuration = logs.Count == 0 ? TimeSpan.MinValue : logs.Last().ServerTime - logs.First().ServerTime,
                Title         = title,
                Logs          = logs,
                RequestsCount = logs.Count(l => l is HttpRequestLog)
            };

            //var engine = new RazorLight.RazorLightEngineBuilder()
            //    .UseMemoryCachingProvider()
            //    .Build();

            return(renderservice.RenderToString(Resources.HtmlLogTemplate, model.Title, model));
        }
Пример #5
0
        public string Render(List <LogItem> logs, string title)
        {
            RazorModel model = new RazorModel
            {
                CaptureDate   = DateTime.UtcNow,
                TotalDuration = logs.Count == 0 ? TimeSpan.MinValue : logs.Last().ServerTime - logs.First().ServerTime,
                Title         = title,
                Logs          = logs,
                RequestsCount = logs.Count(l => l is HttpRequestLog)
            };

            var engine = new RazorLight.RazorLightEngineBuilder()
                         .UseMemoryCachingProvider()
                         .Build();

            return(engine.CompileRenderAsync("HtmlLog", Resources.HtmlLogTemplate, model).Result);
        }
Пример #6
0
        public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace,
                            IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
        {
            // SwitchDomainForRazorEngine();
            byte[] resultBytes;
            try
            {
                var model = new RazorModel();
                //set file name and namespace for model using
                model.DefaultNameSpace = wszDefaultNamespace;
                var info = new FileInfo(wszInputFilePath);
                if (info.Exists)
                {
                    model.FileName = info.Name;
                }
                int                  iFound;
                uint                 itemId;
                ProjectItem          item;
                VSDOCUMENTPRIORITY[] pdwPriority = new VSDOCUMENTPRIORITY[1];

                // obtain a reference to the current project as an IVsProject type
                IVsProject vsProject = VsHelper.ToVsProject(project);
                // this locates, and returns a handle to our source file, as a ProjectItem
                vsProject.IsDocumentInProject(wszInputFilePath, out iFound, pdwPriority, out itemId);

                // if our source file was found in the project (which it should have been)
                if (iFound != 0 && itemId != 0)
                {
                    IServiceProvider oleSp;
                    vsProject.GetItemContext(itemId, out oleSp);
                    if (oleSp != null)
                    {
                        ServiceProvider sp = new ServiceProvider(oleSp);
                        // convert our handle to a ProjectItem
                        item = sp.GetService(typeof(ProjectItem)) as ProjectItem;
                    }
                    else
                    {
                        throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem");
                    }
                }
                else
                {
                    throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem");
                }

                var generator = new RazorGenerator(wszInputFilePath, bstrInputFileContents, model);
                generator.Init();
                //get extension from header file
                if (!string.IsNullOrEmpty(generator.RazorTemplate.OutPutExtension))
                {
                    _extenstion = generator.RazorTemplate.OutPutExtension;
                }
                //generate code
                var result = generator.Render();
                resultBytes = Encoding.UTF8.GetBytes(result);
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint)outputLength;
                return(VSConstants.S_OK);
            }
            catch (TemplateCompilationException tex)
            {
                //Display error in result template
                foreach (var compilerError in tex.CompilerErrors)
                {
                    pGenerateProgress.GeneratorError(0, 1, compilerError.ErrorText, (uint)compilerError.Line,
                                                     (uint)compilerError.Column);
                }
                var message = MRazorUtil.GetError(tex);
                resultBytes = Encoding.UTF8.GetBytes(message);
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint)outputLength;
                return(VSConstants.S_FALSE);// Change to E_Fail will display error in error list
            }
            catch (Exception ex)
            {
                var messageBuilder = new StringBuilder(ex.Message);
                messageBuilder.AppendLine();
                if (ex.Source != null)
                {
                    messageBuilder.Append(ex.Source);
                }
                messageBuilder.Append(ex.StackTrace);
                if (ex.InnerException != null)
                {
                    messageBuilder.AppendLine();
                    messageBuilder.Append(ex.InnerException.Message + ex.InnerException.StackTrace);
                }
                resultBytes = Encoding.UTF8.GetBytes(messageBuilder.ToString());
                int outputLength = resultBytes.Length;
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(outputLength);
                Marshal.Copy(resultBytes, 0, rgbOutputFileContents[0], outputLength);
                pcbOutput = (uint)outputLength;
                return(VSConstants.S_FALSE);// Change to E_Fail will display error in error list
            }
            //finally
            //{
            //    //unload domain for unload dll loaded from InputDllFolder
            //    if (_domain != null) AppDomain.Unload(_domain);
            //}
        }
Пример #7
0
        public ConsoleApp(string[] args, ManualResetEvent wait)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var gb2312 = Encoding.GetEncoding("GB2312");

            if (gb2312 != null)
            {
                try
                {
                    Console.OutputEncoding = gb2312;
                    Console.InputEncoding  = gb2312;
                }
                catch { }
            }

            //var ntjson = Assembly.LoadFile(@"C:\Users\28810\Desktop\testfreesql\bin\Debug\netcoreapp2.2\publish\testfreesql.dll");

            //using (var gen = new Generator(new GeneratorOptions()))
            //{
            //    gen.TraceLog = log => Console.WriteFormatted(log + "\r\n", Color.DarkGray);
            //    gen.Build(ArgsOutput, new[] { typeof(ojbk.Entities.AuthRole) }, false);
            //}

            var version = "v" + string.Join(".", typeof(ConsoleApp).Assembly.GetName().Version.ToString().Split('.').Where((a, b) => b <= 2));

            Console.WriteAscii(" FreeSql", Color.Violet);
            Console.WriteFormatted(@"
  # Github # {0} {1}
", Color.SlateGray,
                                   new Colorful.Formatter("https://github.com/2881099/FreeSql", Color.DeepSkyBlue),
                                   new Colorful.Formatter("v" + string.Join(".", typeof(ConsoleApp).Assembly.GetName().Version.ToString().Split('.').Where((a, b) => b <= 2)), Color.SlateGray));

            ArgsRazorRaw    = "1";
            ArgsRazor       = RazorContentManager.实体类_特性_cshtml;
            ArgsNameOptions = new[] { false, false, false, false };
            ArgsNameSpace   = "MyProject";
            ArgsFilter      = "";
            ArgsMatch       = "";
            ArgsFileName    = "{name}.cs";
            ArgsReadKey     = true;
            Action <string> setArgsOutput = value =>
            {
                ArgsOutput  = value;
                ArgsOutput  = ArgsOutput.Trim().TrimEnd('/', '\\');
                ArgsOutput += ArgsOutput.Contains("\\") ? "\\" : "/";
                if (!Directory.Exists(ArgsOutput))
                {
                    Directory.CreateDirectory(ArgsOutput);
                }
            };

            setArgsOutput(Directory.GetCurrentDirectory());

            string args0 = args[0].Trim().ToLower();

            if (args[0] == "?" || args0 == "--help" || args0 == "-help")
            {
                Console.WriteFormatted(@"
    {0}

    更新工具:dotnet tool update -g FreeSql.Generator


  # 快速开始 #

  > {1} {2} 1 {3} 0,0,0,0 {4} MyProject {5} ""MySql,Data Source=127.0.0.1;...""

     -Razor 1                  * 选择模板:实体类+特性
     -Razor 2                  * 选择模板:实体类+特性+导航属性
     -Razor ""d:\diy.cshtml""    * 自定义模板文件

     -NameOptions              * 4个布尔值对应:
                                 首字母大写
                                 首字母大写,其他小写
                                 全部小写
                                 下划线转驼峰

     -NameSpace                * 命名空间

     -DB ""{6},data source=127.0.0.1;port=3306;user id=root;password=root;initial catalog=数据库;charset=utf8;sslmode=none;max pool size=2""
     -DB ""{7},data source=.;integrated security=True;initial catalog=数据库;pooling=true;max pool size=2""
     -DB ""{8},host=192.168.164.10;port=5432;username=postgres;password=123456;database=数据库;pooling=true;maximum pool size=2""
     -DB ""{9},user id=user1;password=123456;data source=//127.0.0.1:1521/XE;pooling=true;max pool size=2""
     -DB ""{10},data source=document.db""
     -DB ""{14},database=localhost:D:\fbdata\EXAMPLES.fdb;user=sysdba;password=123456;max pool size=2""
     -DB ""{11},server=127.0.0.1;port=5236;user id=2user;password=123456789;database=2user;poolsize=2""
     -DB ""{12},server=127.0.0.1;port=54321;uid=USER2;pwd=123456789;database=数据库""
     -DB ""{13},host=192.168.164.10;port=2003;database=数据库;username=SYSDBA;password=szoscar55;maxpoolsize=2""
                               * {11}(达梦数据库)、{12}(人大金仓数据库)、{13}(神舟通用数据库)

     -Filter                   Table+View+StoreProcedure
                               默认生成:表+视图+存储过程
                               如果不想生成视图和存储过程 -Filter View+StoreProcedure

     -Match                    表名或正则表达式,只生成匹配的表,如:dbo\.TB_.+

     -FileName                 文件名,默认:{name}.cs
     -Output                   保存路径,默认为当前 shell 所在目录
                               {15}

", Color.SlateGray,
                                       new Colorful.Formatter("FreeSql 快速生成数据库的实体类", Color.SlateGray),
                                       new Colorful.Formatter("FreeSql.Generator", Color.White),
                                       new Colorful.Formatter("-Razor", Color.ForestGreen),
                                       new Colorful.Formatter("-NameOptions", Color.ForestGreen),
                                       new Colorful.Formatter("-NameSpace", Color.ForestGreen),
                                       new Colorful.Formatter("-DB", Color.ForestGreen),
                                       new Colorful.Formatter("MySql", Color.Yellow),
                                       new Colorful.Formatter("SqlServer", Color.Yellow),
                                       new Colorful.Formatter("PostgreSQL", Color.Yellow),
                                       new Colorful.Formatter("Oracle", Color.Yellow),
                                       new Colorful.Formatter("Sqlite", Color.Yellow),
                                       new Colorful.Formatter("Dameng", Color.Yellow),
                                       new Colorful.Formatter("KingbaseES", Color.Yellow),
                                       new Colorful.Formatter("ShenTong", Color.Yellow),
                                       new Colorful.Formatter("Firebird", Color.Yellow),
                                       new Colorful.Formatter("推荐在实体类目录创建 gen.bat,双击它重新所有实体类", Color.ForestGreen)
                                       );
                wait.Set();
                return;
            }
            for (int a = 0; a < args.Length; a++)
            {
                switch (args[a].Trim().ToLower())
                {
                case "-razor":
                    ArgsRazorRaw = args[a + 1].Trim();
                    switch (ArgsRazorRaw)
                    {
                    case "1": ArgsRazor = RazorContentManager.实体类_特性_cshtml; break;

                    case "2": ArgsRazor = RazorContentManager.实体类_特性_导航属性_cshtml; break;

                    default: ArgsRazor = File.ReadAllText(args[a + 1]); break;
                    }
                    a++;
                    break;

                case "-nameoptions":
                    ArgsNameOptions = args[a + 1].Split(',').Select(opt => opt == "1").ToArray();
                    if (ArgsNameOptions.Length != 4)
                    {
                        throw new ArgumentException("-NameOptions 参数错误,格式为:0,0,0,0");
                    }
                    a++;
                    break;

                case "-namespace":
                    ArgsNameSpace = args[a + 1];
                    a++;
                    break;

                case "-db":
                    var dbargs = args[a + 1].Split(',', 2);
                    if (dbargs.Length != 2)
                    {
                        throw new ArgumentException("-DB 参数错误,格式为:MySql,ConnectionString");
                    }
                    switch (dbargs[0].Trim().ToLower())
                    {
                    case "mysql": ArgsDbType = DataType.MySql; break;

                    case "sqlserver": ArgsDbType = DataType.SqlServer; break;

                    case "postgresql": ArgsDbType = DataType.PostgreSQL; break;

                    case "oracle": ArgsDbType = DataType.Oracle; break;

                    case "sqlite": ArgsDbType = DataType.Sqlite; break;

                    case "firebird": ArgsDbType = DataType.Firebird; break;

                    case "dameng": ArgsDbType = DataType.Dameng; break;

                    case "kingbasees": ArgsDbType = DataType.KingbaseES; break;

                    case "shentong": ArgsDbType = DataType.ShenTong; break;

                    case "clickhouse": ArgsDbType = DataType.ClickHouse; break;

                    default: throw new ArgumentException($"-DB 参数错误,不支持的类型:\"{dbargs[0]}\"");
                    }
                    ArgsConnectionString = dbargs[1].Trim();
                    a++;
                    break;

                case "-filter":
                    ArgsFilter = args[a + 1];
                    a++;
                    break;

                case "-match":
                    ArgsMatch = args[a + 1];
                    if (Regex.IsMatch("", ArgsMatch))
                    {
                    }                                         //throw
                    a++;
                    break;

                case "-filename":
                    ArgsFileName = args[a + 1];
                    a++;
                    break;

                case "-readkey":
                    ArgsReadKey = args[a + 1].Trim() == "1";
                    a++;
                    break;

                case "-output":
                    setArgsOutput(args[a + 1]);
                    a++;
                    break;

                default:
                    throw new ArgumentException($"错误的参数设置:{args[a]}");
                }
            }

            if (string.IsNullOrEmpty(ArgsConnectionString))
            {
                throw new ArgumentException($"-DB 参数错误,未提供 ConnectionString");
            }

            RazorEngine.Engine.Razor = RazorEngineService.Create(new RazorEngine.Configuration.TemplateServiceConfiguration
            {
                EncodedStringFactory = new RazorEngine.Text.RawStringFactory() // Raw string encoding.
            });
            var razorId = Guid.NewGuid().ToString("N");

            RazorEngine.Engine.Razor.Compile(ArgsRazor, razorId);

            var outputCounter = 0;

            using (IFreeSql fsql = new FreeSql.FreeSqlBuilder()
                                   .UseConnectionString(ArgsDbType, ArgsConnectionString)
                                   .UseAutoSyncStructure(false)
                                   .UseMonitorCommand(cmd => Console.WriteFormatted(cmd.CommandText + "\r\n", Color.SlateGray))
                                   .Build())
            {
                List <DbTableInfo> tables = new List <DbTableInfo>();
                if (string.IsNullOrEmpty(ArgsMatch) == false)
                {
                    try
                    {
                        var matchTable = fsql.DbFirst.GetTableByName(ArgsMatch);
                        if (matchTable != null)
                        {
                            tables.Add(matchTable);
                        }
                    }
                    catch { }
                }
                if (tables.Any() == false)
                {
                    tables = fsql.DbFirst.GetTablesByDatabase();
                }
                var outputTables = tables;

                //开始生成操作
                foreach (var table in outputTables)
                {
                    if (string.IsNullOrEmpty(ArgsMatch) == false)
                    {
                        if (Regex.IsMatch($"{table.Schema}.{table.Name}".TrimStart('.'), ArgsMatch) == false)
                        {
                            continue;
                        }
                    }
                    switch (table.Type)
                    {
                    case DatabaseModel.DbTableType.TABLE:
                        if (ArgsFilter.Contains("Table", StringComparison.OrdinalIgnoreCase))
                        {
                            Console.WriteFormatted(" Ignore Table -> " + table.Name + "\r\n", Color.DarkSlateGray);
                            continue;
                        }
                        break;

                    case DatabaseModel.DbTableType.VIEW:
                        if (ArgsFilter.Contains("View", StringComparison.OrdinalIgnoreCase))
                        {
                            Console.WriteFormatted(" Ignore View -> " + table.Name + "\r\n", Color.DarkSlateGray);
                            continue;
                        }
                        break;

                    case DatabaseModel.DbTableType.StoreProcedure:
                        if (ArgsFilter.Contains("StoreProcedure", StringComparison.OrdinalIgnoreCase))
                        {
                            Console.WriteFormatted(" Ignore StoreProcedure -> " + table.Name + "\r\n", Color.DarkSlateGray);
                            continue;
                        }
                        break;
                    }
                    var sw    = new StringWriter();
                    var model = new RazorModel(fsql, ArgsNameSpace, ArgsNameOptions, tables, table);
                    RazorEngine.Engine.Razor.Run(razorId, sw, null, model);

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

                    var outputFile = $"{ArgsOutput}{ArgsFileName.Replace("{name}", model.GetCsName(table.Name))}";
                    File.WriteAllText(outputFile, plus.ToString());
                    switch (table.Type)
                    {
                    case DatabaseModel.DbTableType.TABLE:
                        Console.WriteFormatted(" OUT Table -> " + outputFile + "\r\n", Color.DeepSkyBlue);
                        break;

                    case DatabaseModel.DbTableType.VIEW:
                        Console.WriteFormatted(" OUT View -> " + outputFile + "\r\n", Color.DeepSkyBlue);
                        break;

                    case DatabaseModel.DbTableType.StoreProcedure:
                        Console.WriteFormatted(" OUT StoreProcedure -> " + outputFile + "\r\n", Color.DeepSkyBlue);
                        break;
                    }
                    ++outputCounter;
                }
            }

            var rebuildBat = ArgsOutput + "__重新生成.bat";

            if (File.Exists(rebuildBat) == false)
            {
                var razorCshtml = ArgsOutput + "__razor.cshtml.txt";
                if (File.Exists(razorCshtml) == false)
                {
                    File.WriteAllText(razorCshtml, ArgsRazor);
                    Console.WriteFormatted(" OUT -> " + razorCshtml + "    (以后) 编辑它自定义模板生成\r\n", Color.Magenta);
                    ++outputCounter;
                }

                File.WriteAllText(rebuildBat, $@"
FreeSql.Generator -Razor ""__razor.cshtml.txt"" -NameOptions {string.Join(",", ArgsNameOptions.Select(a => a ? 1 : 0))} -NameSpace {ArgsNameSpace} -DB ""{ArgsDbType},{ArgsConnectionString}""{(string.IsNullOrEmpty(ArgsFilter) ? "" : $" -Filter \"{ArgsFilter}\"")}{(string.IsNullOrEmpty(ArgsMatch) ? "" : $" -Match \"{ArgsMatch}\"")} -FileName ""{ArgsFileName}""
");
                Console.WriteFormatted(" OUT -> " + rebuildBat + "    (以后) 双击它重新生成实体\r\n", Color.Magenta);
                ++outputCounter;
            }

            Console.WriteFormatted($"\r\n[{DateTime.Now.ToString("MM-dd HH:mm:ss")}] 生成完毕,总共生成了 {outputCounter} 个文件,目录:\"{ArgsOutput}\"\r\n", Color.DarkGreen);

            if (ArgsReadKey)
            {
                Console.ReadKey();
            }
            wait.Set();
        }
Пример #8
0
        public ConsoleApp(string[] args, ManualResetEvent wait)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var gb2312 = Encoding.GetEncoding("GB2312");

            if (gb2312 != null)
            {
                try
                {
                    Console.OutputEncoding = gb2312;
                    Console.InputEncoding  = gb2312;
                }
                catch { }
            }

            //var ntjson = Assembly.LoadFile(@"C:\Users\28810\Desktop\testfreesql\bin\Debug\netcoreapp2.2\publish\testfreesql.dll");

            //using (var gen = new Generator(new GeneratorOptions()))
            //{
            //    gen.TraceLog = log => Console.WriteFormatted(log + "\r\n", Color.DarkGray);
            //    gen.Build(ArgsOutput, new[] { typeof(ojbk.Entities.AuthRole) }, false);
            //}

            var version = "v" + string.Join(".", typeof(ConsoleApp).Assembly.GetName().Version.ToString().Split('.').Where((a, b) => b <= 2));

            Console.WriteAscii(" FreeSql", Color.Violet);
            Console.WriteFormatted(@"
  # Github # {0} {1}
", Color.SlateGray,
                                   new Colorful.Formatter("https://github.com/2881099/FreeSql", Color.DeepSkyBlue),
                                   new Colorful.Formatter("v" + string.Join(".", typeof(ConsoleApp).Assembly.GetName().Version.ToString().Split('.').Where((a, b) => b <= 2)), Color.SlateGray));

            ArgsNameOptions = new[] { false, false, false, false };
            ArgsOutput      = Directory.GetCurrentDirectory();
            ArgsFileName    = "{name}.cs";
            string args0 = args[0].Trim().ToLower();

            if (args[0] == "?" || args0 == "--help" || args0 == "-help")
            {
                Console.WriteFormatted(@"
    {0}

    更新工具:dotnet tool update -g FreeSql.Generator


  # 快速开始 #

  > {1} {2} 1 {3} 0,0,0,0 {4} MyProject {5} ""MySql,Data Source=127.0.0.1;...""

     -Razor 1                  * 选择模板:实体类+特性
     
     -Razor 2                  * 选择模板:实体类+特性+导航属性
     
     -Razor ""d:\diy.cshtml""    * 自定义模板文件
     
     -NameOptions              * 总共4个布尔值,分别对应:
                               # 首字母大写
                               # 首字母大写,其他小写
                               # 全部小写
                               # 下划线转驼峰
                               
     -NameSpace                * 命名空间
     
     -DB ""{6},Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=数据库;Charset=utf8;SslMode=none;Max pool size=2""
     
     -DB ""{7},Data Source=.;Integrated Security=True;Initial Catalog=数据库;Pooling=true;Max Pool Size=2""
     
     -DB ""{8},Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=数据库;Pooling=true;Maximum Pool Size=2""
     
     -DB ""{9},user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=2""
     
     -DB ""{10},Driver={DM8 ODBC DRIVER};Server=127.0.0.1:5236;Persist Security Info=False;Trusted_Connection=Yes;UID=USER1;PWD=123456789;Max pool size=2""
                               {10} 是国产达梦数据库,需要使用 ODBC 连接

     -FileName                 文件名,默认:{name}.cs

     -Output                   保存路径,默认为当前 shell 所在目录
                               {11}

", Color.SlateGray,
                                       new Colorful.Formatter("使用 FreeSql 快速生成数据库的实体类", Color.SlateGray),
                                       new Colorful.Formatter("FreeSql.Generator", Color.White),
                                       new Colorful.Formatter("-Razor", Color.ForestGreen),
                                       new Colorful.Formatter("-NameOptions", Color.ForestGreen),
                                       new Colorful.Formatter("-NameSpace", Color.ForestGreen),
                                       new Colorful.Formatter("-DB", Color.ForestGreen),
                                       new Colorful.Formatter("MySql", Color.Yellow),
                                       new Colorful.Formatter("SqlServer", Color.Yellow),
                                       new Colorful.Formatter("PostgreSQL", Color.Yellow),
                                       new Colorful.Formatter("Oracle", Color.Yellow),
                                       new Colorful.Formatter("OdbcDameng", Color.Yellow),
                                       new Colorful.Formatter("推荐在实体类目录创建 gen.bat,双击它重新所有实体类", Color.ForestGreen)
                                       );
                wait.Set();
                return;
            }
            for (int a = 0; a < args.Length; a++)
            {
                switch (args[a])
                {
                case "-Razor":
                    ArgsRazorRaw = args[a + 1].Trim();
                    switch (ArgsRazorRaw)
                    {
                    case "1": ArgsRazor = RazorContentManager.实体类_特性_cshtml; break;

                    case "2": ArgsRazor = RazorContentManager.实体类_特性_导航属性_cshtml; break;

                    default: ArgsRazor = File.ReadAllText(args[a + 1]); break;
                    }
                    a++;
                    break;

                case "-NameOptions":
                    ArgsNameOptions = args[a + 1].Split(',').Select(opt => opt == "1").ToArray();
                    if (ArgsNameOptions.Length != 4)
                    {
                        throw new ArgumentException("-NameOptions 参数错误,格式为:0,0,0,0");
                    }
                    a++;
                    break;

                case "-NameSpace":
                    ArgsNameSpace = args[a + 1];
                    a++;
                    break;

                case "-DB":
                    var dbargs = args[a + 1].Split(',', 2);
                    if (dbargs.Length != 2)
                    {
                        throw new ArgumentException("-DB 参数错误,格式为:MySql,ConnectionString");
                    }
                    switch (dbargs[0].Trim().ToLower())
                    {
                    case "mysql": ArgsDbType = DataType.MySql; break;

                    case "sqlserver": ArgsDbType = DataType.SqlServer; break;

                    case "postgresql": ArgsDbType = DataType.PostgreSQL; break;

                    case "oracle": ArgsDbType = DataType.Oracle; break;

                    case "odbcdameng": ArgsDbType = DataType.OdbcDameng; break;

                    default: throw new ArgumentException($"-DB 参数错误,不支持的类型:{dbargs[0]}");
                    }
                    ArgsConnectionString = dbargs[1].Trim();
                    if (string.IsNullOrEmpty(ArgsConnectionString))
                    {
                        throw new ArgumentException($"-DB 参数错误,未提供 ConnectionString");
                    }
                    a++;
                    break;

                case "-FileName":
                    ArgsFileName = args[a + 1];
                    a++;
                    break;

                case "-Output":
                    ArgsOutput = args[a + 1];
                    a++;
                    break;
                }
            }

            ArgsOutput  = ArgsOutput.Trim().TrimEnd('/', '\\');
            ArgsOutput += ArgsOutput.Contains("\\") ? "\\" : "/";
            if (!Directory.Exists(ArgsOutput))
            {
                Directory.CreateDirectory(ArgsOutput);
            }

            RazorEngine.Engine.Razor = RazorEngineService.Create(new RazorEngine.Configuration.TemplateServiceConfiguration
            {
                EncodedStringFactory = new RazorEngine.Text.RawStringFactory() // Raw string encoding.
            });
            var razorId = Guid.NewGuid().ToString("N");

            RazorEngine.Engine.Razor.Compile(ArgsRazor, razorId);

            var outputCounter = 0;

            using (IFreeSql fsql = new FreeSql.FreeSqlBuilder()
                                   .UseConnectionString(ArgsDbType, ArgsConnectionString)
                                   .UseAutoSyncStructure(false)
                                   .UseMonitorCommand(cmd => Console.WriteFormatted(cmd.CommandText + "\r\n", Color.SlateGray))
                                   .Build())
            {
                var tables       = fsql.DbFirst.GetTablesByDatabase();
                var outputTables = tables;


                //开始生成操作
                foreach (var table in outputTables)
                {
                    var sw    = new StringWriter();
                    var model = new RazorModel(fsql, ArgsNameSpace, ArgsNameOptions, tables, table);
                    RazorEngine.Engine.Razor.Run(razorId, sw, null, model);

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

                    var outputFile = $"{ArgsOutput}{ArgsFileName.Replace("{name}", model.GetCsName(table.Name))}";
                    File.WriteAllText(outputFile, plus.ToString());
                    Console.WriteFormatted(" OUT -> " + outputFile + "\r\n", Color.DeepSkyBlue);
                    ++outputCounter;
                }
            }

            var rebuildBat = ArgsOutput + "__重新生成.bat";

            if (File.Exists(rebuildBat) == false)
            {
                File.WriteAllText(rebuildBat, $@"
FreeSql.Generator -Razor {ArgsRazorRaw} -NameOptions {string.Join(",", ArgsNameOptions.Select(a => a ? 1 : 0))} -NameSpace {ArgsNameSpace} -DB ""{ArgsDbType},{ArgsConnectionString}""
");
                Console.WriteFormatted(" OUT -> " + rebuildBat + "    (以后) 双击它重新生成实体\r\n", Color.Magenta);
                ++outputCounter;
            }

            Console.WriteFormatted($"\r\n[{DateTime.Now.ToString("MM-dd HH:mm:ss")}] 生成完毕,总共生成了 {outputCounter} 个文件,目录:\"{ArgsOutput}\"\r\n", Color.DarkGreen);

            Console.ReadKey();
            wait.Set();
        }
Пример #9
0
        /// <summary>
        /// 传入任务信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        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("生成时发生异常,请检查模版代码.");
            }
        }
Пример #10
0
        /// <summary>
        /// 传入任务信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        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)
            {
                return("生成时发生异常,请检查模版代码.");
            }
        }