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 ...
随机推荐
- nodejs的第五天学习笔记
一.调试nodejs代码 1)使用console.log() 使用麻烦,用了以后还要删除 2)nodejs的自带调试器 -node debug a.js 没有任何作用,一个玩具,将来有一天可以会变得强 ...
- MySQL DDL 整理
DDL is Data Definition Language statements. Some examples:数据定义语言,用于定义和管理 SQL 数据库中的所有对象的语言 -- 清空表内容 T ...
- 【WebGoat习题解析】Parameter Tampering->Bypass HTML Field Restrictions
The form below uses HTML form field restrictions. In order to pass this lesson, submit the form with ...
- Python’s SQLAlchemy vs Other ORMs[转发 2]Storm
Storm Storm is a Python ORM that maps objects between one or more databases and Python. It allows de ...
- HTML 或 CSS 文件中引用的图片文件移动到任意位置
对于一个套接字的输入操作,第一步通常涉及等待数据从网络到达,当所等待分组到达时,被复制到内核的某个缓冲区: 第二步就是把数据从内核缓冲区复制到应用进程缓冲区.通过 Session 的 createQu ...
- Migrating an ASP.NET MVC application to ADFS authentication
I recently built an ASP.NET application at work to help track internal use of our products. It's bee ...
- git代码冲突解决
1.git fetch 跟git pull差别是前者不会和本地直接merge code,而后者会,所以git fetch更安全 git fetch origin master:tmpgit dif ...
- iOS:使用代理模式监听开关状态改变事件
记一次解决跨控制器监听开关状态改变的尝试. 为了统一设置UITableViewCell里的内容,自定义了UITableViewCell类的一个基类,命名为SettingCell.SettingCell ...
- Centos 6.5 把自带python 2.6.6, 升级到 2.7
http://blog.csdn.net/jcjc918/article/details/11022345
- opencv用imread( argv[1], 1)读取图片
显示一幅图:主要是运用功能:imread namedWindow imshowimread:从字面意思我们就可以看懂,用来读取图片的:namedWindow:显然,我们也可以看到这是用来命名窗口名称的 ...