public override void OnFileCreateComplated(Configuration configuration, Item item, DbTable table, string fileName) { var projectFile = this.GetPorjectFile(configuration, item); var itemGroupItemType = this.GetItemGroupItemType(item.Extension); ProjectFileConfigurationManager.AddItemGroupItem(projectFile, fileName, itemGroupItemType); }
/// <summary> /// 文件生成完毕后的处理。 /// </summary> /// <param name="configuration">代码生成配置信息</param> /// <param name="sectionItem">生成配置项</param> /// <param name="table">数据库表信息</param> /// <param name="fileName">文件名</param> public override void OnFileCreateComplated(Configuration configuration, Item sectionItem, DbTable table, string fileName) { var configFile = this.GetConfigFile(configuration, sectionItem, table); var xdocument = XDocument.Load(configFile); var id = string.Format("{0}Service", table.ClassName.CamelNaming()); var xmlns = this.GetDefaultNamespace(); var exists = (from o in xdocument.Descendants(xmlns + "object") where o.Attribute("id").Value == id select o).Any(); if (!exists) { var element = this.CreateElement("object"); element.SetAttributeValue("id", id); element.SetAttributeValue("type", string.Format(table.FullClassNameFormat, "Service")); element.SetAttributeValue("parent", "serviceSupport"); xdocument.Root.Add(new XComment(string.Format("配置{0}服务对象", table.Description))); xdocument.Root.Add(element); File.SetAttributes(configFile, FileAttributes.Normal); xdocument.Save(configFile, SaveOptions.None); } this.ConfigImports(configuration, sectionItem, table); }
/// <summary> /// 获取配置文件。 /// </summary> /// <param name="configuration">代码生成配置信息</param> /// <param name="item">文件生成配置项信息</param> /// <param name="table">数据库表领域信息</param> /// <returns>配置文件</returns> protected string GetConfigFile(Configuration configuration, Item item, DbTable table) { var projectName = item.Project.Split('\\').LastOrDefault(); var projectPath = item.GetProjectFolder(configuration.OutputFolder, configuration.BaseNamespace); var configFile = string.IsNullOrWhiteSpace(table.ModuleName) ? string.Format(@"{0}\ApplicationContext-{1}.xml", projectPath, projectName) : string.Format(@"{0}\ApplicationContext-{1}-{2}.xml", projectPath, projectName, table.ModuleName); if (!File.Exists(configFile)) { var file = new FileInfo(configFile); if (!file.Directory.Exists) { file.Directory.Create(); } var xdocument = new XDocument(this.CreateElement("objects")); xdocument.Save(configFile, SaveOptions.None); var projectFile = this.GetPorjectFile(configuration, item); var itemGroupItemType = this.GetItemGroupItemType("xml"); ProjectFileConfigurationManager.AddItemGroupItem(projectFile, configFile, itemGroupItemType); } return configFile; }
protected string GetPorjectFile(Configuration configuration, Item item) { var projectFolder = item.GetProjectFolder(configuration.OutputFolder, configuration.BaseNamespace); var projectFile = string.Format(@"{0}\{1}.csproj", projectFolder, item.GetProjectName(configuration.BaseNamespace)); return projectFile; }
/// <summary> /// 生成工程。 /// </summary> /// <param name="configuration">代码生成配置信息</param> public void Create(Configuration configuration) { //if (this.IsFirstCreate(configuration)) //{ // this.Initialize(configuration); //} this._buildEvent?.Publish(new BuildEventArg(Status.Begin)); this.DbTypeMappingHandler(configuration); this.CreateHandler(configuration); // 序列化配置。 configuration.SerializeConfiguration(); this._buildEvent.Publish(new BuildEventArg(Status.Success)); }
private void ConfigSqlConfig(Configuration configuration, DbTable table, string configFile, string projectName) { XNamespace xmlns = "http://ibatis.apache.org/dataMapper"; var embedded = string.Format("{0}.{1}.xml, {2}", configuration.CurrentDatabase.Type, table.ClassName, projectName); if (!string.IsNullOrWhiteSpace(table.ModuleName)) { embedded = string.Format("{0}.{1}", table.ModuleName, embedded); } var xdocument = XDocument.Load(configFile); var exists = (from s in xdocument.Descendants(xmlns + "sqlMap") where s.Attribute("embedded") != null && s.Attribute("embedded").Value == embedded select s).Any(); if (!exists) { var sqlMapElement = new XElement(xmlns + "sqlMap"); sqlMapElement.SetAttributeValue("embedded", embedded); if (xdocument.Descendants(xmlns + "sqlMaps").Any()) { xdocument.Descendants(xmlns + "sqlMaps").FirstOrDefault().Add(sqlMapElement); } else { var sqlMapsElement = new XElement(xmlns + "sqlMaps"); sqlMapsElement.Add(sqlMapElement); xdocument.Root.Add(sqlMapsElement); } File.SetAttributes(configFile, FileAttributes.Normal); xdocument.Save(configFile); } }
/// <summary> /// 文件生成完毕后的处理。 /// </summary> /// <param name="configuration">代码生成配置信息</param> /// <param name="item">生成配置项</param> /// <param name="table">数据库表信息</param> /// <param name="fileName">文件名</param> public override void OnFileCreateComplated(Configuration configuration, Item item, DbTable table, string fileName) { if (item.Parameters.ContainsKey("project")) { var projects = item.Parameters["project"].Split('&'); foreach (var project in projects) { var dbType = configuration.CurrentDatabase.Type; var writerSqlMapFilePath = configuration.OutputFolder + "\\" + string.Format(project, configuration.BaseNamespace, dbType, "Writer"); var readerSqlMapFilePath = configuration.OutputFolder + "\\" + string.Format(project, configuration.BaseNamespace, dbType, "Reader"); if (File.Exists(writerSqlMapFilePath)) { this.ConfigSqlConfig(configuration, table, writerSqlMapFilePath, item.GetProjectName(configuration.BaseNamespace)); } if (File.Exists(readerSqlMapFilePath)) { this.ConfigSqlConfig(configuration, table, readerSqlMapFilePath, item.GetProjectName(configuration.BaseNamespace)); } } } }
/// <summary> /// 采用XSLT方式创建代码。 /// </summary> /// <param name="configuration"></param> /// <param name="item"></param> /// <param name="table"></param> private void CreateByXslt(Configuration configuration, Item item, DbTable table) { table.Namespace = item.GetNamespace(configuration.BaseNamespace, table.ModuleName); table.FullClassNameFormat = $"{table.Namespace}.{table.ClassName}{"{0}"}, {item.GetProjectName(configuration.BaseNamespace)}"; var xml = table.ToXml( configuration.CurrentDatabase, configuration.BaseNamespace, configuration.Author, configuration.BuildDate, configuration.CopyrightOwner); if (item.Dependencys != null) { var dependencys = new XElement("dependencys"); foreach (var dependency in item.Dependencys) { var dependencyItem = ConfigManager.Items[dependency]; if (dependencyItem == null || (dependencyItem.Name == "SearchResponse" && !table.HasSearchData)) { continue; } var dependencyNs = dependencyItem.GetNamespace(configuration.BaseNamespace, table.ModuleName); var element = new XElement("dependency", dependencyNs); element.SetAttributeValue("name", dependencyItem.Name); element.SetAttributeValue("className", string.IsNullOrWhiteSpace(dependencyItem.FileFormat) ? table.ClassName : string.Format(dependencyItem.FileFormat, table.ClassName)); element.SetAttributeValue("assembly", dependencyItem.GetProjectName(configuration.BaseNamespace)); var exists = (from d in dependencys.Descendants("dependency") where d.Value == dependencyNs select d).Any(); if (!exists) { dependencys.Add(element); } } xml.Root.Add(dependencys); } var templateFile = item.TemplateFile; var outputFile = item.GetOutputFile(configuration, table); XslHelper.Transform(xml, templateFile, outputFile); // 代码创建完成后的处理。 OnFileCreateComplated(configuration, item, table, outputFile); }
protected override void CreateHandler(Configuration configuration) { if (configuration?.Tables != null) { var tables = configuration.Tables.Where(t => t.IsEnabled); foreach (var sectionItem in ConfigManager.Items) { if (configuration.CurrentDatabase.Type != DatabaseType.MSSQL && sectionItem.Name == "SqlMap") { sectionItem.TemplateFile = sectionItem.TemplateFile.Replace("SqlMap.xslt", $"SqlMap_{configuration.CurrentDatabase.Type}.xslt"); } // 表的处理。 foreach (var table in tables) { if (sectionItem.TemplateFile.EndsWith("xslt", StringComparison.InvariantCultureIgnoreCase)) { if (table.IsView && sectionItem.IgnoreView) { continue; } if (table.IsEntityOnly && sectionItem.Name != "Entity") { continue; } if (!table.HasSearchData && sectionItem.Name == "SearchResponse") { continue; } this.CreateByXslt(configuration, sectionItem, table); } } } } }
/// <summary> /// 文件生成完毕后的处理。 /// </summary> /// <param name="configuration">代码生成配置信息</param> /// <param name="item">生成配置项</param> /// <param name="table">数据库表信息</param> /// <param name="fileName">文件名</param> public abstract void OnFileCreateComplated(Configuration configuration, Item item, DbTable table, string fileName);
private bool IsFirstCreate(Configuration configuration) { if ("Mercurius.Siskin".Equals(configuration.BaseNamespace, StringComparison.InvariantCultureIgnoreCase)) { return false; } var settingFile = $@"{configuration.OutputFolder}\pa.hdata"; if (File.Exists(settingFile)) { return false; } File.Create(settingFile); File.SetAttributes(settingFile, FileAttributes.Hidden | FileAttributes.ReadOnly); return true; }
/// <summary> /// 代码生成处理。 /// </summary> protected abstract void CreateHandler(Configuration configuration);
/// <summary> /// 初始化处理。 /// </summary> public abstract void Initialize(Configuration configuration);
private static void OnFileCreateComplated(Configuration configuration, Item sectionItem, DbTable table, string outputFile) { if (!string.IsNullOrWhiteSpace(sectionItem.Handler)) { var handlers = sectionItem.Handler.Split(';'); foreach (var handler in handlers) { IFileCreatedHandler fileCreateComplateHandler = null; if (_dictHandler.ContainsKey(handler)) { fileCreateComplateHandler = _dictHandler[handler]; } else { fileCreateComplateHandler = Activator.CreateInstance(Type.GetType(handler)) as IFileCreatedHandler; if (fileCreateComplateHandler != null) { _dictHandler.Add(handler, fileCreateComplateHandler); } } fileCreateComplateHandler?.OnFileCreateComplated(configuration, sectionItem, table, outputFile); } } }
protected void ConfigImports(Configuration configuration, Item item, DbTable table) { if (string.IsNullOrWhiteSpace(table.ModuleName)) { return; } XDocument xdocument = null; var projectName = item.Project.Split('\\').LastOrDefault(); var projectNamespace = item.GetProjectName(configuration.BaseNamespace); var projectPath = item.GetProjectFolder(configuration.OutputFolder, configuration.BaseNamespace); var configFile = string.Format(@"{0}\ApplicationContext-{1}.xml", projectPath, projectName); var assemblyResource = string.Format("assembly://{0}/{0}/ApplicationContext-{1}-{2}.xml", projectNamespace, projectName, table.ModuleName); if (!File.Exists(configFile)) { var file = new FileInfo(configFile); if (!file.Directory.Exists) { file.Directory.Create(); } xdocument = new XDocument(this.CreateElement("objects")); xdocument.Save(configFile, SaveOptions.None); } else { xdocument = XDocument.Load(configFile); } var xmlns = this.GetDefaultNamespace(); var exists = (from o in xdocument.Descendants(xmlns + "import") where o.Attribute("resource").Value == assemblyResource select o).Any(); if (!exists) { var element = this.CreateElement("import"); element.SetAttributeValue("resource", assemblyResource); var last = xdocument.Root.Descendants(xmlns + "import").LastOrDefault(); if (last != null) { last.AddAfterSelf(element); } else { var importComment = new XComment(string.Format("导入{0}模块的配置文件", table.ModuleDescription)); xdocument.Root.AddFirst(importComment); importComment.AddAfterSelf(element); } File.SetAttributes(configFile, FileAttributes.Normal); xdocument.Save(configFile, SaveOptions.None); } }
/// <summary> /// 项目初始化。 /// </summary> /// <param name="configuration">初始化配置</param> public override void Initialize(Configuration configuration) { if (File.Exists(@"Projects\CSharp.zip")) { this._buildEvent.Publish(new BuildEventArg(Status.Begin, "开始导入架构...")); var zipFile = ZipFile.Read(@"Projects\CSharp.zip", new ReadOptions { Encoding = Encoding.GetEncoding("GB2312") }); zipFile.ReadProgress += (sender, e) => { this._buildEvent.Publish(new BuildEventArg(Status.Building, $"正在解压{e.ArchiveName}文件...")); }; var entries = zipFile.Entries.ToList(); this._buildEvent.Publish(new BuildEventArg(Status.Building, "开始解压基础框架压缩包...")); foreach (var t in entries) { this._buildEvent.Publish(new BuildEventArg(Status.Building, $"解压{t.FileName}...")); t.FileName = t.FileName.Replace("Mercurius.Sparrow", configuration.BaseNamespace); t.Extract(configuration.OutputFolder, ExtractExistingFileAction.OverwriteSilently); } this._buildEvent.Publish(new BuildEventArg(Status.Building, "基础框架压缩包解压完成!")); foreach (var item in entries) { if (item.IsDirectory) { continue; } if (!this.NeedReplaceFile(item.FileName)) { continue; } this._buildEvent.Publish(new BuildEventArg(Status.Building, $"修改文件{item.FileName}中的命名空间...")); var fileName = $@"{configuration.OutputFolder}\{item.FileName}"; var reader = new StreamReader(fileName, Encoding.UTF8); var texts = reader.ReadToEnd(); reader.Dispose(); if (texts.Contains("Mercurius.Sparrow")) { texts = texts.Replace("Mercurius.Sparrow", configuration.BaseNamespace); var writer = new StreamWriter(fileName, false, Encoding.UTF8); writer.Write(texts); writer.Dispose(); } this._buildEvent.Publish(new BuildEventArg(Status.Building, $"修改文件{item.FileName}中的命名空间完成!")); } this._buildEvent.Publish(new BuildEventArg(Status.Success, "架构导入完成!")); } }
/// <summary> /// 转换SqlType为基本数据类型。 /// </summary> private void DbTypeMappingHandler(Configuration configuration) { var dbTypeMapping = ServiceLocator.Current.GetInstance<DbTypeMapping>(configuration.CurrentDatabase.Type.ToString()); for (var i = 0; i < configuration.Tables.Count; i++) { var table = configuration.Tables[i]; for (var j = 0; j < table.Columns.Count; j++) { var column = table.Columns[j]; column.BasicType = dbTypeMapping.GetBasicType(configuration.Language, column.SqlType); } } }