Esempio n. 1
0
        public string PreprocessTemplate(string inputFile, string content, ITextTemplatingCallback callback, string className, string classNamespace, out string[] references)
        {
            var assemblyExpression = new Regex("<\\#\\@\\s*assembly\\s+name\\s*=\\s*\"(?<Assembly>[^\"]*)\"\\s*\\#>", RegexOptions.IgnoreCase);

            references = assemblyExpression.Matches(content).Cast <Match>().Select(match => match.Groups["Assembly"].Value).ToArray();
            return(string.Empty);
        }
        public async Task RemoteProcedureTestWithDummyHost()
        {
            IProcessTransformationRunFactory factory = await RemotingServices.ConnectAsync <IProcessTransformationRunFactory>(new Uri($"ipc://{TransformationRunFactory.TransformationRunFactoryService}/{TransformationRunFactory.TransformationRunFactoryMethod}"));

            IProcessTextTemplatingEngine engine = new TemplatingEngine();

            if (factory?.IsRunFactoryAlive() ?? default)
            {
                IProcessTransformationRunner runner = engine.PrepareTransformationRunner(Samples.template, new DummyHost(), factory);

                runner.Should().NotBeNull();

                ITextTemplatingCallback result = factory.StartTransformation(runner.RunnerId);

                if (result.Errors.HasErrors)
                {
                    foreach (TemplateError error in result.Errors)
                    {
                        Console.Out.WriteLine(error.Message);
                    }
                }

                result.TemplateOutput.Should().Be(Samples.outcome);
            }
        }
Esempio n. 3
0
        public string PreprocessTemplate(string templateInputFile, string templateContent, ITextTemplatingCallback processingCallback, string className, string classNamespace, out string[] references)
        {
            string str2;

            this.hierarchy = null;
            references     = new string[0];
            this.callback  = processingCallback;
            this.inputFile = templateInputFile;
            this.lastInvocationRaisedErrors = false;
            string str = "";

            str = this.engine.PreprocessTemplate(templateContent, this, className, classNamespace, out str2, out references);
            if (StringComparer.OrdinalIgnoreCase.Compare("CSharp", str2) == 0)
            {
                this.SetFileExtension(".cs");
                return(str);
            }
            if (StringComparer.OrdinalIgnoreCase.Compare("VB", str2) == 0)
            {
                this.SetFileExtension(".vb");
                return(str);
            }
            this.SetFileExtension(".cs");
            return(str);
        }
Esempio n. 4
0
        public string PreprocessTemplate(string inputFile, string content, ITextTemplatingCallback callback, string className, string classNamespace, out string[] references)
        {
            string result = null;

            references = Array.Empty <string>();

            if (this is ITextTemplatingComponents SubSonicComponents)
            {
                SubSonicComponents.Callback     = callback;
                SubSonicComponents.TemplateFile = inputFile;

                LastInvocationRaisedErrors = false;

                result = SubSonicComponents.Engine.PreprocessTemplate(content, SubSonicComponents.Host, className, classNamespace, out string language, out references);

                if (language.Equals("C#", StringComparison.OrdinalIgnoreCase))
                {
                    SubSonicComponents.Host.SetFileExtension(".cs");
                }
                else if (language.Equals("VB", StringComparison.OrdinalIgnoreCase))
                {
                    SubSonicComponents.Host.SetFileExtension(".vb");
                }
                else
                {
                    SubSonicComponents.Host.SetFileExtension(DetectExtensionDirective(content));
                }
            }

            return(result);
        }
Esempio n. 5
0
 public string ProcessTemplate(string templateInputFile, string templateContent, ITextTemplatingCallback processingCallback = new ITextTemplatingCallback(), object hierarchy = new object())
 {
     this.hierarchy = hierarchy as IVsHierarchy;
     this.callback  = processingCallback;
     this.inputFile = templateInputFile;
     this.lastInvocationRaisedErrors = false;
     this.SetFileExtension(".cs");
     return(this.engine.ProcessTemplate(templateContent, this));
 }
Esempio n. 6
0
        public string ProcessTemplate(string inputFile, string content, ITextTemplatingCallback callback = null)
        {
            Debug.Assert(!string.IsNullOrEmpty(inputFile), "inputFile is null or empty.");
            Debug.Assert(!string.IsNullOrEmpty(content), "content is null or empty.");

            TemplateFile = inputFile;
            Callback     = callback;

            return(new Engine().ProcessTemplate(content, this));
        }
Esempio n. 7
0
        public string ProcessTemplate(string inputFile, string content, ITextTemplatingCallback callback = null, object hierarchy = null)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            string result = "";

            if (this is ITextTemplatingComponents SubSonicComponents)
            {
                SubSonicComponents.Hierarchy    = hierarchy;
                SubSonicComponents.Callback     = callback;
                SubSonicComponents.TemplateFile = inputFile;

                SubSonicComponents.Host.SetFileExtension(SearchForLanguage(content, "C#") ? ".cs" : ".vb");

                transformationHost.Session = transformationHost.CreateSession();

                result = SubSonicComponents.Engine.ProcessTemplate(content, SubSonicComponents.Host);

                if ((errorSessionDepth == 0) && MustUnloadAfterProcessingTemplate)
                {
                    MustUnloadAfterProcessingTemplate = false;
                    UnloadGenerationAppDomain();
                }

                // SqmFacade is a DTE wrapper that can send additional commands to VS
                if (SearchForLanguage(content, "C#"))
                {
                    SqmFacade.T4PreprocessTemplateCS();
                }
                else if (SearchForLanguage(content, "VB"))
                {
                    SqmFacade.T4PreprocessTemplateVB();
                }
            }

            return(result);
        }
Esempio n. 8
0
 public string ProcessTemplate(string inputFile, string content, ITextTemplatingCallback callback, object hierarchy)
 {
     throw new NotImplementedException();
 }
Esempio n. 9
0
 string ITextTemplating.PreprocessTemplate(string inputFile, string content, ITextTemplatingCallback callback, string className, string classNamespace, out string[] references)
 {
     throw new NotImplementedException();
 }
Esempio n. 10
0
 string ITextTemplating.ProcessTemplate(string inputFile, string content, ITextTemplatingCallback callback, object hierarchy)
 {
     throw new NotImplementedException();
 }
 public string PreprocessTemplate(string inputFile, string content, ITextTemplatingCallback callback, string className, string classNamespace, out string[] references)
 {
     var assemblyExpression = new Regex("<\\#\\@\\s*assembly\\s+name\\s*=\\s*\"(?<Assembly>[^\"]*)\"\\s*\\#>", RegexOptions.IgnoreCase);
     references = assemblyExpression.Matches(content).Cast<Match>().Select(match => match.Groups["Assembly"].Value).ToArray();
     return string.Empty;
 }
Esempio n. 12
0
 string ITextTemplating.PreprocessTemplate(string inputFile, string content, ITextTemplatingCallback callback, string className, string classNamespace, out string[] references)
 {
     throw new NotImplementedException();
 }
        public string ProcessTemplate(string inputFile, string content, ITextTemplatingCallback callback = null)
        {
            Debug.Assert(!string.IsNullOrEmpty(inputFile), "inputFile is null or empty.");
            Debug.Assert(!string.IsNullOrEmpty(content), "content is null or empty.");

            TemplateFile = inputFile;
            Callback = callback;

            return new Engine().ProcessTemplate(content, this);
        }
Esempio n. 14
0
        protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
        {
            string result = "";

            ThreadHelper.ThrowIfNotOnUIThread();

            bool errors = false;

            if ((Package?.IsTemplateInProcess ?? false) && Package?.ProcessResults != null)
            {
                callback = Package.TextTemplatingCallback.DeepCopy();
                result   = Package.ProcessResults;
                Package.ProcessResults = null;
            }
            else
            {
                if (!Package.ShowSecurityWarningDialog())
                {
                    return(Array.Empty <byte>());
                }
                base.SetWaitCursor();

                callback = new TextTemplatingCallback();

                ITextTemplating processor = GetTextTemplating();

                if (processor == null)
                {
                    throw new InvalidOperationException(SubSonicCoreErrors.TextTemplatingUnavailable);
                }

                processor.BeginErrorSession();

                if (GetService(typeof(IVsHierarchy)) is IVsHierarchy hierarchy)
                {
                    result = ProcessTemplate(inputFileName, inputFileContent, processor, hierarchy);

                    errors |= callback.Errors.HasErrors;
                    errors |= processor.EndErrorSession();

                    MarkProjectForTextTemplating(hierarchy);
                }
            }

            if (errors)
            {
                if (ErrorList is IVsErrorList vsErrorList)
                {
                    try
                    {
                        vsErrorList.BringToFront();
                        vsErrorList.ForceShowErrors();
                    }
                    catch
                    { }
                }
            }

            callback.SetOutputEncoding(EncodingHelper.GetEncoding(inputFileName) ?? Encoding.UTF8, false);

            result = result?.TrimStart(Environment.NewLine.ToCharArray()) ?? ERROR_OUTPUT;

            Encoding encoding = callback.GetOutputEncoding();

            byte[] bytes    = encoding.GetBytes(result);
            byte[] preamble = encoding.GetPreamble();
            if ((preamble != null) && (preamble.Length != 0))
            {
                bool success = false;
                if (bytes.Length >= preamble.Length)
                {
                    success = true;
                    for (int i = 0; i < preamble.Length; i++)
                    {
                        if (preamble[i] != bytes[i])
                        {
                            success = false;
                            break;
                        }
                    }
                }
                if (!success)
                {
                    byte[] array = new byte[preamble.Length + bytes.Length];
                    preamble.CopyTo(array, 0);
                    bytes.CopyTo(array, preamble.Length);
                    bytes = array;
                }
            }

            return(bytes);
        }
Esempio n. 15
0
        public async ThreadingTasks.Task <string> ProcessTemplateAsync(string inputFilename, string content, ITextTemplatingCallback callback, object hierarchy, bool debugging = false)
        {
            if (this is ITextTemplatingComponents Component)
            {
                Component.Hierarchy        = hierarchy;
                Component.Callback         = callback;
                Component.TemplateFile     = inputFilename;
                LastInvocationRaisedErrors = false;
                Component.Host.SetFileExtension(SearchForLanguage(content, "C#") ? ".cs" : ".vb");

                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                try
                {
                    try
                    {
                        runFactory = await GetTransformationRunFactoryAsync(subSonicOutput.GetOutputTextWriter(), SubSonicCoreVisualStudioAsyncPackage.Singleton.CancellationTokenSource.Token);
                    }
                    catch (Exception ex)
                    {
                        await LogErrorAsync(string.Format(CultureInfo.CurrentCulture, SubSonicCoreErrors.ExceptionStartingRunFactoryProcess, ex), new Location(inputFilename));

                        runFactory = null;
                    }

                    if (runFactory == null)
                    {
                        await LogErrorAsync(SubSonicCoreErrors.ErrorStartingRunFactoryProcess, new Location(TemplateFile));

                        if (debugging)
                        {
                            ProcessTemplateEventArgs args = new ProcessTemplateEventArgs
                            {
                                TemplateOutput = SubSonicCoreErrors.DebugErrorOutput,
                                Succeeded      = false
                            };
                            this.OnTransformProcessCompleted(args);
                        }
                        return(SubSonicCoreErrors.DebugErrorOutput);
                    }

                    if (!SubSonicCoreVisualStudioAsyncPackage.Singleton.CancellationTokenSource.IsCancellationRequested)
                    {   // we have not been cancelled so let's continue
                        // we need to prepare the transformation and send the important parts over to the T4 Host Process
                        if (Engine.PrepareTransformationRunner(content, Component.Host, runFactory, debugging) is IProcessTransformationRunner runner)
                        {
                            if (!debugging)
                            {   // if we are not debugging we can wait for the process to finish
                                // and we do not need to attach to the host process.
                                try
                                {
                                    if (runFactory.StartTransformation(runner.RunnerId) is TextTemplatingCallback result)
                                    {
                                        if (result.Errors.HasErrors)
                                        {
                                            Callback.Errors.AddRange(result.Errors);

                                            foreach (var templateError in result.Errors)
                                            {
                                                await LogErrorAsync(templateError.Message, templateError.Location, templateError.IsWarning);
                                            }
                                        }

                                        Component.Callback.SetFileExtension(result.Extension);

                                        return(result.TemplateOutput);
                                    }
                                    else if (runFactory.GetErrors(runner.RunnerId) is TemplateErrorCollection errors)
                                    {
                                        Callback.Errors.AddRange(errors);

                                        foreach (var templateError in errors)
                                        {
                                            await LogErrorAsync(templateError.Message, templateError.Location, templateError.IsWarning);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (TemplatingEngine.IsCriticalException(ex))
                                    {
                                        throw;
                                    }
                                    await LogErrorAsync(ex.ToString(), new Location(Host.TemplateFile));
                                }
                                finally
                                {
                                    runFactory.DisposeOfRunner(runner.RunnerId); // clean up the runner
                                }
                            }
                            else
                            {   // when debugging this we will attach to the process
                                // the ui thread will be waiting for a callback from process to complete generation of file.
                                bool success = false;

                                try
                                {
                                    foreach (EnvDTE.Process process in package.DTE.Debugger.LocalProcesses)
                                    {
                                        if (process.ProcessID == (this.transformProcess?.Id ?? default))
                                        {
                                            process.Attach();
                                            success = true;
                                            break;
                                        }
                                    }
                                }
                                catch (Exception attachException)
                                {
                                    await LogErrorAsync(string.Format(CultureInfo.CurrentCulture, SubSonicCoreErrors.ExceptionAttachingToRunFactoryProcess, attachException), new Location(inputFilename));
                                }

                                if (success)
                                {
                                    Dispatcher uiDispatcher = Dispatcher.CurrentDispatcher;
                                    this.debugThread = new Thread(() => StartTransformation(inputFilename, runner, uiDispatcher));
                                    this.debugThread.Start();
                                }
                                else
                                {
                                    await LogErrorAsync(SubSonicCoreErrors.ErrorAttachingToRunFactoryProcess, new Location(inputFilename));

                                    ProcessTemplateEventArgs args = new ProcessTemplateEventArgs
                                    {
                                        TemplateOutput = SubSonicCoreErrors.DebugErrorOutput,
                                        Succeeded      = false
                                    };
                                    this.OnTransformProcessCompleted(args);
                                }
                            }
                        }
                        else
                        {
                            ProcessTemplateEventArgs args = new ProcessTemplateEventArgs();
                            if (debugging)
                            {
                                args.TemplateOutput = SubSonicCoreErrors.DebugErrorOutput;
                                args.Succeeded      = false;
                                this.OnTransformProcessCompleted(args);
                            }

                            await LogErrorsAsync(transformationHost.Errors.ToCompilerErrorCollection());
                        }
                    }
                }
                catch (IOException)
                {
                    if (transformProcess != null)
                    {
                        try
                        {
                            transformProcess.Kill();
                        }
                        catch (Exception)
                        { }
                        finally
                        {
                            transformProcess = null;
                        }
                    }

                    RemotingServices.Disconnect(new Uri($"ipc://{TransformationRunFactory.TransformationRunFactoryService}"));
                }
            }
            return(SubSonicCoreErrors.DebugErrorOutput);
        }