private void SimulateTransformation()
 {
     this.templatingCallback = new TextTemplatingCallback();
     this.templatingCallback.Initialize();
     string[] references;
     this.templatingService.PreprocessTemplate(this.input.FileNames[1], string.Empty, this.templatingCallback, "GeneratedTextTransformation", string.Empty, out references);
 }
        public FakeTextTemplating()
        {
            this.Errors = new CompilerErrorCollection();

            var callback = new TextTemplatingCallback();
            callback.Initialize();
            this.Callback = callback;
        }
    private string ProcessTemplate(string inputFile, TextTemplatingCallback handler)
    {
        var output = _host.ProcessTemplate(
            inputFile,
            File.ReadAllText(inputFile),
            handler);

        foreach (CompilerError error in handler.Errors)
        {
            var builder = new StringBuilder();

            if (!string.IsNullOrEmpty(error.FileName))
            {
                builder.Append(error.FileName);

                if (error.Line > 0)
                {
                    builder
                    .Append("(")
                    .Append(error.Line);

                    if (error.Column > 0)
                    {
                        builder
                        .Append(",")
                        .Append(error.Line);
                    }
                    builder.Append(")");
                }

                builder.Append(" : ");
            }

            builder
            .Append(error.IsWarning ? "warning" : "error")
            .Append(" ")
            .Append(error.ErrorNumber)
            .Append(": ")
            .AppendLine(error.ErrorText);

            if (error.IsWarning)
            {
                _reporter.WriteWarning(builder.ToString());
            }
            else
            {
                _reporter.WriteError(builder.ToString());
            }
        }

        if (handler.OutputEncoding != Encoding.UTF8)
        {
            _reporter.WriteWarning(DesignStrings.EncodingIgnored(handler.OutputEncoding.WebName));
        }

        return(output);
    }
        public FakeTextTemplating()
        {
            this.Errors = new CompilerErrorCollection();

            var callback = new TextTemplatingCallback();

            callback.Initialize();
            this.Callback = callback;
        }
    public void Assembly_works()
    {
        var host = new TextTemplatingService(
            new ServiceCollection()
            .BuildServiceProvider());
        var callback = new TextTemplatingCallback();

        var result = host.ProcessTemplate(
            @"T:\test.tt",
            @"<#@ assembly name=""Microsoft.EntityFrameworkCore"" #><#= nameof(Microsoft.EntityFrameworkCore.DbContext) #>",
            callback);

        Assert.Empty(callback.Errors);
        Assert.Equal("DbContext", result);
    }
    public void Directive_throws_when_processor_unknown()
    {
        var host = new TextTemplatingService(
            new ServiceCollection()
            .BuildServiceProvider());
        var callback = new TextTemplatingCallback();

        var ex = Assert.Throws <FileNotFoundException>(
            () => host.ProcessTemplate(
                @"T:\test.tt",
                @"<#@ test processor=""TestDirectiveProcessor"" #>",
                callback));

        Assert.Equal(DesignStrings.UnknownDirectiveProcessor("TestDirectiveProcessor"), ex.Message);
    }
    public void Service_works()
    {
        var host = new TextTemplatingService(
            new ServiceCollection()
            .AddSingleton("Hello, Services!")
            .BuildServiceProvider());
        var callback = new TextTemplatingCallback();

        var result = host.ProcessTemplate(
            @"T:\test.tt",
            @"<#@ template hostSpecific=""true"" #><#= ((IServiceProvider)Host).GetService(typeof(string)) #>",
            callback);

        Assert.Empty(callback.Errors);
        Assert.Equal("Hello, Services!", result);
    }
    public void Error_works()
    {
        var host = new TextTemplatingService(
            new ServiceCollection()
            .BuildServiceProvider());
        var callback = new TextTemplatingCallback();

        host.ProcessTemplate(
            @"T:\test.tt",
            @"<# Error(""Hello, Error!""); #>",
            callback);

        var error = Assert.Single(callback.Errors.Cast <CompilerError>());

        Assert.Equal("Hello, Error!", error.ErrorText);
    }
    public void Output_works()
    {
        var host = new TextTemplatingService(
            new ServiceCollection()
            .BuildServiceProvider());
        var callback = new TextTemplatingCallback();

        host.ProcessTemplate(
            @"T:\test.tt",
            @"<#@ output extension="".txt"" encoding=""us-ascii"" #>",
            callback);

        Assert.Empty(callback.Errors);
        Assert.Equal(".txt", callback.Extension);
        Assert.Equal(Encoding.ASCII, callback.OutputEncoding);
    }
    public void ResolvePath_work()
    {
        using var dir = new TempDirectory();

        var host = new TextTemplatingService(
            new ServiceCollection()
            .BuildServiceProvider());
        var callback = new TextTemplatingCallback();

        var result = host.ProcessTemplate(
            Path.Combine(dir, "test.tt"),
            @"<#@ template hostSpecific=""true"" #><#= Host.ResolvePath(""data.json"") #>",
            callback);

        Assert.Empty(callback.Errors);
        Assert.Equal(Path.Combine(dir, "data.json"), result);
    }
    public void Session_works()
    {
        var host = new TextTemplatingService(
            new ServiceCollection()
            .BuildServiceProvider());

        host.Session = new TextTemplatingSession
        {
            ["Value"] = "Hello, Session!"
        };
        var callback = new TextTemplatingCallback();

        var result = host.ProcessTemplate(
            @"T:\test.tt",
            @"<#= Session[""Value""] #>",
            callback);

        Assert.Empty(callback.Errors);
        Assert.Equal("Hello, Session!", result);
    }
    public void Include_works()
    {
        using var dir = new TempDirectory();
        File.WriteAllText(
            Path.Combine(dir, "test.ttinclude"),
            "Hello, Include!");

        var host = new TextTemplatingService(
            new ServiceCollection()
            .BuildServiceProvider());
        var callback = new TextTemplatingCallback();

        var result = host.ProcessTemplate(
            Path.Combine(dir, "test.tt"),
            @"<#@ include file=""test.ttinclude"" #>",
            callback);

        Assert.Empty(callback.Errors);
        Assert.Equal("Hello, Include!", result);
    }
    public void Session_works_with_parameter()
    {
        var host = new TextTemplatingService(
            new ServiceCollection()
            .BuildServiceProvider());

        host.Session = new TextTemplatingSession
        {
            ["Value"] = "Hello, Session!"
        };
        var callback = new TextTemplatingCallback();

        var result = host.ProcessTemplate(
            @"T:\test.tt",
            @"<#@ parameter name=""Value"" type=""System.String"" #><#= Value #>",
            callback);

        Assert.Empty(callback.Errors);
        Assert.Equal("Hello, Session!", result);
    }
Beispiel #14
0
        protected override string ProcessTemplate(string inputFileName, string inputFileContent, ITextTemplating processor, IVsHierarchy hierarchy)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            try
            {
                TextTemplatingCallback callback = new TextTemplatingCallback(this);

                processor.BeginErrorSession();
                string templateCode = processor.PreprocessTemplate(inputFileName, inputFileContent, callback, TEMPLATE_CLASS, TEMPLATE_NAMESPACE,
                                                                   out string[] references);

                if (processor.EndErrorSession() || callback.ErrorLogged)
                {
                    return(ERROR_OUTPUT);
                }

                DetectExtensionDirective(inputFileContent);
                _encoding = callback.OutputEncoding;

                references = ProcessReferences(references, inputFileName).ToArray();

                string output = TextTemplatingHelper.ExecuteTemplate(inputFileName, templateCode, references, out TemplateError[] errors);
                GenerateErrors(errors);

                if (output == null)
                {
                    return(ERROR_OUTPUT);
                }
                else
                {
                    return(output);
                }
            }
            catch (Exception e)
            {
                GenerateError(false, $"Something went wrong processing the template '{inputFileName}': {e}");
                return(ERROR_OUTPUT);
            }
        }
Beispiel #15
0
 public SubSonicCoreVisualStudioAsyncPackage()
 {
     singletonInstance       = this;
     callback                = new TextTemplatingCallback();
     CancellationTokenSource = new CancellationTokenSource();
 }
    public override ScaffoldedModel GenerateModel(IModel model, ModelCodeGenerationOptions options)
    {
        if (options.ContextName == null)
        {
            throw new ArgumentException(
                      CoreStrings.ArgumentPropertyNull(nameof(options.ContextName), nameof(options)), nameof(options));
        }

        if (options.ConnectionString == null)
        {
            throw new ArgumentException(
                      CoreStrings.ArgumentPropertyNull(nameof(options.ConnectionString), nameof(options)), nameof(options));
        }

        var resultingFiles = new ScaffoldedModel();

        var contextTemplate = Path.Combine(options.ProjectDir !, TemplatesDirectory, "DbContext.t4");

        Check.DebugAssert(_host.Session == null, "Session is not null.");
        _host.Session = _host.CreateSession();
        try
        {
            _host.Session.Add("Model", model);
            _host.Session.Add("Options", options);
            _host.Session.Add("NamespaceHint", options.ContextNamespace ?? options.ModelNamespace);
            _host.Session.Add("ProjectDefaultNamespace", options.RootNamespace);

            var handler       = new TextTemplatingCallback();
            var generatedCode = ProcessTemplate(contextTemplate, handler);

            var dbContextFileName = options.ContextName + handler.Extension;
            resultingFiles.ContextFile = new ScaffoldedFile
            {
                Path = options.ContextDir != null
                    ? Path.Combine(options.ContextDir, dbContextFileName)
                    : dbContextFileName,
                Code = generatedCode
            };
        }
        finally
        {
            _host.Session = null;
        }

        var entityTypeTemplate = Path.Combine(options.ProjectDir !, TemplatesDirectory, "EntityType.t4");

        if (File.Exists(entityTypeTemplate))
        {
            foreach (var entityType in model.GetEntityTypes())
            {
                // TODO: Should this be handled inside the template?
                if (CSharpDbContextGenerator.IsManyToManyJoinEntityType(entityType))
                {
                    continue;
                }

                _host.Session = _host.CreateSession();
                try
                {
                    _host.Session.Add("EntityType", entityType);
                    _host.Session.Add("Options", options);
                    _host.Session.Add("NamespaceHint", options.ModelNamespace);
                    _host.Session.Add("ProjectDefaultNamespace", options.RootNamespace);

                    var handler       = new TextTemplatingCallback();
                    var generatedCode = ProcessTemplate(entityTypeTemplate, handler);
                    if (string.IsNullOrWhiteSpace(generatedCode))
                    {
                        continue;
                    }

                    var entityTypeFileName = entityType.Name + handler.Extension;
                    resultingFiles.AdditionalFiles.Add(
                        new ScaffoldedFile {
                        Path = entityTypeFileName, Code = generatedCode
                    });
                }
                finally
                {
                    _host.Session = null;
                }
            }
        }

        return(resultingFiles);
    }
 private void SimulateTransformation()
 {
     this.templatingCallback = new TextTemplatingCallback();
     this.templatingCallback.Initialize();
     string[] references;
     this.templatingService.PreprocessTemplate(this.input.FileNames[1], string.Empty, this.templatingCallback, "GeneratedTextTransformation", string.Empty, out references);            
 }