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. CI 3.0.6 控制器打印base_url 地址不为 localhost的解决方法

    1.在application\config\autoload.php 第92行 加载url    $autoload['helper'] = array('url'); 2.application\c ...

  2. gdb 常用内容

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

  3. hive配置以及在启动过程中出现的问题

    一.hive配置 1.安装环境 在hadoop-1.2.1集群上安装hive-1.2.1 2.将hive-1.2.1环境变量添加到PATH路径下 使用如下命令打开配置文件 nano /etc/prof ...

  4. web.Config配置数据库的连接

    <!--连接字符串设置--> <connectionStrings> <add name="ConnString" connectionString= ...

  5. ZACC_DOCUMENT

    method if_ex_acc_document~change. data: wa_extension type bapiparex, ext_value() type c, wa_accit ty ...

  6. java selenium (十三) 智能等待页面加载完成

    我们经常会碰到用selenium操作页面上某个元素的时候, 需要等待页面加载完成后, 才能操作.  否则页面上的元素不存在,会抛出异常. 或者碰到AJAX异步加载,我们需要等待元素加载完成后, 才能操 ...

  7. 总结js中数据类型的bool值及其比较

    首先需要知道的是,js中有6个值为false,分别是: 0, '', null, undefined, NaN 和 false, 其他(包括{}, [], Infinity)为true. 可以使用Bo ...

  8. Asp.net页面引用SAP IQ 16 iAnywhere.Data.SQLAnywhere.V4.0.dll报错,语言文件没找到

    参考http://sqlanywhere-forum.sap.com/questions/20420/saconnection-threw-an-exception-cannot-find-the-l ...

  9. WinPipe后门程序代码示例(仅限技术交流)

    具体怎么编译,生成执行程序,不懂得先学习C++程序代码编译和集成开发环境. 多的不说了,只有两个代码文件,一个头文件,一个源文件.不多说了,直接上干货. (恶意使用,或者商用,后果自负,与本人无关.) ...

  10. 多个radiobutton选定一个

    asp.net中怎么判断其中一个radiobutton被选中后登录的是一个窗体,另一个被选中后登录的是另一个窗体. 页面设置两按钮的GroupName为同一组值: <asp:RadioButto ...