t4 加载文件到解决方案
Use EnvDTE add/remove multiple files to project
Project Source
Source: EnvDTEManipulate
Licence: MIT
EnvDTE is an assembly-wrapped COM library containing the objects and members for Visual Studio core automation.
It’s widely used in Visual Studio Plugins to provide ability manipulate visual studio functionalities.
By using EnvDTE inside TextTemplate, we can create a easy solution for massive file creation.
Usage
First you need include EnvDTE into TextTemplate
<#@ assembly name="EnvDTE" #>
<#@ import namespace="EnvDTE" #>
Also, you need to set the hostspecific to « true ».
<#@ template debug="false" hostspecific="true" language="C#" #>
This will allow you to use ITextTemplateEngineHost instance(Host), which allows you to access current TextTemplate instance.
Then using following code to obtain an instance of EnvDTE.DTE
var host = this.Host; //ITextTemplateEngineHost
var serviceProvider = (IServiceProvider)host; //Convert Host to IServiceProvider
var dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE)); //Using IServiceProvider to get instance for EnvDTE
Get current solution
///<summary>
/// Get current solution instance
/// http://msdn.microsoft.com/en-us/library/envdte.solution_members(v=vs.90).aspx
///</summary>
EnvDTE.Solution getCurrentSolution(DTE dte)
{
return dte.Solution;
}
Get project item of text template file
///<summary>
/// Get project item of this text template file
/// http://msdn.microsoft.com/en-us/library/envdte.projectitem_members(v=vs.90).aspx
///</summary>
EnvDTE.ProjectItem getProjectItemOfThisTextTemplate(DTE dte)
{
return dte.Solution.FindProjectItem(this.Host.TemplateFile);
}
Get current project
EnvDTE.Project getCurrentProject(DTE dte)
{
return getProjectItemOfThisTextTemplate(dte).ContainingProject;
}
Add subitem under project text template
void addSubItem(DTE dte, string path)
{ var item = getProjectItemOfThisTextTemplate(dte); //item.Collection
//http://msdn.microsoft.com/fr-fr/library/envdte.projectitems_members(v=vs.90).aspx //Using add from template to add sub item into Text Template
item.ProjectItems.AddFromTemplate(this.Host.TemplateFile, path);
}
Clear all subitems under current text template file
void clearTextTemplateGeneratedItems(DTE dte, bool deleteDiskFile = false)
{
var item = getProjectItemOfThisTextTemplate(dte); //item.Collection only provides insertion functions.
foreach(ProjectItem subItem in item.ProjectItems)
{
File.Delete(subItem.FileNames[1]);
subItem.Delete();
}
}
Example
Create class file and sql file from xml file: Models.xml
<?xml version="1.0" encoding="utf-8" ?>
<Models>
<Model name="MyUser">
<Property name="FirstName" type="string"></Property>
<Property name="LastName" type="string"></Property>
</Model>
<Model name="MyGroup">
<Property name="Name" type="string"></Property>
</Model>
</Models>
Create models for this xml structure:
class Model
{
public string name { get; private set; }
public IReadOnlyList properties { get; private set; } public Model(XmlNode node)
{
if(node.Attributes["name"]!=null) name = node.Attributes["name"].Value;
var properties = new List(); foreach(XmlNode subNode in node.SelectNodes("Property"))
{
properties.Add(new Property(subNode));
} this.properties = properties;
}
} class Property
{
public string name { get; private set; }
public string type { get; private set; }
public Property(XmlNode node)
{
if(node.Attributes["name"]!=null) name = node.Attributes["name"].Value;
if(node.Attributes["type"]!=null) type = node.Attributes["type"].Value;
} public string getSqlType() {
if(type=="string") return "nvarchar(100)"; return "ERROR:"+type+"";
}
}
Using XmlDocument class load xml file:
XmlDocument doc = new XmlDocument();
doc.Load(this.Host.ResolvePath("Models.xml")); this.clearTextTemplateGeneratedItems(dte, true); List models = new List(); foreach(XmlNode node in doc.SelectNodes("/Models/Model"))
models.Add(new Model(node));
Then generate class file from Models
///<summary>
/// Generate csharp class files
///</summary>
void GenerateClassFile(DTE dte, IEnumerable models)
{
foreach(Model m in models)
{
#>
public class <#= m.name #> {
<#+ foreach(var p in m.properties) { #>
public <#= p.type #> <#= p.name #> { get; set; }
<#+ } #>
}
<#+
var filePath = Host.ResolvePath("") + "\\" + m.name + ".cs"; //attention, file path must use "\" not "/" using(StreamWriter w = File.CreateText(filePath))
{
//Write the code generated to file
w.WriteLine(this.GenerationEnvironment.ToString()); //Empty the code generated
this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
}
//Add item to solution
this.addProjectItem(dte,filePath);
}
}
And generate SQL files from Models
///<summary>
/// Generate SQL files
///</summary>
void GenerateSQLFile(DTE dte, IEnumerable models)
{
foreach(Model m in models)
{
#>
CREATE TABLE <#= m.name #> (
<#+ foreach(var p in m.properties) { #>
<#= p.name #> <#= p.getSqlType() #>
<#+ } #>
)
<#+
var filePath = Host.ResolvePath("") + "\\" + m.name + ".sql"; //attention, file path must use "\" not "/" using(StreamWriter w = File.CreateText(filePath))
{
//Write the code generated to file
w.WriteLine(this.GenerationEnvironment.ToString()); //Empty the code generated
this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
}
//Add item to solution
this.addProjectItem(dte,filePath);
}
} 转自 :http://shengjieinsight.com/blog/2013/12/use-envdte-addremove-multiple-files-to-project/
t4 加载文件到解决方案的更多相关文章
- NPM包管理器入门(附加cnpm : 无法加载文件错误解决方案)
NPM 包管理器 1.作用: 快速构建nodejs工程 快速安装和依赖第三个模块 2.使用方法 快速构建 npm init 会得到一package.json文件 { "name": ...
- 能加载文件或程序集 HRESULT:0x80070057 (E_INVALIDARG)的异常的解决方案
今天下午由于机器蓝屏后,导致我的VS不能够调试我的网站了. 症状就是 : VS无法调试,但是可以编译和发布.而且只是 我在调试时蓝屏的那个项目 不能调试. 出现的错误就是: 能加载文件或程序集“Eny ...
- 关于:未能加载文件或程序集“ICSharpCode.SharpZipLib”或它的某一个依赖项异常的解决方案
问题: 今天项目迁移忽然又个ICSharpCode.SharpZipLib.dll 程序包丢失了,于是我在网上下载一个这样的包,结果程序运行就提示:未能加载文件或程序集“ICSharpCode.Sha ...
- 类似“未能加载文件或程序集“tesseractengine3”或它的某一个依赖项”等一些问题的解决方案
有些时候我们引用了一些32位的dll,结果就会出现类似“未能加载文件或程序集“tesseractengine3”或它的某一个依赖项”这样的问题,原因是IIS的应用程序池的设置中默认是不启用32位的应用 ...
- 未能加载文件或程序集EntityFramework, Version=6.0.0.0解决办法
其他信息: 未能加载文件或程序集"EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934 ...
- 目标平台、活动平台 配置,出现未能加载文件或程序集“xxx”或它的某一个依赖项报错
今天在做动态加载程序集的时候,发现明明程序集存在的情况下,还是依然报“未能加载文件或程序集“xxx”或它的某一个依赖项报错”的错误,排除了程序和配置的错误后,怀疑是否是环境的问题,于是百度加msdn后 ...
- 未能加载文件或程序集“Newtonsoft.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=30a [问题点数:40分,结帖人u010259408]
未能加载文件或程序集“Newtonsoft.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=30a [问题点数:40分,结帖人u01025 ...
- resx文件在X64位编译,提示“未能加载文件或程序集”的问题?
原文:resx文件在X64位编译,提示"未能加载文件或程序集"的问题? resx文件在X64位编译,提示"未能加载文件或程序集"的问题? 解答: 错误现象如下 ...
- 未能加载文件或程序集Microsoft.ReportViewer.WebForms, Version=10.0.0.0
解决方案如下ASP.NET项目使用VS2010开发,部署到windows 2008环境中,出现未能加载文件或程序集“Microsoft.ReportViewer.WebForms, Version=1 ...
随机推荐
- Connection broken for id 62, my id = 70, error =
启动费zokeeper失败,报错如下:Connection broken for id 62, my id = 70, error = 原因是因为zoo.cfg中server.id不正确. serve ...
- 20161117__修改yum源
1.CentOS6.5中修改yum源 http://www.cnblogs.com/liuling/p/2014-4-14-001.html 在自己安装的CentOS6.5中使用yum安装软件,总是提 ...
- 无法删除对象 '产品',因为该对象正由一个 FOREIGN KEY 约束引用。
在删除northwindcs表时,发生报错,消息 3726,级别 16,状态 1,第 2 行,无法删除对象 '产品',因为该对象正由一个 FOREIGN KEY 约束引用.此时判断是因为有其他表的外键 ...
- [官方软件] Easy Sysprep v4.3.29.602 【系统封装部署利器】(2016.01.22)--skyfree大神
[官方软件] Easy Sysprep v4.3.29.602 [系统封装部署利器](2016.01.22) Skyfree 发表于 2016-1-22 13:55:55 https://www.it ...
- samba完美安装
感觉是一个相当强大的东西. Samba是在Linux和UNIX系统上实现SMB协议的一个免费软件.它为局域网内的不同计算机之间提供文件及打印机等资源的共享服务.为客户机/服务器型协议,客户机通过该协议 ...
- 支撑双十一的,不仅仅是AliSQL,也不仅仅是Oceanbase
全棉时代,作为稳健医疗集团的全资子公司,传承了稳健医疗集团在医用棉制品行业20年的专业技术和生产经验,以其独创的 "全棉水刺无纺布专利工艺"为核心技术载体,成功实现了医用产品向民用 ...
- linux command
ubuntu start network:sudo service network-manager start
- 了解Android的编译器
了解一下Android的编译器并记录下来: Android在4.4以前是使用Dalvik VM的,通过Just In Time(JIT即时编译)来完成编译工作,在Android4.4提供了一种测试版本 ...
- swift_Class类的继承
//: Playground - noun: a place where people can play var str = "Hello, playground" //***** ...
- HashMap,LinkedHashMap,TreeMap的区别
Map主要用于存储健值对,根据键得到值,因此不允许键重复(重复了覆盖了),但允许值重复. Hashmap 是一个最常用的Map,它根据键的HashCode 值存储数据,根据键可以直接获取它的值,具有很 ...