Use EnvDTE add/remove multiple files to project

By admin | décembre 17, 2013

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 加载文件到解决方案的更多相关文章

  1. NPM包管理器入门(附加cnpm : 无法加载文件错误解决方案)

    NPM 包管理器 1.作用: 快速构建nodejs工程 快速安装和依赖第三个模块 2.使用方法 快速构建 npm init 会得到一package.json文件 { "name": ...

  2. 能加载文件或程序集 HRESULT:0x80070057 (E_INVALIDARG)的异常的解决方案

    今天下午由于机器蓝屏后,导致我的VS不能够调试我的网站了. 症状就是 : VS无法调试,但是可以编译和发布.而且只是 我在调试时蓝屏的那个项目 不能调试. 出现的错误就是: 能加载文件或程序集“Eny ...

  3. 关于:未能加载文件或程序集“ICSharpCode.SharpZipLib”或它的某一个依赖项异常的解决方案

    问题: 今天项目迁移忽然又个ICSharpCode.SharpZipLib.dll 程序包丢失了,于是我在网上下载一个这样的包,结果程序运行就提示:未能加载文件或程序集“ICSharpCode.Sha ...

  4. 类似“未能加载文件或程序集“tesseractengine3”或它的某一个依赖项”等一些问题的解决方案

    有些时候我们引用了一些32位的dll,结果就会出现类似“未能加载文件或程序集“tesseractengine3”或它的某一个依赖项”这样的问题,原因是IIS的应用程序池的设置中默认是不启用32位的应用 ...

  5. 未能加载文件或程序集EntityFramework, Version=6.0.0.0解决办法

    其他信息: 未能加载文件或程序集"EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934 ...

  6. 目标平台、活动平台 配置,出现未能加载文件或程序集“xxx”或它的某一个依赖项报错

    今天在做动态加载程序集的时候,发现明明程序集存在的情况下,还是依然报“未能加载文件或程序集“xxx”或它的某一个依赖项报错”的错误,排除了程序和配置的错误后,怀疑是否是环境的问题,于是百度加msdn后 ...

  7. 未能加载文件或程序集“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 ...

  8. resx文件在X64位编译,提示“未能加载文件或程序集”的问题?

    原文:resx文件在X64位编译,提示"未能加载文件或程序集"的问题? resx文件在X64位编译,提示"未能加载文件或程序集"的问题? 解答: 错误现象如下 ...

  9. 未能加载文件或程序集Microsoft.ReportViewer.WebForms, Version=10.0.0.0

    解决方案如下ASP.NET项目使用VS2010开发,部署到windows 2008环境中,出现未能加载文件或程序集“Microsoft.ReportViewer.WebForms, Version=1 ...

随机推荐

  1. WPF界面布局——Canvas

    Canvas用于定义一个区域,称为画布,用于完全控制每个元素的精确位置.它是布局控件中最为简单的一种,直接将元素放在指定位置,使用Canvas时,必须指定一个子元素的位置(相对于Canvas),否则所 ...

  2. [原创] Easy SysLite V1.2 (2016.5.29更新,新增加WIN10支持,一个程序适配所有系统减肥)

    [原创] Easy SysLite V1.2 (2016.5.29更新,新增加WIN10支持,一个程序适配所有系统减肥) nohacks 发表于 2016-5-29 17:12:51 https:// ...

  3. SAP 采购订单收货时报错:对于采购订单xxxx无收货可能

    因为这个问题查了挺长时间,所以写在博客里记录下. 报错详细: 每个公司的配置不同,我公司遇到的这个问题原因是这里的确认控制是从信息记录带过来的,问题解决方法是,修改下确认控制的选项: 修改确认控制的后 ...

  4. 自定义UI集成微信、QQ、微博分享功能

    目前社会化分享是一个非常常见的功能,通过阅读官方文档可以进行对应平台的分享.在项目中原本有微信的分享,后来需要集成QQ和微博的分享,于是想着用ShareSDK,在使用的过程中发现ShareSDK中的w ...

  5. loadrunner json

    Action(){ web_custom_request("JRPT_WriteLog", //VuGen中树形视图中显示的名称 "Url=url", //请求 ...

  6. gdb 常用内容

    gdb exegdb exe coregdb -p info m TAB ^関数の先頭 info b ^list the breakpoint set args -a test ^引数設定 show ...

  7. jQuery事件绑定on()、bind()与delegate() 方法详解

    jquery中有四种事件绑定函数,bind(),live(),on(),delegate(),由于live现在并不常用,因此不做过多解释. 1. bind()用法 $("div p" ...

  8. 20145224&20145238 《信息安全系统设计基础》 第三次实验

    20145224&20145238 <信息安全系统设计基础>第三次实验 课程:信息安全系统设计基础 班级:1452 姓名:陈颢文 荆玉茗 学号:20145224 20145238 ...

  9. 课程作业01:模仿JavaAppArguments.java示例,编写一个程序,此程序从命令行接收多个数字,求和之后输出结果。

    1.设计思想: 首先是从JavaAppArguments.java示例开始,此示例已打印参数,定义数字 之和和作为存储单位的整型,然后将输入参数的字符串转化为整型,之后求和即可. 2.程序流程图: 3 ...

  10. 一步一步将Vim打造成C++超级IDE

    文/嶽永鹏 最近从MS Windows 转到了Liunx,花了一段时间熟悉和学习Liunx环境.有时候,真的很是怀念MS Vistual Studio那种超级智能的开发环境,总是想在Vim拾起那些曾进 ...