I am trying to get up to speed with T4 templates. I found the following example ( here ):
<#@ template hostspecific="True" #>
<#@ output extension="txt" #>
<#@ include file="T4Toolbox.tt" #>
<#@ import namespace="EnvDTE" #>
<#
CodeEnum enumeration = GetEnum("ContactType.cs");
WriteLine("Found enumeration " + enumeration.Name);
foreach (CodeElement element in enumeration.Children)
{
CodeVariable value = element as CodeVariable;
if (value != null)
WriteLine("… found value " + value.Name);
}
#>
<#+
private CodeEnum GetEnum(string enumFile)
{
ProjectItem projectItem = TransformationContext.FindProjectItem(enumFile);
FileCodeModel codeModel = projectItem.FileCodeModel;
return FindEnum(codeModel.CodeElements);
}
private CodeEnum FindEnum(CodeElements elements)
{
foreach (CodeElement element in elements)
{
CodeEnum enumeration = element as CodeEnum;
if (enumeration != null)
return enumeration;
enumeration = FindEnum(element.Children);
if (enumeration != null)
return enumeration;
}
return null;
}
#>
Somehow none of the types that are in the EnvDTE namespace are recognized. I am using the Visual T4 extension. All EnvDTE types are underlined in red. The template doesn't run, and I'm getting a list of errors like:
The type or namespace ... could not be found (are you missing a using directive or assembly reference?)
Does anyone know how to solve this?
try to use like this
DTE env = GetVSEnvironment();
....
private DTE GetVSEnvironment() {
DTE env = null;
var provider = Host as IServiceProvider;
if (provider != null) {
env = provider.GetService(typeof(DTE)) as DTE;
}
if (env == null) {
throw new InvalidOperationException("Template must be executed from Visual Studio");
}
return env;
}
now you do env.blablabla
eg: env.Solution.FindProjectItem(Host.TemplateFile).ContainingProject;
Hmm, I'd think that the following include
<#@ template hostspecific="True" #>
would pull in the assembly, but maybe not. First, try adding the following to the top of your template.
<#@ Assembly Name="EnvDTE" #>
If that doesn't work, try adding the full path. For me, its
<#@ Assembly Name="C:\Program Files (x86)\Common Files\microsoft shared\MSEnv\PublicAssemblies\envdte.dll" #>
您是否在项目中添加了对ENVDTE和ENVDTE80(90等)的引用?
添加此行对我有用:
<#@ Assembly Name="EnvDTE" #>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.