| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- 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
- {
- /// <summary>
- /// 运用T4模板生成文件
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="viewModel"></param>
- /// <param name="fileName"></param>
- /// <param name="fileType"></param>
- protected virtual async Task<bool> CreateT4Async<T>(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);
- }
- /// <summary>
- /// 创建文件
- /// </summary>
- /// <param name="viewModel"></param>
- /// <param name="sourcePath"></param>
- /// <param name="fileName"></param>
- /// <param name="content"></param>
- protected virtual async Task<bool> 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;
- }
- /// <summary>
- /// 添加文件到项目中
- /// </summary>
- /// <param name="projectName"></param>
- /// <param name="files"></param>
- protected virtual async Task AddFilesToProjectAsync(string projectName, List<string> 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);
- }
- }
- }
|