Exemplo n.º 1
0
        /// <summary>
        /// 运行
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public override FunctionResult Run(IFunctionParameter param)
        {
            return(FunctionHelper.RunFunction <BackupDatabase_Parameters>(param, (typeParam, sb, result) =>
            {
                RecordLog(sb, "开始获取 ISenparcEntities 对象");
                var senparcEntities = ServiceProvider.GetService(typeof(ISenparcEntities)) as SenparcEntitiesBase;
                RecordLog(sb, "获取 ISenparcEntities 对象成功");
                var sql = $@"Backup Database {senparcEntities.Database.GetDbConnection().Database} To disk='{typeParam.Path}'";
                RecordLog(sb, "准备执行 SQL:" + sql);
                int affectRows = senparcEntities.Database.ExecuteSqlRaw(sql);
                RecordLog(sb, "执行完毕,备份结束。affectRows:" + affectRows);

                RecordLog(sb, "检查备份文件:" + typeParam.Path);
                if (File.Exists(typeParam.Path))
                {
                    var modifyTime = File.GetLastWriteTimeUtc(typeParam.Path);
                    if ((SystemTime.UtcDateTime - modifyTime).TotalSeconds < 5 /*5秒钟内创建的*/)
                    {
                        RecordLog(sb, "检查通过,备份成功!最后修改时间:" + modifyTime.ToString());
                        result.Message = "备份完成!";
                    }
                    else
                    {
                        result.Message = $"文件存在,但修改时间不符,可能未备份成功,请检查文件!文件最后修改时间:{modifyTime.ToString()}";
                        RecordLog(sb, result.Message);
                    }
                }
                else
                {
                    result.Message = "备份文件未生成,备份失败!";
                    RecordLog(sb, result.Message);
                }
            }));
        }
Exemplo n.º 2
0
        /// <summary>
        /// 运行
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public override FunctionResult Run(IFunctionParameter param)
        {
            return(FunctionHelper.RunFunction <CheckUpdate_Parameters>(param, (typeParam, sb, result) =>
            {
                RecordLog(sb, "开始获取 ISenparcEntities 对象");
                var senparcEntities = ServiceProvider.GetService(typeof(ISenparcEntities)) as SenparcEntitiesBase;
                RecordLog(sb, "获取 ISenparcEntities 对象成功");
                RecordLog(sb, "开始检测未安装版本");
                var pendingMigrations = senparcEntities.Database.GetPendingMigrations();

                var oldMigrations = senparcEntities.Database.GetAppliedMigrations();
                foreach (var item in oldMigrations)
                {
                    result.Message = "检测到当前已安装更新:" + item;
                }

                if (pendingMigrations.Count() == 0)
                {
                    result.Message = "未检测到官方 NCF 框架更新。";
                }
                else
                {
                    foreach (var item in pendingMigrations)
                    {
                        RecordLog(sb, "检测到未安装的新版本:" + item);
                    }
                    result.Message = $"检测到 {pendingMigrations.Count()} 个新版本,请使用“Merge EF Core”方法进行更新!";
                }
                RecordLog(sb, result.Message);
            }));
        }
Exemplo n.º 3
0
        /// <summary>
        /// 【异步方法】执行 Run 方法的公共方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="param"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        public static async Task <FunctionResult> RunFunctionAsync <T>(IFunctionParameter param, Func <T, StringBuilder, FunctionResult, Task <FunctionResult> > func)
            where T : IFunctionParameter
        {
            var            typeParam = (T)param;
            StringBuilder  sb        = new StringBuilder();
            FunctionResult result    = new FunctionResult()
            {
                Success = true
            };

            try
            {
                var newResult = await func.Invoke(typeParam, sb, result).ConfigureAwait(false);

                if (newResult != null)
                {
                    result = newResult;
                }
            }
            catch (Exception ex)
            {
                result.Success   = false;
                result.Exception = new XncfFunctionException(ex.Message, ex);
                result.Message   = "发生错误!" + result.Message;

                RecordLog(sb, "发生错误:" + ex.Message);
                RecordLog(sb, ex.StackTrace.ToString());
            }
            result.Log = sb.ToString();
            return(result);
        }
Exemplo n.º 4
0
        /// <summary>
        /// 运行
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public override FunctionResult Run(IFunctionParameter param)
        {
            /* 这里是处理文字选项(单选)的一个示例 */
            return(FunctionHelper.RunFunction <DownloadSourceCode_Parameters>(param, (typeParam, sb, result) =>
            {
                if (Enum.TryParse <DownloadSourceCode_Parameters.Parameters_Site>(typeParam.Site.SelectedValues.FirstOrDefault() /*单选可以这样做,如果是多选需要遍历*/, out var siteType))
                {
                    switch (siteType)
                    {
                    case DownloadSourceCode_Parameters.Parameters_Site.GitHub:
                        result.Message = "https://github.com/NeuCharFramework/NCF/archive/master.zip";
                        break;

                    case DownloadSourceCode_Parameters.Parameters_Site.Gitee:
                        result.Message = "https://gitee.com/NeuCharFramework/NCF/repository/archive/master.zip";
                        break;

                    default:
                        result.Message = "未知的下载地址";
                        result.Success = false;
                        break;
                    }
                }
                else
                {
                    result.Message = "未知的下载参数";
                    result.Success = false;
                }
            }));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Returns a IFunctionParameter[] of the Collection contents.
        /// </summary>
        /// <returns></returns>
        public IFunctionParameter[] ToArray()
        {
            var retArr = new IFunctionParameter[Count];

            List.CopyTo(retArr, 0);
            return(retArr);
        }
Exemplo n.º 6
0
 /// <summary>
 /// Gets the value as a generic object for the specified element.
 /// </summary>
 /// <param name="element">The element to get the value from.</param>
 /// <returns></returns>
 protected object GetTypedValue(IFunctionParameter element)
 {
     if (element == null)
     {
         throw new ArgumentNullException("element");
     }
     return(element.GetTypedValue(DataType, 0));
 }
Exemplo n.º 7
0
        /// <summary>
        /// 运行
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public override FunctionResult Run(IFunctionParameter param)
        {
            var typeParam = param as Terminal_Parameters;

            FunctionResult result = new FunctionResult()
            {
                Success = true
            };

            StringBuilder sb = new StringBuilder();

            base.RecordLog(sb, "开始运行 Terminal");

            var upperCmd = typeParam.CommandLine.ToUpper();

            switch (upperCmd)
            {
            case "SCF RELEASE":    //切换到发布状态

                break;

            case "SCF DEVELOP":    //切换到开发状态
                break;

            default:
                //TODO:需要限制一下执行的命令
                if (!CommandFilter(typeParam.CommandLine))
                {
                    sb.AppendLine("命令不在允许范围之内");
                    result.Log     = sb.ToString();
                    result.Message = "操作失败!";
                    return(result);
                }

                string strExecRes = string.Empty;
                if (!string.IsNullOrEmpty(typeParam.CommandLine))
                {
                    strExecRes = ExeCommand($"{typeParam.CommandLine}");
                }
                else
                {
                    strExecRes = ExeCommand($"dir");
                }

                sb.AppendLine(strExecRes);
                result.Log     = sb.ToString();
                result.Message = "操作成功!";

                if (!string.IsNullOrEmpty(strExecRes))
                {
                    result.Message += Environment.CommandLine + strExecRes;
                }

                break;
            }
            return(result);
        }
Exemplo n.º 8
0
 /// <summary>
 /// 【异步方法】执行 Run 方法的公共方法
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="param"></param>
 /// <param name="action"></param>
 /// <returns></returns>
 public static async Task <FunctionResult> RunFunctionAsync <T>(IFunctionParameter param, Func <T, StringBuilder, FunctionResult, Task> action)
     where T : IFunctionParameter
 {
     return(await RunFunctionAsync <T>(param, async (typeParam, sb, result) =>
     {
         await action(typeParam, sb, result).ConfigureAwait(false);
         return null;
     }));
 }
Exemplo n.º 9
0
 /// <summary>
 /// 执行 Run 方法的公共方法
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="param"></param>
 /// <param name="action"></param>
 /// <returns></returns>
 public static FunctionResult RunFunction <T>(IFunctionParameter param, Action <T, StringBuilder, FunctionResult> action)
     where T : IFunctionParameter
 {
     return(RunFunction <T>(param, (typeParam, sb, result) =>
     {
         action(typeParam, sb, result);
         return null;
     }));
 }
Exemplo n.º 10
0
 public override FunctionResult Run(IFunctionParameter param)
 {
     return(FunctionHelper.RunFunction <Parameters>(param, (typeParam, sb, result) =>
     {
         var databaseConfigurationFactory = DatabaseConfigurationFactory.Instance;
         var currentDatabaseConfiguration = databaseConfigurationFactory.Current;
         result.Message = $"当前 DatabaseConfiguration:{currentDatabaseConfiguration.GetType().Name},数据库类型:{currentDatabaseConfiguration.MultipleDatabaseType}";
     }));
 }
Exemplo n.º 11
0
        /// <summary>
        /// 运行
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public override FunctionResult Run(IFunctionParameter param)
        {
            /* 这里是处理文字选项(单选)的一个示例 */
            return(FunctionHelper.RunFunction <UpdateDocs_Parameters>(param, (typeParam, sb, result) =>
            {
                var wwwrootDir = Path.Combine(Senparc.CO2NET.Config.RootDictionaryPath, "wwwroot");
                var copyDir = Path.Combine(wwwrootDir, "NcfDocs");
                //创建目录
                FileHelper.TryCreateDirectory(wwwrootDir);
                FileHelper.TryCreateDirectory(copyDir);

                var gitUrl = "https://gitee.com/NeuCharFramework/NcfDocs";
                try
                {
                    Repository.Clone(gitUrl, copyDir, new CloneOptions()
                    {
                        IsBare = false
                    });
                }
                catch (Exception)
                {
                    try
                    {
                        var mergeResult = LibGit2Sharp.Commands.Pull(
                            new Repository(copyDir),
                            new Signature("*****@*****.**", "*****@*****.**", SystemTime.Now),
                            new PullOptions());

                        sb.AppendLine("已有文件存在,开始 pull 更新");
                        sb.AppendLine(mergeResult.Status.ToString());
                    }
                    catch (Exception ex)
                    {
                        SenparcTrace.BaseExceptionLog(ex);
                    }
                }

                sb.AppendLine($"仓库创建于 {copyDir}");

                UpdateDocs_Version versionData = null;
                var versionFile = Path.Combine(copyDir, "version.json");
                using (var fs = new FileStream(versionFile, FileMode.Open))
                {
                    using (var sr = new StreamReader(fs))
                    {
                        var versionJson = sr.ReadToEnd();
                        versionData = versionJson.GetObject <UpdateDocs_Version>();
                    }
                }

                result.Message = $"更新成功,当前版本:{versionData.Version},更新时间:{versionData.UpdateTime.ToShortDateString()},What's New:{versionData.WhatsNew ?? "无"}";
            }));
        }
Exemplo n.º 12
0
        public override FunctionResult Run(IFunctionParameter param)
        {
            Console.WriteLine("Run");
            FunctionResult result = new FunctionResult()
            {
                Success = true,
                Message = "OK",
                Log     = "This is Log"
            };

            return(result);
        }
Exemplo n.º 13
0
 /// <summary>
 /// 运行
 /// </summary>
 /// <param name="param"></param>
 /// <returns></returns>
 public override FunctionResult Run(IFunctionParameter param)
 {
     return(FunctionHelper.RunFunction <UpdateDatabase_Parameters>(param, (typeParam, sb, result) =>
     {
         RecordLog(sb, "开始获取 ISenparcEntities 对象");
         ISenparcEntitiesDbContext senparcEntities = ServiceProvider.GetService(typeof(ISenparcEntitiesDbContext)) as ISenparcEntitiesDbContext;
         RecordLog(sb, "获取 ISenparcEntities 对象成功");
         RecordLog(sb, "开始重新标记 Merge 状态");
         senparcEntities.ResetMigrate();
         RecordLog(sb, "开始执行 Migrate()");
         senparcEntities.Migrate();
         RecordLog(sb, "执行 Migrate() 结束,操作完成");
         result.Message = "操作完成,立即生效。";
     }));
 }
Exemplo n.º 14
0
 /// <summary>
 /// 运行
 /// </summary>
 /// <param name="param"></param>
 /// <returns></returns>
 public override FunctionResult Run(IFunctionParameter param)
 {
     return(FunctionHelper.RunFunction <ExportSQL_Parameters>(param, (typeParam, sb, result) =>
     {
         RecordLog(sb, "开始获取 ISenparcEntities 对象");
         var senparcEntities = ServiceProvider.GetService(typeof(ISenparcEntities)) as SenparcEntitiesBase;
         RecordLog(sb, "获取 ISenparcEntities 对象成功");
         RecordLog(sb, "开始生成 SQL ");
         var sql = senparcEntities.Database.GenerateCreateScript();
         RecordLog(sb, "SQL 已生成:");
         RecordLog(sb, $"============ SCF Database {SystemTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}  ============");
         RecordLog(sb, "\r\n\r\n" + sql + "\r\n\r\n");
         RecordLog(sb, $"============ SCF Database {SystemTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}  ============");
         result.Message = "SQL 已生成,请下载日志文件!";
     }));
 }
Exemplo n.º 15
0
        /// <summary>
        /// 运行
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public override FunctionResult Run(IFunctionParameter param)
        {
            return(FunctionHelper.RunFunction <RestoreNameSpace_Parameters>(param, (typeParam, sb, result) =>
            {
                var changeNamespaceParam = new ChangeNamespace_Parameters()
                {
                    NewNamespace = "Senparc.",
                    Path = typeParam.Path
                };

                ChangeNamespace changeNamespaceFunction = new ChangeNamespace(base.ServiceProvider);
                changeNamespaceFunction.OldNamespaceKeyword = typeParam.MyNamespace;
                var newesult = changeNamespaceFunction.Run(changeNamespaceParam);
                if (result.Success)
                {
                    result.Message = "还原命名空间成功!";
                }
                return newesult;
            }));
        }
Exemplo n.º 16
0
        /// <summary>
        /// 运行
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public override FunctionResult Run(IFunctionParameter param)
        {
            var typeParam = param as LaunchApp_Parameters;

            FunctionResult result = new FunctionResult()
            {
                Success = true
            };

            StringBuilder sb = new StringBuilder();

            base.RecordLog(sb, "开始运行 LaunchApp");

            StartApp(typeParam.FilePath);

            //sb.AppendLine($"LaunchPath{typeParam.LaunchPath}");
            sb.AppendLine($"FilePath{typeParam.FilePath}");

            result.Log     = sb.ToString();
            result.Message = "操作成功!";
            return(result);
        }
Exemplo n.º 17
0
 public override FunctionResult Run(IFunctionParameter param)
 {
     /* 这里是处理文字选项(单选)的一个示例 */
     return(FunctionHelper.RunFunction <ClearDocs_Parameters>(param, (typeParam, sb, result) =>
     {
         var wwwrootDir = Path.Combine(Senparc.CO2NET.Config.RootDictionaryPath, "wwwroot");
         var copyDir = Path.Combine(wwwrootDir, "NcfDocs");
         try
         {
             //执行Dos命令
             sb = ExecDosCommand(sb, wwwrootDir, copyDir);
             //写入批处理文件并执行
             //sb = WriteBatchFile(sb, wwwrootDir, copyDir);
         }
         catch (Exception)
         {
             sb.AppendLine("清理失败");
         }
         //sb.AppendLine($"清理目录 {copyDir}");
         //\r\n<br /> {sb.ToString()}
         result.Message = $"清理成功,清理时间:{DateTime.Now.ToLongDateString()} {DateTime.Now.ToLongTimeString()}";
     }));
 }
Exemplo n.º 18
0
        /// <summary>
        /// 运行
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public override FunctionResult Run(IFunctionParameter param)
        {
            return(FunctionHelper.RunFunction <SetConfig_Parameters>(param, (typeParam, sb, result) =>
            {
                //RecordLog(sb, "开始获取 ISenparcEntities 对象");
                //var senparcEntities = ServiceProvider.GetService(typeof(ISenparcEntities)) as SenparcEntitiesBase;
                //RecordLog(sb, "获取 ISenparcEntities 对象成功");

                var configService = base.ServiceProvider.GetService <ServiceBase <DbConfig> >();
                var config = configService.GetObject(z => true);
                if (config == null)
                {
                    config = new DbConfig(typeParam.BackupCycleMinutes, typeParam.BackupPath);
                }
                else
                {
                    configService.Mapper.Map(typeParam, config);
                }
                configService.SaveObject(config);

                result.Message = "设置已保存!";
            }));
        }
Exemplo n.º 19
0
 /// <summary>
 /// Returns the value of the argument in the index specified of the type AnyUri.
 /// </summary>
 /// <param name="args">The arguments list</param>
 /// <param name="index">The index</param>
 /// <returns>The Uri value.</returns>
 protected static Uri GetAnyUriArgument(IFunctionParameter[] args, int index)
 {
     if (args == null) throw new ArgumentNullException("args");
     return (Uri)args[index].GetTypedValue(DataTypeDescriptor.AnyUri, index);
 }
Exemplo n.º 20
0
 /// <summary>
 /// Gets the value as a generic object for the specified element.
 /// </summary>
 /// <param name="element">The element to get the value from.</param>
 /// <returns></returns>
 protected object GetTypedValue(IFunctionParameter element)
 {
     if (element == null) throw new ArgumentNullException("element");
     return element.GetTypedValue(DataType, 0);
 }
Exemplo n.º 21
0
        public override FunctionResult Run(IFunctionParameter param)
        {
            return(FunctionHelper.RunFunction <Parameters>(param, (typeParam, sb, result) =>
            {
                var projectName = $"{typeParam.OrgName}.Xncf.{typeParam.XncfName}";
                _outPutBaseDir = Path.Combine(Senparc.CO2NET.Config.RootDictionaryPath, "..", $"{projectName}");
                _outPutBaseDir = Path.GetFullPath(_outPutBaseDir);
                if (!Directory.Exists(_outPutBaseDir))
                {
                    Directory.CreateDirectory(_outPutBaseDir);
                }

                //定义 Register 主文件
                Senparc.Xncf.XncfBuilder.Templates.Register registerPage = new Senparc.Xncf.XncfBuilder.Templates.Register()
                {
                    OrgName = typeParam.OrgName,
                    XncfName = typeParam.XncfName,
                    Uid = Guid.NewGuid().ToString().ToUpper(),
                    Version = typeParam.Version,
                    MenuName = typeParam.MenuName,
                    Icon = typeParam.Icon,
                    Description = typeParam.Description,
                };

                var useSample = typeParam.UseSammple.SelectedValues.Contains("1");

                #region 使用函数

                //判断是否使用函数(方法)
                var useFunction = typeParam.UseModule.SelectedValues.Contains("function");
                var functionTypes = "";
                if (useFunction)
                {
                    functionTypes = "typeof(MyFunction)";

                    //添加文件夹
                    var dir = AddDir("Functions");
                    Senparc.Xncf.XncfBuilder.Templates.Functions.MyFunction functionPage = new XncfBuilder.Templates.Functions.MyFunction()
                    {
                        OrgName = typeParam.OrgName,
                        XncfName = typeParam.XncfName
                    };
                    WriteContent(functionPage, sb);
                }
                registerPage.FunctionTypes = functionTypes;
                registerPage.UseFunction = useFunction;

                #endregion

                #region 判断 Web - Area
                var useWeb = useSample || typeParam.UseModule.SelectedValues.Contains("web");
                //判断 Area
                if (useWeb)
                {
                    //生成目录
                    var areaDirs = new List <string> {
                        "Areas",
                        "Areas/Admin",
                        "Areas/Admin/Pages/",
                        $"Areas/Admin/Pages/{typeParam.XncfName}",
                        "Areas/Admin/Pages/Shared",
                    };
                    areaDirs.ForEach(z => AddDir(z));

                    //载入Page
                    var areaPages = new List <IXncfTemplatePage> {
                        new ViewStart(typeParam.OrgName, typeParam.XncfName),
                        new ViewImports(typeParam.OrgName, typeParam.XncfName),
                        new Senparc.Xncf.XncfBuilder.Templates.Areas.Admin.Pages.MyApps.Index(typeParam.OrgName, typeParam.XncfName, typeParam.MenuName),
                        new Index_cs(typeParam.OrgName, typeParam.XncfName),
                    };
                    areaPages.ForEach(z => WriteContent(z, sb));

                    //生成Register.Area
                    var registerArea = new RegisterArea(typeParam.OrgName, typeParam.XncfName, useSample);
                    WriteContent(registerArea, sb);
                }

                #endregion

                #region 判断 数据库

                var useDatabase = useSample || typeParam.UseModule.SelectedValues.Contains("database");
                registerPage.UseDatabase = useDatabase;
                if (useDatabase)
                {
                    //生成目录
                    var dbDirs = new List <string> {
                        "App_Data",
                        "App_Data/Database",
                        "Models",
                        "Models/DatabaseModel",
                        "Models/MultipleDatabase",
                        "Migrations",
                        "Migrations/Migrations.SQLite",
                        "Migrations/Migrations.SqlServer",
                        "Migrations/Migrations.MySql",
                    };
                    dbDirs.ForEach(z => AddDir(z));

                    var initMigrationTime = Templates.Migrations.Migrations.SqlServer.Init.GetFileNamePrefix();

                    //载入Page
                    var dbFiles = new List <IXncfTemplatePage> {
                        new RegisterDatabase(typeParam.OrgName, typeParam.XncfName),
                        new XncfBuilder.Templates.App_Data.Database.SenparcConfig(typeParam.OrgName, typeParam.XncfName),
                        //重复多数据库 - SQLite
                        new MySenparcEntities(typeParam.OrgName, typeParam.XncfName, useSample),
                        new XncfBuilder.Templates.Models.DatabaseModel.SenparcDbContextFactory(typeParam.OrgName, typeParam.XncfName),
                        //重复多数据库 - SqlServer
                        new Templates.Models.MultipleDatabase.SenparcEntities_SqlServer(typeParam.OrgName, typeParam.XncfName),
                        //重复多数据库 - MySql
                        new Templates.Models.MultipleDatabase.SenparcEntities_MySql(typeParam.OrgName, typeParam.XncfName),

                        //重复多数据库 - SQLite
                        new Templates.Migrations.Migrations.SQLite.Init(typeParam.OrgName, typeParam.XncfName, initMigrationTime),
                        new Templates.Migrations.Migrations.SQLite.InitDesigner(typeParam.OrgName, typeParam.XncfName, initMigrationTime),
                        //重复多数据库 - SqlServer
                        new Templates.Migrations.Migrations.SqlServer.Init(typeParam.OrgName, typeParam.XncfName, initMigrationTime),
                        new Templates.Migrations.Migrations.SqlServer.InitDesigner(typeParam.OrgName, typeParam.XncfName, initMigrationTime),
                        //重复多数据库 - MySql
                        new Templates.Migrations.Migrations.MySql.Init(typeParam.OrgName, typeParam.XncfName, initMigrationTime),
                        new Templates.Migrations.Migrations.MySql.InitDesigner(typeParam.OrgName, typeParam.XncfName, initMigrationTime),
                    };
                    dbFiles.ForEach(z => WriteContent(z, sb));
                }

                #endregion

                #region 安装 Sample
                if (useSample)
                {
                    var sampleDirs = new List <string> {
                        "Models/DatabaseModel/Dto",
                        "Models/DatabaseModel/Mapping",
                        "Services",
                    };
                    sampleDirs.ForEach(z => AddDir(z));

                    var sampleMigrationTime = Templates.Migrations.Migrations.SqlServer.Init.GetFileNamePrefix(SystemTime.Now.DateTime.AddSeconds(1));

                    //载入Page

                    var sampleFiles = new List <IXncfTemplatePage> {
                        //重复多数据库 - SQLite
                        new Templates.Migrations.Migrations.SQLite.AddSample(typeParam.OrgName, typeParam.XncfName, sampleMigrationTime),
                        new Templates.Migrations.Migrations.SQLite.AddSampleDesigner(typeParam.OrgName, typeParam.XncfName, sampleMigrationTime),
                        //重复多数据库 - SQLServer
                        new Templates.Migrations.Migrations.SqlServer.AddSample(typeParam.OrgName, typeParam.XncfName, sampleMigrationTime),
                        new Templates.Migrations.Migrations.SqlServer.AddSampleDesigner(typeParam.OrgName, typeParam.XncfName, sampleMigrationTime),
                        //重复多数据库 - MySql
                        new Templates.Migrations.Migrations.MySql.AddSample(typeParam.OrgName, typeParam.XncfName, sampleMigrationTime),
                        new Templates.Migrations.Migrations.MySql.AddSampleDesigner(typeParam.OrgName, typeParam.XncfName, sampleMigrationTime),


                        new ColorDto(typeParam.OrgName, typeParam.XncfName),
                        new Sample_ColorConfigurationMapping(typeParam.OrgName, typeParam.XncfName),

                        new Color(typeParam.OrgName, typeParam.XncfName),
                        new ColorService(typeParam.OrgName, typeParam.XncfName),

                        new DatabaseSample(typeParam.OrgName, typeParam.XncfName, typeParam.MenuName),
                        new DatabaseSample_cs(typeParam.OrgName, typeParam.XncfName, typeParam.MenuName),

                        new _SideMenu(typeParam.OrgName, typeParam.XncfName)
                    };
                    sampleFiles.ForEach(z => WriteContent(z, sb));

                    //Sample快照
                    //重复多数据库 - SQLite
                    var addSampleSnapshot = new Templates.Migrations.Migrations.SQLite.SenparcEntitiesModelSnapshotForAddSample(typeParam.OrgName, typeParam.XncfName);
                    WriteContent(addSampleSnapshot, sb);

                    //重复多数据库 - SQL Server
                    var addSampleSnapshot_SqlServer = new Templates.Migrations.Migrations.SqlServer.SenparcEntitiesModelSnapshotForAddSample(typeParam.OrgName, typeParam.XncfName);
                    WriteContent(addSampleSnapshot_SqlServer, sb);

                    //重复多数据库 - MySQL
                    var addSampleSnapshot_MySql = new Templates.Migrations.Migrations.MySql.SenparcEntitiesModelSnapshotForAddSample(typeParam.OrgName, typeParam.XncfName);
                    WriteContent(addSampleSnapshot_MySql, sb);
                }
                else if (useDatabase)
                {
                    //默认 Init 快照
                    //重复多数据库 - SQLite
                    var initSnapshot = new Templates.Migrations.Migrations.SQLite.SenparcEntitiesModelSnapshotForInit(typeParam.OrgName, typeParam.XncfName);
                    WriteContent(initSnapshot, sb);

                    //重复多数据库 - SQL Server
                    var initSnapshot_SqlServer = new Templates.Migrations.Migrations.SqlServer.SenparcEntitiesModelSnapshotForInit(typeParam.OrgName, typeParam.XncfName);
                    WriteContent(initSnapshot_SqlServer, sb);

                    //重复多数据库 - MySQL
                    var initSnapshot_MySql = new Templates.Migrations.Migrations.MySql.SenparcEntitiesModelSnapshotForInit(typeParam.OrgName, typeParam.XncfName);
                    WriteContent(initSnapshot_MySql, sb);
                }

                #endregion

                #region 生成 Register 主文件

                registerPage.UseSample = useSample;
                WriteContent(registerPage, sb);

                #endregion

                #region 生成 .csproj

                string areaBaseVersion = "";
                try
                {
                    //areaBaseVersion = FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetAssembly(Type.GetType("Senparc.Ncf.AreaBase.Admin.AdminPageModelBase,Senparc.Ncf.AreaBase")).Location).ProductVersion;
                    var dllPath = Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);
                    var areaBaseDllPath = Path.Combine(dllPath, "Senparc.Ncf.AreaBase.dll");
                    areaBaseVersion =
                        FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.LoadFrom(areaBaseDllPath).Location).ProductVersion;
                }
                catch
                {
                }


                //生成 .csproj
                Senparc.Xncf.XncfBuilder.Templates.csproj csprojPage = new csproj()
                {
                    OrgName = typeParam.OrgName,
                    XncfName = typeParam.XncfName,
                    Version = typeParam.Version,
                    MenuName = typeParam.MenuName,
                    Description = typeParam.Description,
                    UseWeb = useWeb,
                    UseDatabase = useDatabase,
                    AreaBaseVersion = areaBaseVersion,
                    XncfBaseVersion = FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetAssembly(typeof(Senparc.Ncf.XncfBase.Register)).Location).ProductVersion,
                };

                //获取当前配置的 FrameworkVersion
                var frameworkVersion = typeParam.OtherFrameworkVersion.IsNullOrEmpty()
                                            ? typeParam.FrameworkVersion.SelectedValues.First()
                                            : typeParam.OtherFrameworkVersion;
                if (useWeb && frameworkVersion == "netstandard2.1")
                {
                    //需要使用网页,强制修正为支持 Host 的目标框架
                    frameworkVersion = "netcoreapp3.1";
                }
                csprojPage.FrameworkVersion = frameworkVersion;

                WriteContent(csprojPage, sb);

                #endregion

                #region 自动附加项目

                var webProjFilePath = Path.GetFullPath(Path.Combine(Senparc.CO2NET.Config.RootDictionaryPath, "Senparc.Web.csproj"));
                if (File.Exists(webProjFilePath))
                {
                    XDocument webCsproj = XDocument.Load(webProjFilePath);
                    if (!webCsproj.ToString().Contains(csprojPage.ProjectFilePath))
                    {
                        var referenceNode = new XElement("ProjectReference");
                        referenceNode.Add(new XAttribute("Include", $"..\\{csprojPage.ProjectFilePath}"));
                        var newNode = new XElement("ItemGroup", referenceNode);
                        webCsproj.Root.Add(newNode);
                        webCsproj.Save(webProjFilePath);
                    }
                }

                #endregion

                #region 生成 .sln

                //生成 .sln
                if (!typeParam.SlnFilePath.ToUpper().EndsWith(".SLN"))
                {
                    result.Success = false;
                    result.Message = $"解决方案文件未找到,请手动引用项目 {csprojPage.RelativeFilePath}";
                    sb.AppendLine($"操作未全部完成:{result.Message}");
                }
                else if (File.Exists(typeParam.SlnFilePath))
                {
                    //是否创建新的 .sln 文件
                    var useNewSlnFile = typeParam.NewSlnFile.SelectedValues.Contains("new");

                    var slnFileName = Path.GetFileName(typeParam.SlnFilePath);
                    string newSlnFileName = slnFileName;
                    string newSlnFilePath = typeParam.SlnFilePath;
                    if (useNewSlnFile)
                    {
                        newSlnFileName = $"{slnFileName}-new-{SystemTime.Now.DateTime.ToString("yyyyMMdd_HHmmss")}.sln";
                        newSlnFilePath = Path.Combine(Path.GetDirectoryName(typeParam.SlnFilePath), newSlnFileName);
                        File.Copy(typeParam.SlnFilePath, newSlnFilePath);
                        sb.AppendLine($"完成 {newSlnFilePath} 文件创建");
                    }
                    else
                    {
                        var backupSln = typeParam.NewSlnFile.SelectedValues.Contains("backup");
                        var backupFileName = $"{slnFileName}-backup-{SystemTime.Now.DateTime.ToString("yyyyMMdd_HHmmss")}.sln";
                        var backupFilePath = Path.Combine(Path.GetDirectoryName(typeParam.SlnFilePath), backupFileName);
                        File.Copy(typeParam.SlnFilePath, backupFilePath);
                        sb.AppendLine($"完成 {newSlnFilePath} 文件备份");
                    }


                    result.Message = $"项目生成成功!请打开  {newSlnFilePath} 解决方案文件查看已附加的项目!<br />注意:如果您操作的项目此刻正在运行中,可能会引发重新编译,导致您看到的这个页面可能已失效。";

                    //修改 new Sln
                    string slnContent = null;
                    using (FileStream fs = new FileStream(newSlnFilePath, FileMode.Open))
                    {
                        using (StreamReader sr = new StreamReader(fs))
                        {
                            slnContent = sr.ReadToEnd();
                            sr.Close();
                        }
                    }

                    var projGuid = Guid.NewGuid().ToString("B").ToUpper();//ex. {76FC86E0-991D-47B7-8AAB-42B27DAB10C1}
                    slnContent = slnContent.Replace(@"Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""Senparc.Core"", ""Senparc.Core\Senparc.Core.csproj"", ""{D0EF2816-B99A-4554-964A-6EA6814B3A36}""
EndProject", @$ "Project(" "{{9A19103F-16F7-4668-BE54-9A1E7A4F7556}}" ") = " "Senparc.Core" ", " "Senparc.Core\Senparc.Core.csproj" ", " "{{D0EF2816-B99A-4554-964A-6EA6814B3A36}}" "
EndProject
Project(" "{{9A19103F-16F7-4668-BE54-9A1E7A4F7556}}" ") = " "{projectName}" ", " "{projectName}\{csprojPage.RelativeFilePath}" ", " "{projGuid}" "
Exemplo n.º 22
0
 /// <summary>
 /// Returns the value of the argument in the index specified of the type IPAddress.
 /// </summary>
 /// <param name="args">The arguments list</param>
 /// <param name="index">The index</param>
 /// <returns>The IPAddress value.</returns>
 protected static typ.IpAddress GetIpAddressArgument(IFunctionParameter[] args, int index)
 {
     if (args == null) throw new ArgumentNullException("args");
     return (typ.IpAddress)args[index].GetTypedValue(DataTypeDescriptor.IpAddress, index);
 }
Exemplo n.º 23
0
 /// <summary>
 /// Returns the value of the argument in the index specified of the type int.
 /// </summary>
 /// <param name="args">The arguments list</param>
 /// <param name="index">The index</param>
 /// <returns>The integer value.</returns>
 protected static int GetIntegerArgument(IFunctionParameter[] args, int index)
 {
     if (args == null) throw new ArgumentNullException("args");
     return (int)args[index].GetTypedValue(DataTypeDescriptor.Integer, index);
 }
Exemplo n.º 24
0
 /// <summary>
 /// Returns the specified indexed argument as a string value.
 /// </summary>
 /// <param name="args">The list of arguments.</param>
 /// <param name="idx">The argument index requested.</param>
 /// <returns>A string representing the value of the argument.</returns>
 public virtual string GetArgumentAsString(IFunctionParameter[] args, int idx)
 {
     if (args == null) throw new ArgumentNullException("args");
     return args[idx].ToString();
 }
Exemplo n.º 25
0
        /// <summary>
        /// 运行
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public override FunctionResult Run(IFunctionParameter param)
        {
            return(FunctionHelper.RunFunction <BackupDatabase_Parameters>(param, (typeParam, sb, result) =>
            {
                try
                {
                    var path = typeParam.Path;

                    if (File.Exists(path))
                    {
                        var copyPath = path + ".last.bak";
                        if (typeParam.Options.SelectedValues.Contains($"{(int)BackupDatabaseOptions.如果文件存在则不覆盖}"))
                        {
                            RecordLog(sb, "检测到同名文件,停止覆盖。地址:" + copyPath);
                            result.Message = "检测到同名文件,停止覆盖!";
                            return;
                        }

                        RecordLog(sb, "检测到同名文件,已经移动到(并覆盖):" + copyPath);
                        File.Move(path, copyPath, true);
                    }

                    RecordLog(sb, "开始获取 ISenparcEntities 对象");
                    var senparcEntities = ServiceProvider.GetService(typeof(ISenparcEntities)) as SenparcEntitiesBase;
                    RecordLog(sb, "获取 ISenparcEntities 对象成功");
                    var sql = $@"Backup Database {senparcEntities.Database.GetDbConnection().Database} To disk='{path}'";
                    RecordLog(sb, "准备执行 SQL:" + sql);
                    int affectRows = senparcEntities.Database.ExecuteSqlRaw(sql);
                    RecordLog(sb, "执行完毕,备份结束。affectRows:" + affectRows);

                    if (typeParam.Options.SelectedValues.Contains($"{(int)BackupDatabaseOptions.校验备份成功}"))
                    {
                        RecordLog(sb, "检查备份文件:" + path);
                        if (File.Exists(path))
                        {
                            var modifyTime = File.GetLastWriteTimeUtc(path);
                            if ((SystemTime.UtcDateTime - modifyTime).TotalSeconds < 5 /*5秒钟内创建的*/)
                            {
                                RecordLog(sb, "检查通过,备份成功!最后修改时间:" + modifyTime.ToString());
                                result.Message = "检查通过,备份成功!";
                            }
                            else
                            {
                                result.Message = $"文件存在,但修改时间不符,可能未备份成功,请检查文件!文件最后修改时间:{modifyTime.ToString()}";
                                RecordLog(sb, result.Message);
                            }
                        }
                        else
                        {
                            result.Message = "备份文件未生成,备份失败!";
                            RecordLog(sb, result.Message);
                        }
                    }
                    else
                    {
                        result.Message = "备份完成!";
                    }
                }
                catch (Exception ex)
                {
                    result.Message += ex.Message;
                    throw;
                }
            }));
        }
Exemplo n.º 26
0
 /// <summary>
 /// 执行程序
 /// </summary>
 /// <param name="param"></param>
 /// <returns></returns>
 public abstract FunctionResult Run(IFunctionParameter param);
Exemplo n.º 27
0
 /// <summary>
 /// Returns the value of the argument in the index specified of the type YearMonthDuration.
 /// </summary>
 /// <param name="args">The arguments list</param>
 /// <param name="index">The index</param>
 /// <returns>The YearMonthDuration value.</returns>
 protected static typ.YearMonthDuration GetYearMonthDurationArgument(IFunctionParameter[] args, int index)
 {
     if (args == null) throw new ArgumentNullException("args");
     if (args == null) throw new ArgumentNullException("args");
     return (typ.YearMonthDuration)args[index].GetTypedValue(DataTypeDescriptor.YearMonthDuration, index);
 }
Exemplo n.º 28
0
 /// <summary>
 /// Returns the value of the argument in the index specified of the type HexBinary.
 /// </summary>
 /// <param name="args">The arguments list</param>
 /// <param name="index">The index</param>
 /// <returns>The HexBinary value.</returns>
 protected static typ.HexBinary GetHexBinaryArgument(IFunctionParameter[] args, int index)
 {
     if (args == null) throw new ArgumentNullException("args");
     return (typ.HexBinary)args[index].GetTypedValue(DataTypeDescriptor.HexBinary, index);
 }
Exemplo n.º 29
0
 /// <summary>
 /// Returns the value of the argument in the index specified of the type DnsName.
 /// </summary>
 /// <param name="args">The arguments list</param>
 /// <param name="index">The index</param>
 /// <returns>The DnsName value.</returns>
 protected static typ.DnsNameDataType GetDnsNameArgument(IFunctionParameter[] args, int index)
 {
     if (args == null) throw new ArgumentNullException("args");
     return (typ.DnsNameDataType)args[index].GetTypedValue(DataTypeDescriptor.DnsName, index);
 }
 /// <summary>
 /// Returns a IFunctionParameter[] of the Collection contents.
 /// </summary>
 /// <returns></returns>
 public IFunctionParameter[] ToArray()
 {
     var retArr = new IFunctionParameter[Count];
     List.CopyTo(retArr, 0);
     return retArr;
 }
Exemplo n.º 31
0
        public override FunctionResult Run(IFunctionParameter param)
        {
            return(FunctionHelper.RunFunction <Parameters>(param, (typeParam, sb, result) =>
            {
                if (!typeParam.DatabaseTypes.SelectedValues.Contains(MultipleDatabaseType.SQLite.ToString()))
                {
                    result.Message = $"{MultipleDatabaseType.SQLite} 暂时为默认数据库,必选";
                    return;
                }


                var commandTexts = new List <string> {
                    @$ "cd {typeParam.ProjectPath}",
                    //@"dir",
                    //@"dotnet --version",
                    //@"dotnet ef",
                    //@"dotnet ef migrations add Int2 --context XncfBuilderEntities_SqlServer --output-dir Migrations/Test",// 本行为示例,将自动根据条件执行
                };

                foreach (var dbType in typeParam.DatabaseTypes.SelectedValues)
                {
                    var migrationDir = Path.Combine(typeParam.ProjectPath, "Migrations", $"Migrations.{dbType}");
                    var outputVerbose = typeParam.OutputVerbose.SelectedValues.Contains("1") ? " -v" : "";
                    var dbTypeSuffix = Enum.TryParse(dbType, out MultipleDatabaseType dbTypeEnum) && dbTypeEnum == MultipleDatabaseType.Default
                                            ? "" : $"_{dbType}";//如果是SQL Lite
                    commandTexts.Add($"dotnet ef migrations add {typeParam.MigrationName} -c {typeParam.DbContextName}{dbTypeSuffix} -o {migrationDir}{outputVerbose}");
                }

                Process p = new Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;
                string strOutput = null;
                try
                {
                    p.Start();
                    foreach (string item in commandTexts)
                    {
                        p.StandardInput.WriteLine(item);
                    }
                    p.StandardInput.WriteLine("exit");
                    strOutput = p.StandardOutput.ReadToEnd();
                    base.RecordLog(sb, strOutput);

                    //strOutput = Encoding.UTF8.GetString(Encoding.Default.GetBytes(strOutput));
                    p.WaitForExit();
                    p.Close();
                }
                catch (Exception e)
                {
                    strOutput = e.Message;
                }
                result.Message = "执行完毕,请查看日志!";

                if (strOutput.Contains("Build FAILED", StringComparison.InvariantCultureIgnoreCase))
                {
                    result.Message += "重要提示:可能出现错误,请检查日志!";
                }
            }));
        }
Exemplo n.º 32
0
        public override FunctionResult Run(IFunctionParameter param)
        {
            return(FunctionHelper.RunFunction <Parameters>(param, (typeParam, sb, result) =>
            {
                var outputStr = BuildSample(typeParam, ref sb); //执行模板生成
                var projectFilePath = $"{typeParam.OrgName}.Xncf.{typeParam.XncfName}\\{typeParam.OrgName}.Xncf.{typeParam.XncfName}.csproj";

                #region 生成 .sln

                var relativeFilePath = $"{typeParam.OrgName}.Xncf.{typeParam.XncfName}.csproj";

                //生成 .sln
                if (!typeParam.SlnFilePath.ToUpper().EndsWith(".SLN"))
                {
                    result.Success = false;
                    result.Message = $"解决方案文件未找到,请手动引用项目 {projectFilePath}";
                    sb.AppendLine($"操作未全部完成:{result.Message}");
                }
                else if (File.Exists(typeParam.SlnFilePath))
                {
                    //是否创建新的 .sln 文件
                    var useNewSlnFile = typeParam.NewSlnFile.SelectedValues.Contains("new");

                    var slnFileName = Path.GetFileName(typeParam.SlnFilePath);
                    string newSlnFileName = slnFileName;
                    string newSlnFilePath = typeParam.SlnFilePath;
                    if (useNewSlnFile)
                    {
                        newSlnFileName = $"{slnFileName}-new-{SystemTime.Now.DateTime.ToString("yyyyMMdd_HHmmss")}.sln";
                        newSlnFilePath = Path.Combine(Path.GetDirectoryName(typeParam.SlnFilePath), newSlnFileName);
                        File.Copy(typeParam.SlnFilePath, newSlnFilePath);
                        sb.AppendLine($"完成 {newSlnFilePath} 文件创建");
                    }
                    else
                    {
                        var backupSln = typeParam.NewSlnFile.SelectedValues.Contains("backup");
                        var backupFileName = $"{slnFileName}-backup-{SystemTime.Now.DateTime.ToString("yyyyMMdd_HHmmss")}.sln";
                        var backupFilePath = Path.Combine(Path.GetDirectoryName(typeParam.SlnFilePath), backupFileName);
                        File.Copy(typeParam.SlnFilePath, backupFilePath);
                        sb.AppendLine($"完成 {newSlnFilePath} 文件备份");
                    }


                    result.Message = $"项目生成成功!请打开  {newSlnFilePath} 解决方案文件查看已附加的项目!<br />注意:如果您操作的项目此刻正在运行中,可能会引发重新编译,导致您看到的这个页面可能已失效。";
                }
                else
                {
                    result.Success = false;
                    result.Message = $"解决方案文件未找到,请手动引用项目 {relativeFilePath}";
                    sb.AppendLine($"操作未全部完成:{result.Message}");
                }


                Console.WriteLine(outputStr);
                Console.WriteLine(sb.ToString());

                #endregion

                #region 将当前设置保存到数据库

                var configService = base.ServiceProvider.GetService <ServiceBase <Config> >();
                var config = configService.GetObject(z => true);
                if (config == null)
                {
                    config = new Config(typeParam.SlnFilePath, typeParam.OrgName, typeParam.XncfName, typeParam.Version, typeParam.MenuName, typeParam.Icon);
                }
                else
                {
                    configService.Mapper.Map(typeParam, config);
                }
                configService.SaveObject(config);

                //result.Message += "\r\n\r\n" + outputStr;

                #endregion
            }));
        }
Exemplo n.º 33
0
 /// <summary>
 /// Returns the value of the argument in the index specified of the type String.
 /// </summary>
 /// <param name="args">The arguments list</param>
 /// <param name="index">The index</param>
 /// <returns>The String value.</returns>
 protected static string GetStringArgument(IFunctionParameter[] args, int index)
 {
     if (args == null) throw new ArgumentNullException("args");
     return (string)args[index].GetTypedValue(DataTypeDescriptor.String, index);
 }
Exemplo n.º 34
0
 /// <summary>
 /// Returns the value of the argument in the index specified of the type bool.
 /// </summary>
 /// <param name="args">The arguments list</param>
 /// <param name="index">The index</param>
 /// <returns>The bool value.</returns>
 protected static bool GetBooleanArgument(IFunctionParameter[] args, int index)
 {
     if (args == null) throw new ArgumentNullException("args");
     return (bool)args[index].GetTypedValue(DataTypeDescriptor.Boolean, index);
 }
Exemplo n.º 35
0
        public override FunctionResult Run(IFunctionParameter param)
        {
            return(FunctionHelper.RunFunction <Parameters>(param, (typeParam, sb, result) =>
            {
                if (typeParam.DatabaseTypes.SelectedValues.Count() == 0)
                {
                    result.Message = "至少选择 1 个数据库!";
                    return;
                }

                var commandTexts = new List <string> {
                    @$ "cd {typeParam.ProjectPath}",
                };

                foreach (var dbType in typeParam.DatabaseTypes.SelectedValues)
                {
                    string migrationDir = GetMigrationDir(typeParam, dbType);
                    var outputVerbose = typeParam.OutputVerbose.SelectedValues.Contains("1") ? " -v" : "";
                    var dbTypeSuffix = $"_{dbType}";
                    commandTexts.Add($"dotnet ef migrations add {typeParam.MigrationName} -c {typeParam.DbContextName}{dbTypeSuffix} -s {typeParam.DatabasePlantPath} -o {migrationDir}{outputVerbose}");
                    // --framework netcoreapp3.1
                    // 如需指定框架,可以追加上述参数,也可以支持更多参数,如net5.0
                }

                Process p = new Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;
                string strOutput = null;
                try
                {
                    p.Start();
                    foreach (string item in commandTexts)
                    {
                        p.StandardInput.WriteLine(item);
                    }
                    p.StandardInput.WriteLine("exit");
                    strOutput = p.StandardOutput.ReadToEnd();
                    base.RecordLog(sb, strOutput);

                    //strOutput = Encoding.UTF8.GetString(Encoding.Default.GetBytes(strOutput));
                    p.WaitForExit();
                    p.Close();
                }
                catch (Exception e)
                {
                    strOutput = e.Message;
                }


                ////Pomelo-MySQL 命名有不统一的情况,需要处理
                //if (typeParam.DatabaseTypes.SelectedValues.Contains(MultipleDatabaseType.MySql.ToString()))
                //{
                //    string migrationDir = GetMigrationDir(typeParam, MultipleDatabaseType.MySql.ToString());
                //    var defaultFileName = $"{typeParam.DbContextName}ModelSnapshot.cs";
                //    var pomeloFileName = $"{typeParam.DbContextName}_MySqlModelSnapshot.cs";
                //    if (File.Exists(defaultFileName) && File.Exists(pomeloFileName))
                //    {
                //        File.Delete(defaultFileName);
                //        base.RecordLog(sb, $"扫描到不兼容常规格式的 Pomelo.EntityFrameworkCore.MySql 的快照文件:{pomeloFileName},已将默认文件删除({defaultFileName})!");
                //    }
                //}

                result.Message = "执行完毕,请查看日志!";

                if (strOutput.Contains("Build FAILED", StringComparison.InvariantCultureIgnoreCase))
                {
                    result.Message += "重要提示:可能出现错误,请检查日志!";
                }
            }));
        }
Exemplo n.º 36
0
        /// <summary>
        /// 运行
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public override FunctionResult Run(IFunctionParameter param)
        {
            return(FunctionHelper.RunFunction <ChangeNamespace_Parameters>(param, (typeParam, sb, result) =>
            {
                base.RecordLog(sb, "开始运行 ChangeNamespace");

                var path = typeParam.Path;
                var newNamespace = typeParam.NewNamespace;

                if (!Directory.Exists(path))
                {
                    base.RecordLog(sb, $"path:{path} not exist");
                    result.Success = false;
                    result.Message = "路径不存在!";
                    return;
                }

                base.RecordLog(sb, $"path:{path} newNamespace:{newNamespace}");

                var meetRules = new List <MeetRule>()
                {
                    new MeetRule("namespace", OldNamespaceKeyword, $"{newNamespace}", "*.cs"),
                    new MeetRule("@model", OldNamespaceKeyword, $"{newNamespace}", "*.cshtml"),
                    new MeetRule("@addTagHelper *,", OldNamespaceKeyword, $"{newNamespace}", "*.cshtml"),
                };

                //TODO:使用正则记录,并全局修改

                Dictionary <string, List <MatchNamespace> > namespaceCollection = new Dictionary <string, List <MatchNamespace> >(StringComparer.OrdinalIgnoreCase);

                //扫描所有规则
                foreach (var item in meetRules)
                {
                    var files = Directory.GetFiles(path, item.FileType, SearchOption.AllDirectories);

                    //扫描所有文件,将满足这一条规则替换条件的对象记录下来
                    foreach (var file in files)
                    {
                        base.RecordLog(sb, $"扫描文件类型:{item.FileType} 数量:{files.Length}");

                        //string content = null;
                        using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                        {
                            using (var sr = new StreamReader(fs))
                            {
                                var line = sr.ReadLine();
                                while (null != line)
                                {
                                    line = sr.ReadLine()?.Trim();
                                    var oldNamespaceFull = $"{item.Prefix} {item.OrignalKeyword}";
                                    if (line != null && line.StartsWith(oldNamespaceFull))
                                    {
                                        if (!namespaceCollection.ContainsKey(file))
                                        {
                                            namespaceCollection[file] = new List <MatchNamespace>();
                                        }

                                        //不能使用Split,中间可能还有空格
                                        //var oldNamespaceArr = line.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                                        var getOld = line.Replace(item.Prefix + " ", "");//也可以用IndexOf+Length来做
                                        var getNew = getOld.Replace(item.OrignalKeyword, item.ReplaceWord);
                                        namespaceCollection[file].Add(new MatchNamespace()
                                        {
                                            Prefix = item.Prefix,//prefix
                                            OldNamespace = getOld,
                                            NewNamespace = getNew
                                        });

                                        namespaceCollection[file].Add(new MatchNamespace()
                                        {
                                            Prefix = "using",
                                            OldNamespace = getOld,
                                            NewNamespace = getNew
                                        });
                                    }

                                    //content += Environment.NewLine + line;
                                }
                                sr.ReadLine();
                            }
                            fs.Close();
                        }
                    }

                    //遍历所有文件,替换已经解锁出来的旧命名空间
                    foreach (var file in files)
                    {
                        string content = null;
                        using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                        {
                            using (var sr = new StreamReader(fs))
                            {
                                content = sr.ReadToEnd();
                            }
                            fs.Close();
                        }

                        foreach (var namespaceInfos in namespaceCollection)
                        {
                            foreach (var namespaceInfo in namespaceInfos.Value)
                            {
                                var oldNamespaceFull = $"{namespaceInfo.Prefix} {namespaceInfo.OldNamespace}";

                                //替换旧的NameSpace
                                if (content.IndexOf(oldNamespaceFull) > -1)
                                {
                                    base.RecordLog(sb, $"文件命中:{file} -> {oldNamespaceFull}");
                                    var newNameSpaceFull = $"{namespaceInfo.Prefix} {namespaceInfo.NewNamespace}";
                                    content = content.Replace(oldNamespaceFull, newNameSpaceFull);
                                }
                            }
                        }

                        using (var fs = new FileStream(file, FileMode.Truncate, FileAccess.ReadWrite))
                        {
                            using (var sw = new StreamWriter(fs))
                            {
                                sw.Write(content);
                                sw.Flush();
                            }
                            fs.Close();
                        }
                    }
                }

                result.Log = sb.ToString();
                result.Message = "更新成功!您还可以使用【还原命名空间】功能进行还原!";
            }));
        }
Exemplo n.º 37
0
        public override FunctionResult Run(IFunctionParameter param)
        {
            return(FunctionHelper.RunFunction <Parameters>(param, (typeParam, sb, result) =>
            {
                /* 页面上点击“执行”后,将调用这里的方法
                 *
                 * 参数说明:
                 * param:IFunctionParameter 类型对象
                 * typeParam:WorkShop.Xncf.Message.MyFunction.Parameters 类型对象
                 * sb:日志
                 * result:返回结果
                 */

                double calcResult = typeParam.Number1;
                var theOperator = typeParam.Operator.SelectedValues.FirstOrDefault();
                switch (theOperator)
                {
                case "+":
                    calcResult = calcResult + typeParam.Number2;
                    break;

                case "-":
                    calcResult = calcResult - typeParam.Number2;
                    break;

                case "×":
                    calcResult = calcResult * typeParam.Number2;
                    break;

                case "÷":
                    if (typeParam.Number2 == 0)
                    {
                        result.Success = false;
                        result.Message = "被除数不能为0!";
                        return;
                    }
                    calcResult = calcResult / typeParam.Number2;
                    break;

                default:
                    result.Success = false;
                    result.Message = $"未知的运算符:{theOperator}";
                    return;
                }

                sb.AppendLine($"进行运算:{typeParam.Number1} {theOperator} {typeParam.Number2} = {calcResult}");

                Action <int> raisePower = power => {
                    if (typeParam.Power.SelectedValues.Contains(power.ToString()))
                    {
                        var oldValue = calcResult;
                        calcResult = Math.Pow(calcResult, power);
                        sb.AppendLine($"进行{power}次方运算:{oldValue}{(power == 2 ? "²" : "³")} = {calcResult}");
                    }
                };

                raisePower(2);
                raisePower(3);

                result.Message = $"计算结果:{calcResult}。计算过程请看日志";
            }));
        }
 /// <summary>
 /// Adds an object to the end of the CollectionBase.
 /// </summary>
 /// <param name="value">The Object to be added to the end of the CollectionBase. </param>
 /// <returns>The CollectionBase index at which the value has been added.</returns>
 public int Add(IFunctionParameter value)
 {
     return (List.Add(value));
 }
Exemplo n.º 39
0
 /// <summary>
 /// Adds an object to the end of the CollectionBase.
 /// </summary>
 /// <param name="value">The Object to be added to the end of the CollectionBase. </param>
 /// <returns>The CollectionBase index at which the value has been added.</returns>
 public int Add(IFunctionParameter value)
 {
     return(List.Add(value));
 }