using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Community.VisualStudio.Toolkit; using VberAdmin.Models; using VberAdmin.Templates.T4; namespace VberAdmin.Generating; public abstract class FileCreateBase { /// /// 运用T4模板生成文件 /// /// /// /// /// protected virtual async Task CreateT4Async(TemplateViewModel viewModel, string fileName, int fileType = 0) where T : IT4CodeBase, new() { 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 await CreateFileAsync(viewModel, path, fileName, pageContent); } /// /// 创建文件 /// /// /// /// /// protected virtual async Task CreateFileAsync(TemplateViewModel viewModel, string sourcePath, string fileName, string content) { 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); await VS.StatusBar.ShowMessageAsync($"VberCode:{fileName}代码已生成。"); return true; } } finally { File.Delete(file); } return false; } /// /// 添加文件到项目中 /// /// /// protected virtual async Task AddFilesToProjectAsync(string projectName, List files) { try { var projects = await VS.Solutions.GetAllProjectsAsync(); foreach (var project in projects) { if (project.Name == projectName) { foreach (var file in files) { await VS.StatusBar.ShowMessageAsync($"VberCode:添加文件[{file}]..."); await project.AddExistingFilesAsync(file); } await project.SaveAsync(); break; } } } catch { //ignored //Debug.WriteLine(e); } } }