using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using Microsoft.CSharp;

namespace Howest.CodeDomHelloWorld
{
	class Program
	{
		static void Main(string[] args)
		{
			CodeEntryPointMethod main = new CodeEntryPointMethod();
			CodeSnippetStatement statement = new CodeSnippetStatement();
			statement.Value = "Console.WriteLine(\"Hello World!\");Console.ReadLine();";
			main.Statements.Add(statement);
			
			CodeTypeDeclaration type = new CodeTypeDeclaration("Program");
			type.Members.Add(main);

			CodeDomProvider provider = new CSharpCodeProvider();
			
			// Uncomment for generating code file
			//StreamWriter wr = new StreamWriter("Program.cs");
			//provider.GenerateCodeFromType(type, wr, new CodeGeneratorOptions());
			//wr.Close();

			// Uncomment for generating assembly
			CodeNamespaceImport import = new CodeNamespaceImport("System");
			CodeNamespace ns = new CodeNamespace("Hello.World");
			ns.Imports.Add(import);
			ns.Types.Add(type);
			CodeCompileUnit unit = new CodeCompileUnit();
			unit.ReferencedAssemblies.Add("System.dll");
			unit.Namespaces.Add(ns);
			CompilerParameters pars = new CompilerParameters(
				new string[] { "System.dll" },
				"Hello.World.exe",
				true);
			pars.GenerateExecutable = true;
			CompilerResults results = provider.CompileAssemblyFromDom(pars, unit);
			foreach (CompilerError err in results.Errors)
			{
				Console.WriteLine("Error {0} on line {1}: {2}", err.ErrorNumber, err.Line, err.ErrorText);
			}
			Console.ReadLine();
		}
	}
}
