views:

534

answers:

4

I have a T4 template for a class set up with TextTemplatingFileGenerator Custom Tool in Visual Studio:

<#@ template language="C#v3.5" hostspecific="True" debug="True" #>
<#
  var className = System.IO.Path.GetFileNameWithoutExtension(Host.TemplateFile);
  var namespaceName = "MyNamespace";
#>

namespace <#= namespaceName #>
{
    public static class <#= className #>
    {
        // some generated code
    }
}

How can I get the value of the "Custom Tool Namespace" property in Visual Studio, so I don't have to hardcode the namespace?

I would even be happy with the default namespace for the C# project.

A: 

I know this doesn't really answer your question but this guy Oleg Sych has a lot of information about T4 stuff on his site. He may be able to help you out with this one. Another one to look at would be Damien Guard.

Joshua Cauble
Thanks for the links. I still cannot find any example that gets the Namespace.
Hallgrim
-1: great answer to a different question.
John Saunders
-1 for too general an answer
GarethJ
+4  A: 

Damien Guard includes some code in a blog posting which retrieves the Custom Tool Namespace for a given file:

public override String GetCustomToolNamespace(string fileName)
{
    return dte.Solution.FindProjectItem(fileName).Properties.Item("CustomToolNamespace").Value.ToString();
}
sixlettervariables
+6  A: 

Here is what you can do with T4 Toolbox:

<#@ template language="C#v3.5" hostspecific="True" debug="True" #> 
<#@ include file="T4Toolbox.tt" #>
<# 
  var namespaceName = TransformationContext.DefaultNamespace; 
#> 

DefaultNamespace property of TransformationContext class returns a string with namespace based on the root namespace of your project and the location of your .tt file in it (i.e. it treats folders as namespaces). This way you don't have to specify Custom Tool Namespace property for every instance of your .tt file.

If you prefer to use the Custom Tool Namespace property, you can pass Host.TemplateFile to the GetCustomToolNamespace method posted by @sixlettervariables.

Oleg

Oleg Sych
+4  A: 

If you're using Visual Studio 2010, you can retrieve the namespace by checking the CallContext's "NamespaceHint" property.

System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint");

GarethJ
+1: It solved my problem too.
Carlos Loth