Esempio n. 1
0
        protected void ProcessTemplate(string relativePath, string templateFile, string outFileName, ITemplateGeneratorHost host)
        {
            string result = InternalProcessTemplate(relativePath, templateFile, outFileName, host);

            OutputType    outputType             = OutputType.Normal;
            TagAttributes codeTemplateAttributes = _currentTemplateContext.Directives["CodeTemplate"] as TagAttributes;

            if (codeTemplateAttributes != null)
            {
                string tmp = codeTemplateAttributes["OutputType"] as string;
                if (tmp != null)
                {
                    try
                    {
                        outputType = (OutputType)Enum.Parse(typeof(OutputType), tmp, true);
                    }
                    catch (ArgumentException) { }
                }
            }

            if (outputType == OutputType.Normal)
            {
                host.AddFile(relativePath, outFileName, result);
            }
        }
Esempio n. 2
0
        private void ProcessTemplates(string relativePath, string srcDirectory, ITemplateGeneratorHost host)
        {
            //foreach(string file in Directory.GetFiles(srcDirectory, "*.config.template"))
            foreach (string file in Directory.GetFiles(srcDirectory))
            {
                if (Path.GetExtension(file).ToLower() == ".template")
                {
                    string outFileName = Path.GetFileName(file);
                    outFileName = outFileName.Substring(0, outFileName.Length - ".template".Length);

                    TemplateContext templateContext = new TemplateContext(relativePath, srcDirectory, host);
                    PushContext(templateContext);

                    ProcessTemplate(relativePath, file, outFileName, host);

                    PopContext();
                }
                else if (Path.GetExtension(file).ToLower() == ".subtemplate")
                {
                    //ignore subtemplates
                }
                else
                {
                    host.AddFile(relativePath, file);
                }
            }
            foreach (string dir in Directory.GetDirectories(srcDirectory))
            {
                DirectoryInfo info = new DirectoryInfo(dir);
                if (info.Name.StartsWith("_"))
                {
                    continue;                    //Ignore special folders
                }
                string relativePathTmp = Path.Combine(relativePath, info.Name);
                ProcessTemplates(relativePathTmp, dir, host);
            }
        }
Esempio n. 3
0
        private string Execute(ITemplateGeneratorHost host, string relativePath, string templateFile, string outFileName)
        {
            Type compiledType = null;

            if (!_compiledAssemblies.Contains(templateFile))
            {
                string guid = Guid.NewGuid().ToString("N");
                string generatorClassName = "Template" + guid;
                string import             = @"using System;
using System.Collections;
";

                foreach (DictionaryEntry entry in _currentTemplateContext.Imports)
                {
                    TagAttributes tagAttributes = entry.Value as TagAttributes;
                    import += "using " + tagAttributes["Namespace"].ToString() + ";\r\n";
                }

                string prefix = @"
namespace FluorineFx.CodeGenerator
{
	public class "     + generatorClassName + @" : Template
	{
		public "         + generatorClassName + @"(TemplateEngine templateEngine, ITemplateGeneratorHost host, TemplateContext templateContext) : base(templateEngine, host, templateContext)
		{
		}

		public void RunTemplate()
		{"        ;

                string suffix = @"
		}
	}
}";

                string code = import + prefix + _codeBuilder.ToString() + suffix;

                if (_templateEngineSettings.Trace)
                {
                    host.AddFile(relativePath, outFileName + ".trace.cs", code);
                }

                CodeDomProvider provider = null;
                //Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
                //Microsoft.VisualBasic.VBCodeProvider provider = new Microsoft.VisualBasic.VBCodeProvider();
                provider = new Microsoft.CSharp.CSharpCodeProvider();
#if (NET_1_1)
                ICodeCompiler compiler = provider.CreateCompiler();
#endif
                CompilerParameters options = new CompilerParameters();
                options.GenerateInMemory   = true;
                options.GenerateExecutable = false;
                foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    //options.ReferencedAssemblies.Add(Path.GetFileName(assembly.Location));
                    options.ReferencedAssemblies.Add(assembly.Location);
                }

                Uri    uri     = new Uri(Assembly.GetExecutingAssembly().CodeBase);
                string libPath = Path.GetDirectoryName(uri.LocalPath);
                options.CompilerOptions = "/lib:\"" + libPath + "\"";
                if (AppDomain.CurrentDomain.BaseDirectory != null)
                {
                    options.CompilerOptions += " /lib:\"" + Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + "\"";
                }
                if (AppDomain.CurrentDomain.DynamicDirectory != null)
                {
                    options.CompilerOptions += " /lib:\"" + Path.GetDirectoryName(AppDomain.CurrentDomain.DynamicDirectory) + "\"";
                }

                foreach (DictionaryEntry entry in _currentTemplateContext.Assemblies)
                {
                    TagAttributes tagAttributes = entry.Value as TagAttributes;
                    bool          referenced    = false;
                    foreach (string referencedAssembly in options.ReferencedAssemblies)
                    {
                        string assembly = Path.GetFileName(referencedAssembly);
                        if (assembly.ToLower() == tagAttributes["Name"].ToString().ToLower())
                        {
                            referenced = true;
                            break;
                        }
                    }
                    if (!referenced)
                    {
                        options.ReferencedAssemblies.Add(tagAttributes["Name"].ToString());
                    }
                }

                //log.Debug("Compiling code");
                //log.Debug(code);

                /*
                 * string output = Path.Combine(Path.GetTempPath(), generatorClassName + ".cs");
                 * using (StreamWriter sw = File.CreateText(output))
                 * {
                 *  sw.Write(code);
                 * }
                 */

#if (NET_1_1)
                CompilerResults results = compiler.CompileAssemblyFromSource(options, code);
#else
                CompilerResults results = provider.CompileAssemblyFromSource(options, code);
                //CompilerResults results = provider.CompileAssemblyFromFile(options, output);
#endif
                if (results.Errors.Count != 0)
                {
                    StringBuilder errorBuilder = new StringBuilder();
                    errorBuilder.Append("*** Compilation Errors ***\n");
                    log.Error("*** Compilation Errors ***");
                    foreach (CompilerError error in results.Errors)
                    {
                        errorBuilder.Append(error.Line + ", " + error.Column + ", " + error.ErrorNumber + ": ");
                        errorBuilder.Append(error.ErrorText);
                        errorBuilder.Append("\r\n");
                        log.Error(error.Line + ", " + error.Column + ", " + error.ErrorNumber + ": " + error.ErrorText);
                    }
                    host.AddFile(relativePath, outFileName + ".error.txt", errorBuilder.ToString());
                    return(errorBuilder.ToString());
                }

                compiledType = results.CompiledAssembly.GetType("FluorineFx.CodeGenerator." + generatorClassName);
                _compiledAssemblies[templateFile] = compiledType;
            }
            else
            {
                compiledType = _compiledAssemblies[templateFile] as Type;
            }

            TextWriter   saved  = Console.Out;
            StringWriter writer = new StringWriter();
            Console.SetOut(writer);
            try
            {
                object     generator = Activator.CreateInstance(compiledType, new object[] { this, host, _currentTemplateContext });//Assembly.CreateInstance("FluorineFx.CodeGenerator." + generatorClassName, true, BindingFlags.Public | BindingFlags.Instance, null, new object[] { this, host, _currentTemplateContext }, null, null);
                MethodInfo mi        = generator.GetType().GetMethod("RunTemplate");
                mi.Invoke(generator, new object[] {});
                return(writer.ToString());
            }
            catch (Exception ex)
            {
                log.Error("Error calling code generator", ex);
                Console.SetOut(saved);
                //Console.WriteLine(code.ToString());
                Console.WriteLine();
                Console.WriteLine("Unable to invoke entry point: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException);
                }
                return(ex.ToString());
            }
            finally
            {
                Console.SetOut(saved);
            }
        }
Esempio n. 4
0
		private string Execute(ITemplateGeneratorHost host, string relativePath, string templateFile, string outFileName)
		{
            Type compiledType = null;
            if (!_compiledAssemblies.Contains(templateFile))
            {
                string guid = Guid.NewGuid().ToString("N");
                string generatorClassName = "Template" + guid;
                string import = @"using System;
using System.Collections;
";

                foreach (DictionaryEntry entry in _currentTemplateContext.Imports)
                {
                    TagAttributes tagAttributes = entry.Value as TagAttributes;
                    import += "using " + tagAttributes["Namespace"].ToString() + ";\r\n";
                }

                string prefix = @"
namespace FluorineFx.CodeGenerator
{
	public class " + generatorClassName + @" : Template
	{
		public " + generatorClassName + @"(TemplateEngine templateEngine, ITemplateGeneratorHost host, TemplateContext templateContext) : base(templateEngine, host, templateContext)
		{
		}

		public void RunTemplate()
		{";

                string suffix = @"
		}
	}
}";

                string code = import + prefix + _codeBuilder.ToString() + suffix;

                if (_templateEngineSettings.Trace)
                {
                    host.AddFile(relativePath, outFileName + ".trace.cs", code);
                }

                CodeDomProvider provider = null;
                //Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
                //Microsoft.VisualBasic.VBCodeProvider provider = new Microsoft.VisualBasic.VBCodeProvider();
                provider = new Microsoft.CSharp.CSharpCodeProvider();
#if (NET_1_1)
			ICodeCompiler compiler = provider.CreateCompiler();
#endif
                CompilerParameters options = new CompilerParameters();
                options.GenerateInMemory = true;
                options.GenerateExecutable = false;
                foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    //options.ReferencedAssemblies.Add(Path.GetFileName(assembly.Location));
                    options.ReferencedAssemblies.Add(assembly.Location);
                }

                Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
                string libPath = Path.GetDirectoryName(uri.LocalPath);
                options.CompilerOptions = "/lib:\"" + libPath + "\"";
                if (AppDomain.CurrentDomain.BaseDirectory != null)
                    options.CompilerOptions += " /lib:\"" + Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + "\"";
                if (AppDomain.CurrentDomain.DynamicDirectory != null)
                    options.CompilerOptions += " /lib:\"" + Path.GetDirectoryName(AppDomain.CurrentDomain.DynamicDirectory) + "\"";

                foreach (DictionaryEntry entry in _currentTemplateContext.Assemblies)
                {
                    TagAttributes tagAttributes = entry.Value as TagAttributes;
                    bool referenced = false;
                    foreach (string referencedAssembly in options.ReferencedAssemblies)
                    {
                        string assembly = Path.GetFileName(referencedAssembly);
                        if (assembly.ToLower() == tagAttributes["Name"].ToString().ToLower())
                        {
                            referenced = true;
                            break;
                        }
                    }
                    if (!referenced)
                        options.ReferencedAssemblies.Add(tagAttributes["Name"].ToString());
                }

                //log.Debug("Compiling code");
                //log.Debug(code);

                /*
                string output = Path.Combine(Path.GetTempPath(), generatorClassName + ".cs");
                using (StreamWriter sw = File.CreateText(output))
                {
                    sw.Write(code);
                }
                */

#if (NET_1_1)
			CompilerResults results = compiler.CompileAssemblyFromSource(options, code);
#else
                CompilerResults results = provider.CompileAssemblyFromSource(options, code);
                //CompilerResults results = provider.CompileAssemblyFromFile(options, output);
#endif
                if (results.Errors.Count != 0)
                {
                    StringBuilder errorBuilder = new StringBuilder();
                    errorBuilder.Append("*** Compilation Errors ***\n");
                    log.Error("*** Compilation Errors ***");
                    foreach (CompilerError error in results.Errors)
                    {
                        errorBuilder.Append(error.Line + ", " + error.Column + ", " + error.ErrorNumber + ": ");
                        errorBuilder.Append(error.ErrorText);
                        errorBuilder.Append("\r\n");
                        log.Error(error.Line + ", " + error.Column + ", " + error.ErrorNumber + ": " + error.ErrorText);
                    }
                    host.AddFile(relativePath, outFileName + ".error.txt", errorBuilder.ToString());
                    return errorBuilder.ToString();
                }

                compiledType = results.CompiledAssembly.GetType("FluorineFx.CodeGenerator." + generatorClassName);
                _compiledAssemblies[templateFile] = compiledType;
            }
            else
                compiledType = _compiledAssemblies[templateFile] as Type;

			TextWriter saved = Console.Out;
			StringWriter writer = new StringWriter();
			Console.SetOut(writer);
			try
			{
                object generator = Activator.CreateInstance(compiledType, new object[] { this, host, _currentTemplateContext });//Assembly.CreateInstance("FluorineFx.CodeGenerator." + generatorClassName, true, BindingFlags.Public | BindingFlags.Instance, null, new object[] { this, host, _currentTemplateContext }, null, null);
				MethodInfo mi = generator.GetType().GetMethod("RunTemplate");
				mi.Invoke(generator, new object[]{} );
				return writer.ToString();
			}
			catch (Exception ex)
			{
				log.Error("Error calling code generator", ex);
				Console.SetOut(saved);
				//Console.WriteLine(code.ToString());
				Console.WriteLine();
				Console.WriteLine("Unable to invoke entry point: {0}", ex.Message);
				if (ex.InnerException != null)
					Console.WriteLine(ex.InnerException);
				return ex.ToString();
			}
			finally
			{
				Console.SetOut(saved);
			}
		}
Esempio n. 5
0
		protected void ProcessTemplate(string relativePath, string templateFile, string outFileName, ITemplateGeneratorHost host)
		{
			string result = InternalProcessTemplate(relativePath, templateFile, outFileName, host);

			OutputType outputType = OutputType.Normal;
			TagAttributes codeTemplateAttributes = _currentTemplateContext.Directives["CodeTemplate"] as TagAttributes;
			if( codeTemplateAttributes != null )
			{
				string tmp = codeTemplateAttributes["OutputType"] as string;
				if (tmp != null)
				{
					try 
					{
						outputType = (OutputType)Enum.Parse(typeof(OutputType), tmp, true);
					}
					catch(ArgumentException) { }
				}
			}

			if( outputType == OutputType.Normal )
			{
				host.AddFile(relativePath, outFileName, result);
			}
		}
Esempio n. 6
0
		private void ProcessTemplates(string relativePath, string srcDirectory, ITemplateGeneratorHost host)
		{
			//foreach(string file in Directory.GetFiles(srcDirectory, "*.config.template"))
			foreach(string file in Directory.GetFiles(srcDirectory))
			{
				if( Path.GetExtension(file).ToLower() == ".template" )
				{
					string outFileName = Path.GetFileName(file);
					outFileName = outFileName.Substring(0, outFileName.Length - ".template".Length);

					TemplateContext templateContext = new TemplateContext(relativePath, srcDirectory, host);
					PushContext(templateContext);

					ProcessTemplate(relativePath, file, outFileName, host);

					PopContext();
				}
				else if( Path.GetExtension(file).ToLower() == ".subtemplate" )
				{
					//ignore subtemplates
				}				
				else
				{
					host.AddFile(relativePath, file);
				}
			}
			foreach(string dir in Directory.GetDirectories(srcDirectory))
			{
				DirectoryInfo info = new DirectoryInfo(dir);
				if( info.Name.StartsWith("_") )
					continue;//Ignore special folders
				string relativePathTmp = Path.Combine(relativePath, info.Name);
				ProcessTemplates(relativePathTmp, dir, host);
			}
		}