| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353 |
- using System.Collections.Generic;
- using System.Text.RegularExpressions;
- using System.Threading.Tasks;
- using EnvDTE;
- using Microsoft.VisualStudio.Shell;
- using VberAdmin.Models;
- namespace VberAdmin.Generating
- {
- public class Generator
- {
- private DTE Dte { get; }
- public TemplateViewModel ViewModel { get; set; }
- private IFileCreate Creator { get; set; }
- public Generator(DTE dte, IFileCreate creator)
- {
- ThreadHelper.ThrowIfNotOnUIThread();
- Dte = dte;
- ViewModel = GetViewModel();
- Creator = creator;
- }
- /// <summary>
- /// 执行生成文件
- /// </summary>
- public async Task ExecuteAsync()
- {
- await Creator.CreateAsync(ViewModel);
- }
- #region 获取模板模型
- /// <summary>
- /// 获取模板模型
- /// </summary>
- /// <returns></returns>
- private TemplateViewModel GetViewModel()
- {
- ThreadHelper.ThrowIfNotOnUIThread();
- Document doc = Dte.ActiveDocument;
- var projectItem = doc.ProjectItem;
- var project = projectItem.ContainingProject;
- TemplateViewModel model = new TemplateViewModel
- {
- ProjectName = project.Name.Replace(".Core", ""),
- BaseFolder = doc.Path
- };
- TextSelection sel = (TextSelection)doc.Selection;
- // ReSharper disable once SuspiciousTypeConversion.Global
- if (sel.ActivePoint.CodeElement[vsCMElement.vsCMElementClass] is CodeClass codeClass)
- {
- model.ClassNamespace = codeClass.Namespace.Name;
- model.HtmlPageTitle = ConvertDocComment(codeClass.DocComment);
- model.HtmlModalTitle = model.HtmlPageTitle;
- model.ClassName = codeClass.Name;
- foreach (CodeElement element in codeClass.Bases)
- {
- string name = element.FullName ?? "";
- string typeStr = Regex.Match(name, "(?<=<).*?(?=>)").Value;
- if (typeStr.Contains("System.Int32"))
- {
- model.IdType = "int";
- }
- else if (typeStr.Contains("System.Int64"))
- {
- model.IdType = "long";
- }
- else if (typeStr.Contains("System.String"))
- {
- model.IdType = "string";
- }
- else if (typeStr.Contains("System.Guid"))
- {
- model.IdType = "Guid";
- }
- if (!string.IsNullOrEmpty(model.IdType))
- break;
- }
- model.Columns = new List<ColumnViewModel>();
- foreach (CodeElement elem in codeClass.Members)
- {
- if (elem.Kind == vsCMElement.vsCMElementProperty)
- {
- // ReSharper disable once SuspiciousTypeConversion.Global
- if (elem is CodeProperty cp)
- {
- var attrType = cp.Type.AsString?.ToLower() ?? "";
- if (attrType.Contains("string") || attrType.Contains("int") || attrType.Contains("datetime") || attrType.Contains("long") || attrType.Contains("bool") || attrType.Contains("decimal") || attrType.Contains("short") || attrType.Contains("double") || attrType.Contains("float") || attrType.Contains("guid"))
- {
- var column = new ColumnViewModel
- {
- ColumnName = cp.Name,
- Comment = ConvertDocComment(cp.DocComment),
- AttrType = cp.Type.AsString?.Replace("System.", ""),
- IsGenreated = cp.Name != "CreatorUser" && cp.Name != "LastModifierUser" &&
- cp.Name != "DeleterUser"
- };
- if (cp.Attributes != null)
- {
- foreach (CodeElement element in cp.Attributes)
- {
- // ReSharper disable once SuspiciousTypeConversion.Global
- CodeAttribute ca = element as CodeAttribute;
- if (ca?.Name == "Required")
- {
- column.IsRequired = true;
- }
- if (ca?.Name == "MaxLength" || ca?.Name == "StringLength")
- {
- column.MaxLengthStr = ca.Value;
- }
- }
- }
- model.Columns.Add(column);
- }
- }
- }
- //else if (elem.Kind == vsCMElement.vsCMElementVariable)
- //{
- // CodeVariable cv = elem as CodeVariable;
- // if (cv != null && cv.Name == "ParentPath")
- // {
- // }
- //
- //}
- // Debug.WriteLine($"【CodeElement】 :value[{elem.Kind.ToString()}]");
- }
- }
- return model;
- }
- /// <summary>
- /// 获取注释
- /// </summary>
- /// <param name="docComment"></param>
- /// <returns></returns>
- private string ConvertDocComment(string docComment)
- {
- string newComment = docComment.Replace("<doc>\r\n<summary>\r\n", "").Replace("\r\n</summary>\r\n</doc>", "");
- return newComment;
- }
- //private void CodeClass(CodeClass cls)
- //{
- // string name = cls.Name;
- // string classNamespace = cls.Namespace.Name;
- // string comment = cls.Comment;
- // string docComment = cls.DocComment;
- // string infoLocation = cls.InfoLocation.ToString();
- // Debug.WriteLine($"【CodeClass】--[Name:{name}]--[Namespace:{classNamespace}]--[Comment:{comment}]--[DocComment:{docComment}]--[InfoLocation:{infoLocation}]");
- //}
- #endregion 获取模板模型
- #region 创建文件
- ///// <summary>
- ///// 生成DTO
- ///// </summary>
- //private void CreateDtos()
- //{
- // ThreadHelper.ThrowIfNotOnUIThread();
- // List<string> dtoFiles = new List<string>();
- // if (ViewModel.IsCreateDto)
- // {
- // if (CreateT4<CreateDto>(ViewModel.CreateDtoName))
- // dtoFiles.Add(ViewModel.DtoFolder + ViewModel.CreateDtoName);
- // }
- // if (ViewModel.IsUpdateDto)
- // {
- // if (CreateT4<UpdateDto>(ViewModel.UpdateDtoName))
- // dtoFiles.Add(ViewModel.DtoFolder + ViewModel.UpdateDtoName);
- // }
- // if (ViewModel.IsUpdateDto)
- // {
- // if (CreateT4<ListDto>(ViewModel.ListDtoName))
- // dtoFiles.Add(ViewModel.DtoFolder + ViewModel.ListDtoName);
- // }
- // if (dtoFiles.Any())
- // AddFilesToProject(ViewModel.ApplicationName, dtoFiles);
- //}
- ///// <summary>
- ///// 生成Application
- ///// </summary>
- //private void CreateApplications()
- //{
- // ThreadHelper.ThrowIfNotOnUIThread();
- // List<string> applicationFileList = new List<string>();
- // if (ViewModel.IsApplicationService)
- // {
- // if (CreateT4<Service>(ViewModel.ServiceName, 1))
- // applicationFileList.Add(ViewModel.ServiceFolder + ViewModel.ServiceName);
- // }
- // if (ViewModel.IsIApplicationService)
- // {
- // if (CreateT4<ServiceInterface>(ViewModel.ServiceInterfaceName, 1))
- // applicationFileList.Add(ViewModel.ServiceFolder + ViewModel.ServiceInterfaceName);
- // }
- // if (applicationFileList.Any())
- // AddFilesToProject(ViewModel.ApplicationName, applicationFileList);
- //}
- ///// <summary>
- ///// 生成Web
- ///// </summary>
- //private void CreateWebs()
- //{
- // ThreadHelper.ThrowIfNotOnUIThread();
- // List<string> webFileList = new List<string>();
- // if (ViewModel.IsController)
- // {
- // if (CreateT4<WebController>(ViewModel.ControllerName, 2))
- // webFileList.Add(ViewModel.ControllerFolder + ViewModel.ControllerName);
- // }
- // if (ViewModel.IsView)
- // {
- // if (CreateT4<WebView>(ViewModel.ViewsName, 3))
- // webFileList.Add(ViewModel.ViewsFolder + ViewModel.ViewsName);
- // }
- // if (webFileList.Any())
- // AddFilesToProject(ViewModel.WebName, webFileList);
- //}
- ///// <summary>
- ///// 运用T4模板生成文件
- ///// </summary>
- ///// <typeparam name="T"></typeparam>
- ///// <param name="fileName"></param>
- ///// <param name="fileType"></param>
- //private bool CreateT4<T>(string fileName, int fileType = 0)
- // where T : IT4CodeBase, new()
- //{
- // ThreadHelper.ThrowIfNotOnUIThread();
- // T t4 = new T { Model = ViewModel };
- // string pageContent = t4.TransformText();
- // string path = ViewModel.DtoFolder;
- // switch (fileType)
- // {
- // case 0:
- // path = ViewModel.DtoFolder;
- // break;
- // case 1:
- // path = ViewModel.ServiceFolder;
- // break;
- // case 2:
- // path = ViewModel.ControllerFolder;
- // break;
- // case 3:
- // path = ViewModel.ViewsFolder;
- // break;
- // }
- // return CreateFile(path, fileName, pageContent);
- //}
- ///// <summary>
- ///// 创建文件
- ///// </summary>
- ///// <param name="sourcePath"></param>
- ///// <param name="fileName"></param>
- ///// <param name="content"></param>
- //private bool CreateFile(string sourcePath, string fileName, string content)
- //{
- // ThreadHelper.ThrowIfNotOnUIThread();
- // string path = Path.GetTempPath();
- // Directory.CreateDirectory(path);
- // string file = Path.Combine(path, fileName);
- // File.WriteAllText(file, content, Encoding.UTF8);
- // try
- // {
- // if (string.IsNullOrEmpty(sourcePath))
- // sourcePath = @"..\..\";
- // if (!File.Exists(sourcePath))
- // Directory.CreateDirectory(sourcePath);
- // string sourceUrl = Path.Combine(sourcePath, fileName);
- // if (ViewModel.IsReplace)
- // File.Delete(sourceUrl);
- // if (!File.Exists(sourceUrl))
- // {
- // File.Copy(file, sourceUrl);
- // Dte.StatusBar.Text = $"VberCode:{fileName}代码已生成。";
- // return true;
- // }
- // }
- // finally
- // {
- // File.Delete(file);
- // }
- // return false;
- //}
- ///// <summary>
- ///// 添加文件到项目中
- ///// </summary>
- ///// <param name="projectName"></param>
- ///// <param name="files"></param>
- //public void AddFilesToProject(string projectName, List<string> files)
- //{
- // ThreadHelper.ThrowIfNotOnUIThread();
- // try
- // {
- // if (Dte != null)
- // {
- // foreach (EnvDTE.Project item in Dte.Solution.Projects)
- // {
- // if (item.Name == projectName)
- // {
- // foreach (string file in files)
- // {
- // Dte.StatusBar.Text = $"VberCode:添加文件[{file}]...";
- // item.ProjectItems.AddFromFile(file);
- // }
- // item.Save();
- // break;
- // }
- // if (item.ProjectItems != null)
- // {
- // foreach (ProjectItem childItem in item.ProjectItems)
- // {
- // if (childItem.Name == projectName)
- // {
- // foreach (string file in files)
- // {
- // Dte.StatusBar.Text = $"VberCode:添加文件[{file}]...";
- // childItem.SubProject?.ProjectItems?.AddFromFile(file);
- // }
- // childItem.SubProject?.Save();
- // break;
- // }
- // }
- // }
- // }
- // }
- // }
- // catch
- // {
- // //ignored
- // //Debug.WriteLine(e);
- // }
- //}
- #endregion 创建文件
- }
- }
|