예제 #1
0
 internal TransformContext(TextTransformation transformation, ITextTemplatingEngineHost host)
 {
     this.Transformation = transformation;
     this.Host = host;
     this.Dte = (DTE)((IServiceProvider)host).GetService(typeof(DTE));
     this.TemplageProjectItem = this.Dte.Solution.FindProjectItem(host.TemplateFile);
 }
예제 #2
0
        /// <summary>
        /// Creates new or appends to existing output file.
        /// </summary>
        /// <param name="output">
        /// An <see cref="OutputInfo"/> object that describes content generated by a template.
        /// </param>
        /// <param name="content">
        /// A <see cref="String"/> that contains content generated by a template.
        /// </param>
        /// <param name="host">
        /// An <see cref="ITextTemplatingEngineHost"/> object hosting the <paramref name="transformation"/>.
        /// </param>
        /// <param name="transformation">
        /// <see cref="TextTransformation"/> object generated by T4 based on top-level .tt file.
        /// </param>
        /// <remarks>
        /// Multiple outputs can be combined in a single output file during code 
        /// generation. This allows user to customize a composite code generator 
        /// to generate output with required granularity without having to modify
        /// the generator itself.
        /// </remarks>
        public void Append(OutputInfo output, string content, ITextTemplatingEngineHost host, TextTransformation transformation)
        {
            if (output == null)
            {
                throw new ArgumentNullException("output");
            }

            if (host == null)
            {
                throw new ArgumentNullException("host");
            }

            string previousDirectory = Environment.CurrentDirectory;
            Environment.CurrentDirectory = Path.GetDirectoryName(host.TemplateFile);
            try
            {
                Validate(output);
                if (string.IsNullOrEmpty(output.File))
                {
                    this.AppendToStandardOutput(output, content, host, transformation);
                }
                else
                {
                    this.AppendToOutputFile(output, content, host);
                }
            }
            finally
            {
                Environment.CurrentDirectory = previousDirectory;
            }
        }
예제 #3
0
            public IntegerByteSwapCodeGenerator(TextTemplating.TextTransformation ttFile,
                                                ByteSwapableIntegerDefinition def, string valueName)
            {
                mFile = ttFile;
                mDef  = def;

                mValueName = valueName;
            }
예제 #4
0
 public BittableHandleGenerator(TextTemplating.TextTransformation ttFile,
                                string underlyingTypeName, string structName)
     : this()
 {
     mFile = ttFile;
     mUnderlyingTypeName = underlyingTypeName;
     mStructName         = structName;
 }
예제 #5
0
 public BittableHandleGenerator(TextTemplating.TextTransformation ttFile,
                                NumberCodeDefinition underlyingType, string structName)
     : this(ttFile, underlyingType.Code.ToString(), structName)
 {
     if (underlyingType == null)
     {
         throw new ArgumentNullException(nameof(underlyingType));
     }
 }
예제 #6
0
        public static IDisposable Indent(this TextTransformation textTransformation, String indent)
        {
            textTransformation.PushIndent(indent);

            return(new ActionDisposable(delegate
            {
                textTransformation.PopIndent();
            }));
        }
예제 #7
0
        public static IDisposable Scope(this TextTransformation textTransformation, String indent)
        {
            textTransformation.WriteLine("{");
            textTransformation.PushIndent(indent);

            return(new ActionDisposable(delegate
            {
                textTransformation.PopIndent();
                textTransformation.WriteLine("}");
            }));
        }
예제 #8
0
        public static BittableHandleGenerator ForIntPtr(TextTemplating.TextTransformation ttFile,
                                                        string structName)
        {
            return(new BittableHandleGenerator(ttFile, "IntPtr", structName)
            {
                Kind = BittableHandleKind.IntPtrWrapper,

                SupportsIComparable = false,

                CtorFromValueTypeName = "IntPtr",
                CtorFromValueParamName = "pointer",
            });
        }
        public AngularTestCodeRenderingSession(
            Fifthweek.Api.ClientHttpStubs.ApiGraph api,
            Microsoft.VisualStudio.TextTemplating.TextTransformation output)
        {
            if (api == null)
            {
                throw new ArgumentNullException("api");
            }

            if (output == null)
            {
                throw new ArgumentNullException("output");
            }

            this.api    = api;
            this.output = output;
        }
예제 #10
0
        public StubFile(
            Microsoft.VisualStudio.TextTemplating.TextTransformation output,
            Fifthweek.Api.ClientHttpStubs.Templates.ITemplate template)
        {
            if (output == null)
            {
                throw new ArgumentNullException("output");
            }

            if (template == null)
            {
                throw new ArgumentNullException("template");
            }

            this.output   = output;
            this.template = template;
        }
예제 #11
0
		void Load (CompilerResults results, string fullName)
		{
			var assembly = results.CompiledAssembly;
			Type transformType = assembly.GetType (fullName);
			tt = (TextTransformation) Activator.CreateInstance (transformType);
			
			//set the host property if it exists
			var hostProp = transformType.GetProperty ("Host", typeof (ITextTemplatingEngineHost));
			if (hostProp != null && hostProp.CanWrite)
				hostProp.SetValue (tt, host, null);
			
			var sessionHost = host as ITextTemplatingSessionHost;
			if (sessionHost != null) {
				//FIXME: should we create a session if it's null?
				tt.Session = sessionHost.Session;
			}
		}
예제 #12
0
            readonly string mOffsetName;             // NOTE: offset variable must be mutable!

            internal IntegerByteAccessCodeGenerator(TextTemplating.TextTransformation ttFile,
                                                    NumberCodeDefinition def,
                                                    string byteName, string bufferName, string offsetName = null,
                                                    int bitCount = -1)
            {
                mFile = ttFile;
                //mDef = def;
                mSizeOfInBits = bitCount == -1
                                        ? def.SizeOfInBits
                                        : bitCount;
                mSizeOfInBytes = bitCount == -1
                                        ? def.SizeOfInBytes
                                        : bitCount / kBitsPerByte;
                mByteName = byteName;

                mBufferName = bufferName;
                mOffsetName = offsetName;
            }
예제 #13
0
        internal TransformationContext(TextTransformation transformation, StringBuilder generationEnvironment)
        {
            if (transformation == null)
            {
                throw new ArgumentNullException("transformation");
            }

            if (generationEnvironment == null)
            {
                throw new ArgumentNullException("generationEnvironment");
            }

            PropertyInfo hostProperty = transformation.GetType().GetProperty("Host");
            if (hostProperty == null)
            {
                throw new ArgumentException("TextTransformation does not have Host property");
            }

            this.Host = (ITextTemplatingEngineHost)hostProperty.GetValue(transformation);
            if (this.Host == null)
            {
                throw new ArgumentException("TextTransformation.Host is null.");
            }

            this.Transformation = transformation;

            // Create a special output file for the transformation output.
            this.outputFiles.Add(new OutputFile(generationEnvironment));

            this.provider = (ITransformationContextProvider)this.GetService(typeof(ITransformationContextProvider));
            if (this.provider == null)
            {
                throw new InvalidOperationException("ITransformationContextProvider service is not available.");
            }

            this.InitializeParameters();
        }
예제 #14
0
 public CharToByteLookupTable62CodeGenerator(TextTemplating.TextTransformation ttFile)
     : base(ttFile)
 {
 }
        public static void OnTransformationEnded(TextTransformation transformation)
        {
            try
            {
                if (transformation == null)
                {
                    throw new ArgumentNullException("transformation");
                }

                if (TransformationContext.transformation != null && !TransformationContext.Errors.HasErrors)
                {
                    //Update the files in the default AppDomain to avoid remoting errors on Database projects
                    //BindingFlags invokeInternalStaticMethod = BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic;
                    //AppDomain defaultDomain = (AppDomain)typeof(AppDomain).InvokeMember("GetDefaultDomain", invokeInternalStaticMethod, null, null, null, CultureInfo.InvariantCulture);

                    //var bd1 = defaultDomain.BaseDirectory;

                    //var setup = new AppDomainSetup();
                    //setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
                    //AppDomain serverAppDomain = AppDomain.CreateDomain("ServerAppDomain", null, setup);

                    //var udf = TransformationContext.outputManager;
                    //defaultDomain.DoCallBack(udf.UpdateFiles);

                    OutputProcessor.Host = Host;
                    outputManager.UpdateFiles();
                }

                TransformationContext.transformation = null;
                TransformationContext.outputManager = null;
                TransformationContext.project = null;
                TransformationContext.projectItem = null;
                TransformationContext.dte = null;

                if (TransformationContext.TransformationEnded != null)
                {
                    TransformationContext.TransformationEnded(null, EventArgs.Empty);
                }
            }
            catch (TransformationException e)
            {
                // Display expected errors in the Error List window without the call stack
                CompilerErrorCollection errors = new CompilerErrorCollection();
                CompilerError error = new CompilerError();
                error.ErrorText = e.Message;
                error.FileName = Host.TemplateFile;
                errors.Add(error);
                TransformationContext.Host.LogErrors(errors);
            }
            finally
            {
                DestroyTraceListener();
            }
        }
        /// <summary>
        /// This method is a part of T4 Toolbox infrastructure. Don't call it in your code.
        /// </summary>
        /// <param name="transformation">
        /// Instance of the <see cref="TextTransformation"/> class generated by T4 engine.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Method throws <see cref="ArgumentNullException"/> when the specified 
        /// <paramref name="transformation"/> is null.
        /// </exception>
        /// <remarks>
        /// During template transformation, this method is called by code in T4Toolbox.tt.
        /// </remarks>
        public static void OnTransformationStarted(TextTransformation transformation)
        {
            if (transformation == null)
            {
                throw new ArgumentNullException("transformation");
            }

            TransformationContext.transformation = transformation;
            TransformationContext.outputManager = new OutputManager();

            CreateTraceListener();
        }
예제 #17
0
 protected BitUtilCodeGenerator(TextTemplating.TextTransformation ttFile, NumberCodeDefinition def)
 {
     File = ttFile;
     Def  = def;
 }
예제 #18
0
        public void RunTransformation(TemplateProcessingSession session, string source, ITextTemplatingEngineHost host, out string result)
        {
            ToStringHelper.FormatProvider = session.FormatProvider;
            CodeDomProvider codeDomProvider = session.CodeDomProvider;
            string          errorOutput     = Resources.ErrorOutput;
            bool            validBaseClass  = string.IsNullOrEmpty(session.BaseClassName);
            Assembly        assembly        = null;

            try
            {
                if (this.ValidateBaseClass(session.BaseClassName, session.ImportDirectives, validBaseClass))
                {
                    session.AssemblyDirectives.Add(base.GetType().Assembly.Location);
                    session.AssemblyDirectives.Add(typeof(ITextTemplatingEngineHost).Assembly.Location);
                    assembly = this.LocateAssembly(session.CacheAssemblies, session.ClassFullName, source, session.TemplateFile, session.Debug, codeDomProvider, session.AssemblyDirectives, session.CompilerOptions);
                }
                if (assembly != null)
                {
                    using (TextTransformation transformation = this.CreateTextTransformation(session.ClassFullName, host, assembly, session.UserTransformationSession))
                    {
                        if (transformation != null)
                        {
                            try
                            {
                                transformation.Initialize();
                            }
                            catch (Exception exception)
                            {
                                if (Engine.IsCriticalException(exception))
                                {
                                    throw;
                                }
                                this.LogError(Resources.ErrorInitializingTransformationObject + string.Format(CultureInfo.CurrentCulture, Resources.Exception, new object[] { exception.ToString() }), false);
                            }
                            if (!transformation.Errors.HasErrors && !this.Errors.HasErrors)
                            {
                                try
                                {
                                    errorOutput = transformation.TransformText();
                                }
                                catch (Exception exception2)
                                {
                                    if (Engine.IsCriticalException(exception2))
                                    {
                                        throw;
                                    }
                                    if (exception2.Data["TextTemplatingProgress"] != null)
                                    {
                                        errorOutput = exception2.Data["TextTemplatingProgress"].ToString();
                                    }
                                    ArgumentNullException exception3 = exception2 as ArgumentNullException;
                                    if ((exception3 != null) && (StringComparer.OrdinalIgnoreCase.Compare(exception3.ParamName, "objectToConvert") == 0))
                                    {
                                        this.LogError(Resources.ExpressionBlockNull + Environment.NewLine + exception3.StackTrace, false);
                                    }
                                    else
                                    {
                                        this.LogError(Resources.TransformationErrorPrepend + exception2.ToString(), false);
                                    }
                                }
                            }
                            foreach (CompilerError error in transformation.Errors)
                            {
                                error.ErrorText = Resources.TransformationErrorPrepend + error.ErrorText;
                            }
                            this.Errors.AddRange(transformation.Errors);
                        }
                    }
                }
            }
            catch (Exception exception4)
            {
                if (Engine.IsCriticalException(exception4))
                {
                    throw;
                }
                this.LogError(Resources.ExceptionWhileRunningCode + string.Format(CultureInfo.CurrentCulture, Resources.Exception, new object[] { exception4.ToString() }), false);
            }
            result = errorOutput;
        }
예제 #19
0
 public static void Initialize(TextTransformation transformation, StringBuilder generationEnvironment)
 {
     CallContext.HostContext = new TransformationContext(transformation, generationEnvironment);
 }
예제 #20
0
 protected BitFondleCodeGenerator(TextTemplating.TextTransformation ttFile, NumberCodeDefinition def)
     : base(ttFile, def)
 {
 }
예제 #21
0
 public static void WriteLine(this TextTransformation textTransformation)
 {
     textTransformation.WriteLine(String.Empty);
 }
예제 #22
0
        /// <summary>
        /// Appends generated <paramref name="content"/> to standard output of the <paramref name="transformation"/>.
        /// </summary>
        /// <param name="output">
        /// An <see cref="OutputInfo"/> object that describes content generated by a template.
        /// </param>
        /// <param name="content">
        /// A <see cref="String"/> that contains content generated by a template.
        /// </param>
        /// <param name="host">
        /// An <see cref="ITextTemplatingEngineHost"/> object hosting the <paramref name="transformation"/>.
        /// </param>
        /// <param name="transformation">
        /// <see cref="TextTransformation"/> object generated by T4 based on top-level .tt file.
        /// </param>
        private void AppendToStandardOutput(OutputInfo output, string content, ITextTemplatingEngineHost host, TextTransformation transformation)
        {
            // If some content was already written to the standard output
            if (this.standardOutput != null)
            {
                Validate(output, this.standardOutput);
            }

            transformation.Write(content);
            host.SetOutputEncoding(output.Encoding, false);

            if (this.standardOutput == null)
            {
                this.standardOutput = new OutputInfo();
                this.standardOutput.Project = GetFullProjectPath(output);
                this.standardOutput.Encoding = output.Encoding;
            }

            this.standardOutput.AppendReferences(output.References);
        }
예제 #23
0
 public IntegerByteAccessCodeGenerator NewByteAccessCodeGenerator(TextTemplating.TextTransformation ttFile,
                                                                  string byteName = "b", string bufferName = "buffer", string offsetName = "offset")
 {
     return(new IntegerByteAccessCodeGenerator(ttFile, mCodeDef, byteName, bufferName, offsetName, mSizeOfInBits));
 }
예제 #24
0
 public IntegerByteSwapCodeGenerator NewByteSwapCodeGenerator(TextTemplating.TextTransformation ttFile,
                                                              string valueName = "value")
 {
     return(new IntegerByteSwapCodeGenerator(ttFile, this, valueName));
 }
예제 #25
0
        public static void GenerateObjectPropertyStreamMethod(TextTemplating.TextTransformation ttFile,
                                                              TagElementStreamSubjectType subject, PrimitiveCodeDefinition codeDef, bool hasTNameParam = true)
        {
            if (ttFile == null)
            {
                throw new ArgumentNullException(nameof(ttFile));
            }
            if (codeDef == null)
            {
                throw new ArgumentNullException(nameof(codeDef));
            }

            ttFile.PushIndent("\t");
            ttFile.PushIndent("\t");

            bool is_opt =
                subject == TagElementStreamSubjectType.ElementOpt ||
                subject == TagElementStreamSubjectType.AttributeOpt
            ;

            string method_name = subject.ToString();

            ttFile.WriteLine(
                "public {5} Stream{0}<T>({2} T theObj, Exprs.Expression<Func<T, {1} >> propExpr {3} {4})",
                method_name,
                codeDef.Keyword,
                hasTNameParam.UseStringOrEmpty("TName name,"),
                is_opt.UseStringOrEmpty(", Predicate<{0}> predicate = null", codeDef.Keyword),
                codeDef.IsInteger.UseStringOrEmpty(", NumeralBase numBase=kDefaultRadix"),
                !is_opt ? "void" : "bool"
                );

            ttFile.WriteLine("{");
            ttFile.PushIndent("\t");

            if (hasTNameParam)
            {
                ttFile.WriteLine("Contract.Requires(ValidateNameArg(name));");
                ttFile.WriteLine("");
            }

            if (is_opt)
            {
                ttFile.WriteLine("if (predicate == null)");
                using (var cb1 = ttFile.EnterCodeBlock())
                    ttFile.WriteLine("predicate = x => true;");

                ttFile.NewLine();
                ttFile.WriteLine("bool executed = false;");
            }

            ttFile.WriteLine("var property = Reflection.Util.PropertyFromExpr(propExpr);");
            ttFile.WriteLine("if (IsReading)");
            using (var cb1 = ttFile.EnterCodeBlock(TextTransformationCodeBlockType.Brackets))
            {
                ttFile.WriteLine("var value = default( {0} );", codeDef.Keyword);
                ttFile.WriteLine("{1}Read{0}({2} ref value {3});",
                                 method_name,
                                 is_opt.UseStringOrEmpty("executed = "),
                                 hasTNameParam.UseStringOrEmpty("name,"),
                                 codeDef.IsInteger.UseStringOrEmpty(", numBase")
                                 );
                if (is_opt)
                {
                    ttFile.WriteLine("if (executed)");
                }
                using (var cb2 = ttFile.EnterCodeBlock(TextTransformationCodeBlockType.Brackets))
                    ttFile.WriteLine("property.SetValue(theObj, value, null);");
            }

            ttFile.WriteLine("else if (IsWriting)");
            using (var cb1 = ttFile.EnterCodeBlock())
            {
                ttFile.WriteLine("{2}Write{0}{3}({4} ({1})property.GetValue(theObj, null) {5}{6});",
                                 method_name,                                           // 0
                                 codeDef.Keyword,                                       // 1
                                 is_opt.UseStringOrEmpty("executed = "),                // 2
                                 is_opt.UseStringOrEmpty("OnTrue"),                     // 3
                                 hasTNameParam.UseStringOrEmpty("name,"),               // 4
                                 is_opt.UseStringOrEmpty(", predicate"),                // 5
                                 codeDef.IsInteger.UseStringOrEmpty(", numBase")        // 6
                                 );
            };

            if (is_opt)
            {
                ttFile.NewLine();
                ttFile.WriteLine("return executed;");
            }

            ttFile.PopIndent();
            ttFile.WriteLine("}");

            ttFile.PopIndent();
            ttFile.PopIndent();
        }
예제 #26
0
 public FastBitCountCodeGenerator(TextTemplating.TextTransformation ttFile, NumberCodeDefinition def)
     : base(ttFile, def)
 {
 }
예제 #27
0
 protected CharLookupTableCodeGeneratorBase(TextTemplating.TextTransformation ttFile)
     : base(ttFile)
 {
 }
예제 #28
0
 public CharIsDigitLookupTable16CodeGenerator(TextTemplating.TextTransformation ttFile)
     : base(ttFile)
 {
 }
 public SqlFormatHelper(TextTransformation textTransformation)
     : base(textTransformation)
 {
 }
예제 #30
0
 protected CharLookupCodeGeneratorBase(TextTemplating.TextTransformation ttFile)
 {
     File = ttFile;
 }
예제 #31
0
 public TransformContextScope(TextTransformation transformation, ITextTemplatingEngineHost host)
 {
     TransformContext.Current = new TransformContext(transformation, host);
 }
 protected FormatHelper(TextTransformation textTransformation)
 {
     textTransformation.ThrowIfNull(() => new ArgumentNullException("textTransformation"));
     _tt = textTransformation;
 }
예제 #33
0
 public BitReverseCodeGenerator(TextTemplating.TextTransformation ttFile, NumberCodeDefinition def)
     : base(ttFile, def)
 {
 }