Git Product home page Git Product logo

t4toolbox's Introduction

T4 Toolbox

T4 Toolbox extends the code generation functionality of the T4 text templates in Visual Studio and allows you to:

  • Generate multiple output files from a single text template
  • Automatically add output files to one or more projects and folders
  • Automatically add or check-out generated files from source control
  • Edit text templates in Visual Studio 2015 with syntax colorization, outlining, QuickInfo tooltips, error reporting and statement completion

You can install the latest stable version of T4 Toolbox using the Extension Manager in Visual Studio or download it from the marketplace. To learn more, visit the Getting Started wiki page.

Building T4 Toolbox

Build status

Pre-requisites

Open T4Toolbox.sln in Visual Studio and build it. The NuGet packages the solution depends on should be restored automatically by Visual Studio. If you have disabled the automatic NuGet package restore in Visual Studio options, you can restore them manually by launching the NuGet Package Manager from the Solution Explorer.

The Debug configuration of the solution builds fast. It builds in seconds and you'll want to use it most of the time to stay productive.

The Release configuration of the solution builds slow because it runs FxCop and StyleCop checks. It can take a minute or more to build and you'll want to avoid it while working with tests, because Test Explorer builds the entire solution for every test run.

Build the Release configuration before submitting pull requests.

Running Tests

The unit test projects (*.Tests.csproj) contain close to a thousand tests. They are fast, but you'll want to run them separately from the integration tests to keep the test runs under 10 seconds. For that:

  • Enter the following filter in the Test Explorer: -Project:Integration (the dash is important).
  • Ensure that no test settings file is selected in the Test / Test Settings menu of Visual Studio.

The integration test projects (*.IntegrationTests.csproj) contain close to a hundred tests. They have to be executed by a special test host inside of the Experimental instance of Visual Studio. The test host is slow, and you'll want to exclude the unit tests to keep the integration test runs under a minute. For that:

  • Enter the following filter in the Test Explorer: Project:Integration (there should be no dash).
  • Select LocalTestRun.testsettings in the Test / Test Settings menu of Visual Studio.
  • At the start of a new test run, you may have to click through the Visual Studio sign-in and initial setup pages.

Debugging

You can debug unit and integration tests by selecting the Debug commands in Test Explorer.

Alternatively, you can debug both generator and editor code by running it in Visual Studio. For that, set the T4Toolbox.vsix project as the startup project in Solution Explorer and specify the following options on the Debug page of the project properties.

  • Start Action / Start external program: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\devenv.exe
  • Start Options / Command line arguments: /rootSuffix Exp

With these settings in place, building the solution will automatically install the extension in the experimental hive of Visual Studio and starting the debugging will automatically launch an experimental instance of Visual Studio and attach your debugger to it.

t4toolbox's People

Contributors

hagronnestad avatar olegsych avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

t4toolbox's Issues

version 14.0.0.76 completely stalled Visual Studio 2015

After I installed version 14.0.0.76, Visual Studio 2015 does not start.
For the first time, there is just a very brief displaying of the splash screen and then nothing. Any subsequent try to start Visual Studio simply does not do anything. No errors are logged in the even log.
I cannot find any way to uninstall T4Toolbox.
Please provide a way to uninstall this component and to get back to the previous state, so I can run Visual Studio again.

Thank you.

Add support for SQL server database projects

I would like it if this extension could add support for SQL server database projects. None of the t4 tools I have used seems to have that feature. I can use t4 templates fine in SQL Server projects. But after installing t4 toolbox hoping to get some syntax highlighting I find the only thing colorized is thing like the includes. Code blocks are completely ignored for coloring and other things. Also I cannot only see the t4 toolbox add new script template item when in a database project. Though it does not complain when manually adding the t4 toolbox include.

Using VS2015 with latest SP

Query which version of T4 Toolbox

I would like to query the version of T4 Toolbox used to generate source code. It's simple enough to embed boilerplate comments like, this code is auto-generated by ..., this sort of thing. But it would be that much more useful to determine the actual version of the underlying T4 Toolbox as one more point of traceability during maintenance cycles. Perhaps this is something which may be exposed via the this that's available, or if there are extensions for this, etc. Thanks...

Scaffold support

Hello. I search away to generate multiple Scaffold MVC 5 Controller t4 template
I can do with this?

Using templates in PCL Project (design time generation)

Hello,

I would like to use t4 and your toolbox in a PCL project (platform-independent api). For building my entities, I want to create a template for outputting multiple files. But when I try to Add -> new item, the t4 toolbox section (and also the t4 tanglible) doesn't appear.

My PCL is .NET 4.5, ASP.Net Core 1.0, Xamarin (Android, iOS (+Classic), Mac).

But I thought the code generation is not in a relation with the assembly, since this code is generated during design-time. So it should not matter, what target the project is.

Thanks!

Failed to load T4ToolBox assembly

However after installing the latest edition 12.10.1.27, I get the error "could not load file or assembly 'T4Toolbox Version=12.0.0.0...."

I am using this on vs2013 with .NET 4.5.2?

It was working earlier and I had to reinstall studio, after which when I installed the new extension, it does not work.

Did I miss something on my configurations?

Configuration:
VS 2013 Premium
.NET 4.5, 4.5.1, 4.5.2 (4 is not installed).
EF 6.1, etc.

Generating files out-of-project

We're using T4Toolbox to generate JavaScript files for a purely front-end project managed in WebStorm. We'd like to keep the projects separate from each other, so I'm wondering if it's possible to use T4Toolbox to output files into another folder, outside the solution structure?

ItemType validation exception

Hi

related to this exception I thinks is for this If I'm not wrong this is the validation code:
private static void ValidateOutputItemType(OutputFile output, Project outputProject)
{
if (!string.IsNullOrEmpty(output.ItemType))
{
ICollection itemTypes = GetAvailableItemTypes(outputProject);
if (!itemTypes.Contains(output.ItemType))
{
throw new TransformationException(string.Format(CultureInfo.CurrentCulture, "ItemType {0} specified for output file {1} is not supported for project {2}", output.ItemType, output.Path, outputProject.FullName));
}
}
}
and the values for ItemType are :none, compile, content, and embebedresource.

former version was posible to set to an arbitrary string like "Page", or "ApplicationDefinition" to generate other things like xaml
is it possible to make a workarround of this validation?
thanks
Javier Hermoso

Generating multiple files along with POCO

Hi, thanks for this tool ๐Ÿ‘

Can you please tell me how to generate additional files for e.g. I want to read the Database, script a POCO user.cs & a DTO userDTO.cs object.

I need help/guidance please to customize some of the output - for e.g. for each POCO class generated from DB, I also want to custom generate additional code/another output class file with the same code for e.g. POCO user.cs so along with user.cs POCO, how can I also get this output to UserDTO.cs

[atValidate(typeof(user))]
public class UsersDto : IChanged
{
    public string uName { get; set; }
    public string uLast { get; set; }
    public string uEmail { get; set; }
}

Wrong completion after <#= ... #

should be #>

(apparently newlines in text between <#= and #> is erased before compilation so any preprocessor directive will be illegal)

image

Make AppVeyor CI run integration tests

The AppVeyor CI build only runs unit tests now because VS 2013 integration tests fail when setting up the experimental profile.

[00:00:00] Build started
[00:00:09] "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe" /RootSuffix Exp /ResetSettings General.vssettings /Embedding /Command File.Exit
[00:04:04] log4net:ERROR XmlHierarchyConfigurator: Could not create Appender [RollingFileAppender] of type [log4net.Appender.RollingFileAppender]. Reported error follows.
[00:04:04] System.IO.FileNotFoundException: Could not load file or assembly 'AWSToolkit.Util' or one of its dependencies. The system cannot find the file specified.
[00:04:04] File name: 'AWSToolkit.Util'
[00:04:04]    at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throw
[00:04:04] OnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type)
[00:04:04]    at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean
[00:04:04]  ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
[00:04:04]    at System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& st
[00:04:04] ackMark)
[00:04:04]    at System.Type.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase)
[00:04:04]    at log4net.Util.SystemInfo.GetTypeFromString(Assembly relativeAssembly, String typeName, Boolean throwOnError, Boolean ignoreCase)
[00:04:04]    at log4net.Util.System
[00:04:04] Info.GetTypeFromString(String typeName, Boolean throwOnError, Boolean ignoreCase)
[00:04:04]    at log4net.Util.TypeConverters.TypeConverter.ConvertFrom(Object source)
[00:04:04]    at log4net.Util.OptionConverter.ConvertStringTo(Type target, String txt)
[00:04:04]    at log4net.Reposi
[00:04:04] tory.Hierarchy.XmlHierarchyConfigurator.ConvertStringTo(Type type, String value)
[00:04:04]    at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.SetParameter(XmlElement element, Object target)
[00:04:04]    at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.Creat
[00:04:04] eObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint)
[00:04:04]    at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.SetParameter(XmlElement element, Object target)
[00:04:04]    at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.Create
[00:04:04] ObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint)
[00:04:04]    at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.SetParameter(XmlElement element, Object target)
[00:04:04]    at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.ParseAp
[00:04:04] pender(XmlElement appenderElement)

Dark Theme

Currently when in the Dark Theme in Visual Studio 2015 the text is all highlighted in a weird background color and the text is white making it almost impossible to read.

Documentation please

Is there any documentation? I want to generate multiple files but i can't find any sample or documentation. Is this still mantained??

Add support fo *.ttinclude

At the moment only *.tt files are support.
Please also add *.ttinclude support for color highlighting.
Thank you!

Need help trying to run a Template from VSIX code without a .tt file in the target project

So: I'm trying to programatically execute a TextTransformation that would generate many new files in the target project, but I need to do so without the target project having any .tt files at all.

I've tried every possible combination of ITextTemplatingEngine, ITextTemplatingEngineHost, TransformationContext, and so on, but I get the "T4 Toolbox transformation context was not properly initialized." error every time.

I can't add the t4toolbox.tt include because I don't actually have any .tt file to begin with, I'm creating a CSharpTemplate 100% programatically by inheriting the class and overriding TransformText().

All this is running in the context of a VSIX extension for Visual Studio 2015.

Is this even possible?

Missing T4 Toolbox in New Project

Hello,

I am using VS2015 Community. After installing T4 Toolbox extension, and restarted VS, I cannot find the T4 Toolbox section in New Project.

Please help.

SyntaxKind is missing

Solution won't build because SyntaxKind is missing. I started through project by project and the first one with a problem is T4Toolbox.TemplateAnalysis . I'm in the process now of putting in SyntaxKind.cs from Microsoft, so if that works I'll be going again--but wondering where I missed it in the docs?

Is there a way to transform using PowerShell msbuild -T4Toolbox.TransformationContextProcessor

Hi Oleg,
I've used your tool set for many years now and think it's great. Big thumbs up to you.

I'm not sure if this was solved or not, but I'm trying to use PowerShell to call MsBuild and transform my tt files that rely on T4Toolbox.

I'm getting the error T4Toolbox.TransformationContextProcessor' could not be found for the directive named 'TransformationContext'

Is there a solution or work around for this?
I'm trying to get it to run on my build server.

Any help is much appreciated, thanks, I'm desperate.

Hugh

system.runtime.remoting.remotingexception

I receive this error when running my t4 against a database, which pulls in stored procedures and gets information on the parameters of that stored procedure. I then use this information to create services.

I know I'm not receiving the error due to an issue on my end as this only happens on long running t4 generation instances. It happens after ~5 minutes. As I said, if I run it on a smaller list of stored procedures, it is running correctly.

Any idea what would cause this, and a potential work-around?

Issue with encoding

In my project T4Toolbox.ScriptFileGenerator is used to generate js resources from the *.resx files.

The encoding is specified using the output directive:
<#@ output extension=".js" encoding="utf-16" #>

There is the copyright symbol 'ยฉ' in the template which fails to encode if the whole solution being built, please see the screenshot:

Also there is a warning while opening this file with the KDiff.

But transformation is fine if the single web project is being built.

Are there any differences in how transformations are performed while building a solution and building a single project?

Release a version compatible with Visual Studio 2017

Working with VS 2017 RC and I can't get T4 Toolbox working.

I tried renaming the vsix to .zip, unzipping, editing the manifest files, then putting it back together but I get errors like the following:

Compiling transformation: The type 'TextTransformation' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.VisualStudio.TextTemplating.14.0, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

Adding a ref to Microsoft.VisualStudio.TextTemplating.15.0 doesn't seem to help.

Edit : Adding nuget package Microsoft.VisualStudio.TextTemplating.14.0 doesn't seem to help.

Could not load file or assembly 'T4Toolbox, Version=12.0.0.0, Culture=neutral, PublicKeyToken=null'

Hi,
After upgrading to latest version of T4Toolbox i am getting following exception:

Error   1   Errors were generated when initializing the transformation object. The transformation will not be run.  The following Exception was thrown:
System.IO.FileNotFoundException: Could not load file or assembly 'T4Toolbox, Version=12.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
File name: 'T4Toolbox, Version=12.0.0.0, Culture=neutral, PublicKeyToken=null'

Server stack trace: 
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection)
   at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
   at System.Reflection.Assembly.Load(String assemblyString)
   at System.UnitySerializationHolder.GetRealObject(StreamingContext context)
   at System.Runtime.Serialization.ObjectManager.ResolveObjectReference(ObjectHolder holder)
   at System.Runtime.Serialization.ObjectManager.DoFixups()
   at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
   at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
   at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.DeserializeObject(MemoryStream stm)
   at System.Runtime.Remoting.Messaging.SmuggledMethodCallMessage.FixupForNewAppDomain()
   at System.Runtime.Remoting.Channels.CrossAppDomainSink.DoDispatch(Byte[] reqStmBuff, SmuggledMethodCallMessage smuggledMcm, SmuggledMethodReturnMessage& smuggledMrm)
   at System.Runtime.Remoting.Channels.CrossAppDomainSink.DoTransitionDispatchCallback(Object[] args)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at System.IServiceProvider.GetService(Type serviceType)
   at T4Toolbox.TransformationContext.GetService(Type serviceType)
   at T4Toolbox.TransformationContext..ctor(TextTransformation transformation, StringBuilder generationEnvironment)
   at T4Toolbox.TransformationContext.Initialize(TextTransformation transformation, StringBuilder generationEnvironment)
   at Microsoft.VisualStudio.TextTemplatingBFAB6986108E94B1AC5A0E0C7B4E30903A3BB628F255F90A41F87609AC7BCC13849429B9F13396DC9DB3DC3A521BD2FFADF91307D99A8DB796F7F1B029FDB32F.GeneratedTextTransformation.Initialize() in c:\'mypath'\Model.tt:line 16
   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid1[T0](CallSite site, T0 arg0)
   at Microsoft.VisualStudio.TextTemplating.TransformationRunner.PerformTransformation()
=== Pre-bind state information ===
LOG: DisplayName = T4Toolbox, Version=12.0.0.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///C:/Program Files (x86)/Microsoft Visual Studio 12.0/Common7/IDE/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
===

I appreciate any help to solve this issue.
Regards,
Assam Zafar

Create files in multi projects

Hello :)

I want to create multiple files through multi projects as faster as it is possible. My code (in Generator.tt) is:

`foreach (var xmlFile in xmlFiles)
{
var xml = XDocument.Load(xmlFile);

            XmlSerializer serializer = new XmlSerializer(typeof(Entity));
            Entity result = null;
            using (TextReader reader = new StringReader(xml.ToString()))
            {
                result = (Entity)serializer.Deserialize(reader);
            }

            this.entityTemplate.entity = result;
            this.entityTemplate.Output.Project = @"C:\@Work\MdaPoc\MdaPoc\MdaPoc.Entities\MdaPoc.Entities.csproj";
            this.entityTemplate.RenderToFile(String.Format(@"gen\{0}.cs", result.Name));

            this.modelTemplate.entity = result;
            this.modelTemplate.Output.Project = @"C:\@Work\MdaPoc\MdaPoc\MdaPoc.Models\MdaPoc.Models.csproj";
            this.modelTemplate.RenderToFile(String.Format(@"gen\{0}ViewModel.cs", result.Name));

            this.modelMapperTemplate.entity = result;
            this.modelMapperTemplate.Output.Project = @"C:\@Work\MdaPoc\MdaPoc\MdaPoc.MVC\MdaPoc.MVC.csproj";
            this.modelMapperTemplate.RenderToFile(String.Format(@"Models\gen\{0}Mapper.cs", result.Name));

            this.dataBaseTableTemplate.entity = result;
            this.dataBaseTableTemplate.Output.Project = @"C:\@Work\MdaPoc\MdaPoc\MdaPoc.Database\MdaPoc.Database.sqlproj";
            this.dataBaseTableTemplate.RenderToFile(String.Format(@"Tables\gen\{0}.Table.sql", result.Name));

            this.dataBaseProcedureTemplate.entity = result;
            this.dataBaseProcedureTemplate.Output.Project = @"C:\@Work\MdaPoc\MdaPoc\MdaPoc.Database\MdaPoc.Database.sqlproj";
            this.dataBaseProcedureTemplate.RenderToFile(String.Format(@"Procedures\gen\{0}.Procedure.sql", result.Name));
        }`

Are there any better way to create those all templates (entityTemplate, modelTemplate, modelMapperTemplate, dataBaseTableTemplate, dataBaseProcedureTemplate)? Create them asynchronously, for exemple?

T4 gallery

In this tutorial @olegsych mention T4 Gallery.
What is it?
Does it work?
Can it be connected to Visual Studio as online templates?

NullReferenceException in T4 Toolbox when trying to execute a .tt file that references T4Toolbox.tt from within a VSIX extension

So, My code is this:

var t4 = this.GetService(typeof(STextTemplating)) as ITextTemplating;
var result = t4.ProcessTemplate(string.Empty, File.ReadAllText(@"c:\tt\tt.tt"));

which I'm running inside a VSIX Extension.

the file "C:\tt\tt.tt" contains:

<#@ template language="C#" hostspecific="True" debug="True" #>
<#@ output extension="txt" #>
<#@ include file="c:\tt\T4Toolbox.tt" #>

<#
// <copyright file="Products_Delete.tt" company="Your Company">
//  Copyright @ Your Company. All Rights Reserved.
// </copyright>  
#>

template content

and the exception I get is:

Object reference not set to an instance of an object.
   at T4Toolbox.VisualStudio.TransformationContextProvider.T4Toolbox.ITransformationContextProvider.GetMetadataValue(Object hierarchyObject, String fileName, String metadataName)
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at T4Toolbox.ITransformationContextProvider.GetMetadataValue(Object hierarchy, String fileName, String metadataName)
   at T4Toolbox.TransformationContext.GetMetadataValue(String metadataName)
   at T4Toolbox.TransformationContext.InitializeParameters()
   at T4Toolbox.TransformationContext..ctor(TextTransformation transformation, StringBuilder generationEnvironment)
   at T4Toolbox.TransformationContext.Initialize(TextTransformation transformation, StringBuilder generationEnvironment)
   at Microsoft.VisualStudio.TextTemplatingD47D3639F9410D55044426DB821C9A4965C45D5D24A64C63B29E0C68D864EE9BF8153B860638D61B9DDF13F8746706878A0D925C09D75DA5669F277BFDE0F7CC.GeneratedTextTransformation.Initialize() in c:\Users\fberasategui\AppData\Local\Temp\31k1h5t4.0.cs:line 16
   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid1[T0](CallSite site, T0 arg0)
   at Microsoft.VisualStudio.TextTemplating.TransformationRunner.PerformTransformation()

the C:\TT directory contains the t4toolbox.tt file and all T4 ToolBox assemblies, btw.

... What am I missing here?

How to reference Newtonsoft.Json.dll

Hello I am trying to work with Json.NET via a T4 template and am having some difficulty. AFAIK, I reference the required assemblies that Json.NET wants, but am still receiving the error:

I have included the SolutionDir as an ItemGroup T4ParameterValue, I think that's correctly in the csproj file, but I could be wrong about that.

  <ItemGroup>
    <T4ParameterValues Include="SolutionDir">
      <Value>$(SolutionDir)</Value>
    </T4ParameterValues>
  </ItemGroup>

My template and error are below. The template is really simple now, bit it may become more elaborate. Basically, I want to specify the enumerated bits as Json collections, and have the boilerplate stuff taken care of by the template.

<#@ template debug="true" language="C#" hostspecific="true" #>
<#@ output extension="cs" #>
<#@ assembly name="System" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.Numerics" #>
<#@ assembly name="System.Runtime.Serialization" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ assembly name="$(SolutionDir)tools\Json.NET\Bin\Net45\Newtonsoft.JSON.dll" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="Newtonsoft.Json" #>
namespace Football.Models.Enumerations
{
<# var name = "TestEnum"; #>
    using Domain;

    public partial class <#= name #> : Enumeration<<#= name #>>
    {
        private string TestMe = "<#= "this is a test" #>";

        private <#= name #>()
            : base(0)
        {
        }
    }
}
Error   105 There was a problem loading the assembly 'D:\Source\Kingdom Software\FootballSimulator\Working\src\tools\Json.NET\Bin\Net45\Newtonsoft.JSON.dll' The following Exception was thrown:
System.IO.FileLoadException: Could not load file or assembly 'file:///D:\Source\Kingdom Software\FootballSimulator\Working\src\tools\Json.NET\Bin\Net45\Newtonsoft.JSON.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)
File name: 'file:///D:\Source\Kingdom Software\FootballSimulator\Working\src\tools\Json.NET\Bin\Net45\Newtonsoft.JSON.dll' ---> System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at Microsoft.VisualStudio.TextTemplating.TransformationRunner.AttemptAssemblyLoad(String assemblyName)

        1   1   

RemoteException when the generation lasts for more than 5-6 minutes

Exception details (from the Error List window in VS):

An Exception was thrown while processing the template. The following Exception was thrown:
System.Runtime.Remoting.RemotingException: Object '/39541794_ec36_4967_abd1_4fb2fc285fd5/alfskziedfqdqc9ooo0xv+8d_42.rem' has been disconnected or does not exist at the server.

Server stack trace:
at System.Runtime.Remoting.Channels.ChannelServices.CheckDisconnectedOrCreateWellKnownObject(IMessage msg)
at System.Runtime.Remoting.Channels.ChannelServices.SyncDispatchMessage(IMessage msg)

Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at T4Toolbox.ITransformationContextProvider.UpdateOutputFiles(String inputFile, OutputFile[] outputFiles)
at T4Toolbox.TransformationContext.Dispose(Boolean disposing)
at T4Toolbox.TransformationContext.Cleanup()
at Microsoft.VisualStudio.TextTemplatingFDF23EE9972E2D1BF77B51ED7E024487964D18418A1B3932BC3A0D48B06CD466A699D456E3BFB9E773BBAC51C6A3FFEFB80D68D0CABFF088D9E446DB439D72E8.GeneratedTextTransformation.Dispose(Boolean disposing) in (omitted file name)
at Microsoft.VisualStudio.TextTemplating.TextTransformation.Dispose()
at Microsoft.VisualStudio.TextTemplating.TransformationRunner.PerformTransformation()
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)

Exception rethrown at [1]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.VisualStudio.TextTemplating.IDebugTransformationRun.PerformTransformation()
at Microsoft.VisualStudio.TextTemplating.Engine.ProcessTemplateImplementation(TemplateProcessingSession session, String content, ITextTemplatingEngineHost host, String className, String classNamespace)

It seems that TransformationContextProvider should alter its lifetime service when it is created in the host's AppDomain, so it will not get disconnected so quickly (or not at all?)

How to work with different Path/File creation

I have read your post of how Files can be outputted in different Folders. - But I can't get it working with my Template.
The first Thing is, that I have to Inherit from Template. - But I use Inheritance within my Code template. - So there would be double inheritance, what isn't supported.

I have a "complex" .tt file (which is working) - But I am not able to transform it.
So, I hope someone can help me.
I attach my .tt file. The result of this .tt file should be generated somewhere else.
THX a lot - Have a nice day

<#@ template debug="true" hostspecific="true" language="VB" #>
<#@ include file="T4Toolbox.tt" #>
<#@ output extension=".vb" #>
<#@ assembly name="System.Windows.Forms" #>

<#@ import namespace="System.Resources" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.ComponentModel.Design" #>

<#

Dim myNameSpace As String = "UI"
Dim myClassName As String = "GetCustomerUI"
Dim myTypeOfResourceManager As String = "TypeOfResourceManager.UICustomer"
Dim myResourcePath As String = "Resources\de-AT\Customer"

Dim myFileName As String = "Customer.de-AT.resx"
Dim myFilePath As String = Path.Combine(Path.GetDirectoryName(Me.Host.ResolvePath("")), myResourcePath, myFileName)
Dim myReader= New ResXResourceReader(myFilePath)

myreader.UseResXDataNodes = true

>

namespace <#=myNameSpace #>
Public Class <#=myClassName #>
Inherits Localize.Localization
Public Sub New()
MyBase.New(<#= myTypeOfResourceManager #>)
End Sub
<# For each item As DictionaryEntry In myReader
Dim name = item.Key
Dim node = DirectCast(item.Value, ResXDataNode)
Dim comment = node.Comment
Dim summary As String = String.Empty
If Not [String].IsNullOrEmpty(comment) Then
summary += " - " + comment
End If

>

    ''' <summary>
    ''' <#= summary #>
    ''' </summary>
    ''' <remarks></remarks>

    Public ReadOnly Property Get<#= name #> As String
        Get
            Return MyBase.GetLocalizedString("<#= name #>")
        End Get
    End Property

<#
Next

>

End Class

End NameSpace

Error loading include file 'T4Toolbox.tt'

Invoking Text Transformation in a VS Extension (https://msdn.microsoft.com/en-us/library/gg586947%28v=vs.120%29.aspx?f=255&MSPPError=-2147217396) results in the following error:

There was an error loading the include file 'T4Toolbox.tt'. The transformation will not be run. The following Exception was thrown:
System.UriFormatException: Invalid URI: The format of the URI could not be determined.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString)
at Microsoft.VisualStudio.TextTemplating.VSHost.TextTemplatingService.CheckSecurityZone(String path)
at Microsoft.VisualStudio.TextTemplating.VSHost.TextTemplatingService.LoadIncludeText(String requestFileName, String& content, String& location)
at Microsoft.VisualStudio.TextTemplating.Engine.ProcessIncludeDirective(Directive directive, ITextTemplatingEngineHost host, VisitedFiles includedFiles)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.