t4 加载文件到解决方案

Use EnvDTE add/remove multiple files to project

By admin | décembre 17, 2013

Un commentaire

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/
时间: 2024-12-09 08:52:55

t4 加载文件到解决方案的相关文章

未能加载文件或程序集“”或它的某一个依赖项。系统找不到指定的文件

连续两天都为这个运行时错误“类型初始值设定项引发异常”而烦恼,调试也不知道哪里出了问题.上网Google一下,一大堆相同的问题,可是按照那些方法折腾来折腾去,问题还是一样.最后在CSDN上发帖子问了,果然“重赏之下必有勇夫”,很快就有高手回复了,问题也随着解决了.哈哈.在此写个随笔,以后如果大家遇到类似问题,也可参考一下,自己也做个备忘,不然放在电脑上,又找不到,我的电脑文件到处乱放,有时连我自己都找不到^_^. 问题是这样嘀: 项目采用了三层架构和工厂模式,并借鉴了PetShop的架构,因为这

未能加载文件或程序集“EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”

 未能加载文件或程序集“EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089” 使用nuget管理程序包,有可能在不同时间安装不同版本的Entity Framework:在项目创建初期安装的是6.0.0.0版本,后来添加的类库,安装了6.1.1版本,所以出现这个问题. 解决办法: 1. 工具 -> 库程序包管理器 -> 管理解决方案的nuget程序包 2. 在选中已安装的包中找到En

未能加载文件或程序集“Newtonsoft.Json, Version=4.5.0.0[已解决]

在使用百度UEditor,不小心将Newtonsoft.Json,升级了,然后就报的一个错,说: 其他信息: 未能加载文件或程序集“Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed”或它的某一个依赖项.找到的程序集清单定义与程序集引用不匹配. (异常来自 HRESULT:0x80131040),各种清理解决方案都不行 ,后来在网站找到了一个方法 ,说插入以下代码就可以了: <run

Assembly.Load未能加载文件或程序集“”或它的某一个依赖项。系统找不到指定的文件

项目采用了三层架构和工厂模式,并借鉴了PetShop的架构,因为这个项目也是采用分布式的数据库,目前只有三个数据库,主要出于提高访问性能考虑. 原来是按照网上对PetShop的介绍来给各项目添加引用的. 1.Web 引用 BLL.2.BLL 引用 IDAL,Model,使用DALFactory创建实例.3.IDAL 引用 Model. 在编程中,使用反射(IoC)是一个很好的架构.在.Net中,System.Reflection命名空间提供了对反射的支持.然而,很多朋友在使用Assembly.L

未能加载文件或程序集“COM.Excel”或它的某一个依赖项

未能加载文件或程序集"COM.Excel"或它的某一个依赖项.参数错误. (异常来自 HRESULT:0x80070057 (E_INVALIDARG)). 解决方案:1涉及到Excel,程序集加载不成功.2去看看这个待加载的Excel程序集文件存在不存在.3目录,在网站根目录下的bin文件夹,结果有文件COM.Excel.dll和Excel.dll两个动态库.看来就是这两个文件了.4存在又加载不成功?这是什么原因,这个路径应该也是正确的,那就是文件路径存在,也找到了,但是加载不成功.

.NET 未能加载文件或程序集&ldquo;xxx&rdquo;或它的某一个依赖项。试图加载格式不正确的程序。

症状: 未能加载文件或程序集"xxx"或它的某一个依赖项.试图加载格式不正确的程序.说明: 执行当前 Web 请求期间,出现未处理的异常.请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息.异常详细信息: System.BadImageFormatException: 未能加载文件或程序集"xxx"或它的某一个依赖项.试图加载格式不正确的程序.源错误:执行当前 Web 请求期间生成了未处理的异常.可以使用下面的异常堆栈跟踪信息确定有关异常原因和发

异常:未能加载文件或程序集”DAL”或它的某一个依赖项——解决办法

下面是我再使用抽象工厂+反射重构机房时,在Factoy中出现了下面一个问题: 去网上查了一下资料,发现这是一个很普遍的问题,它出现的原因主要有两种: 第一种: 加载DLL路径错误.解决办法是调整D层生成DLL的路径到UI的bin文件夹中.如下图: 反射的一个原则是:一切皆以UI层的bin文件夹中的dll名称为中心,说白一点,dll就是一个类库.我理解的反射,就是一串拼接的字符串,组成要实例化的类的名字.使用反射加载类时,默认是从UI层中的bin中找的,所以要在UI的bin文件夹下生成D层类的dl

“System.BadImageFormatException”类型的未经处理的异常在 PurchaseDevices.Access.dll 中发生 其他信息: 未能加载文件或程序集“System.Data.SQLite, Version=1.0.66.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139”或它的某一个依赖项。试图加载格式不正确

引用sqlite的程序集时,有时会报如下异常: "System.BadImageFormatException"类型的未经处理的异常在 PurchaseDevices.Access.dll 中发生 其他信息: 未能加载文件或程序集"System.Data.SQLite, Version=1.0.66.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139"或它的某一个依赖项.试图加载格式不正确的程序. 解决方案:在配置

未能加载文件或程序集Office, Version=2.2.0.0, Culture=neutral, PublicKeyToken=null或它的某一个依赖项。找到的程序集清单定义与程序集引用不匹配。 (异常来自 HRESULT:0x80131040)

未能加载文件或程序集Office, Version=2.2.0.0, Culture=neutral, PublicKeyToken=null或它的某一个依赖项.找到的程序集清单定义与程序集引用不匹配. (异常来自 HRESULT:0x80131040) 1.导出Excel程序调试起来很正常,发布到服务器上却出错. 错误:未能加载文件或程序集“Office, Version=2.2.0.0, Culture=neutral, PublicKeyToken=null”或它的某一个依赖项.找到的程序