動態編譯
在代碼生成器成功的生成所有的C#源代碼文本 後,我們就可以執行動態編譯了,函數MyFastORMFramework.BuildHelpers就是實現動態編譯 ,其代碼為
private int BuildHelpers( string strFileName )
{
System.Collections.ArrayList RecordTypes = new System.Collections.ArrayList();
foreach( Type RecordType in myRecordHelpers.Keys )
{
if( myRecordHelpers[ RecordType ] == null )
{
RecordTypes.Add( RecordType );
}
}//foreach
if( RecordTypes.Count == 0 )
return 0 ;
// 開始創建代碼
string nsName = "Temp" + System.Guid.NewGuid().ToString("N");
// 生成C#代碼
string strSource = GenerateCode(nsName, strFileName , RecordTypes );
// 編譯臨時生成的C#代碼
System.Collections.Specialized.StringCollection strReferences = new System.Collections.Specialized.StringCollection();
System.CodeDom.Compiler.CompilerParameters options = new System.CodeDom.Compiler.CompilerParameters();
options.GenerateExecutable = false;
options.GenerateInMemory = true ;
// 添加編譯器使用的引用
System.Collections.ArrayList refs = new System.Collections.ArrayList();
foreach( Type t in RecordTypes )
{
refs.Add( t.Assembly.CodeBase );
}
refs.Add( this.GetType().Assembly.CodeBase );
refs.AddRange( new string[]{
"mscorlib.dll",
"System.dll" ,
"System.Data.dll" ,
});
for( int iCount = 0 ; iCount < refs.Count ; iCount ++ )
{
string strRef = ( string ) refs[ iCount ] ;
if( strRef.StartsWith("file:///"))
strRef = strRef.Substring( "file:///".Length );
if( options.ReferencedAssemblIEs.Contains( strRef ) == false )
{
options.ReferencedAssemblIEs.Add( strRef );
}
}
//string strSource = myWriter.ToString();
// 調用C#代碼編譯 器編譯生成程序集
Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
// 若使 用微軟.Net框架.1則調用ICodeCompiler
//System.CodeDom.Compiler.ICodeCompiler compiler = provider.CreateCompiler ();
//System.CodeDom.Compiler.CompilerResults result = compiler.CompileAssemblyFromSource( options , strSource );
// 若使用VS.Net2005或更新版本編譯程序會在這裡形成一個編譯警告信息,
// 則可以將上面兩行代碼去掉而使用下面的代碼
System.CodeDom.Compiler.CompilerResults result = provider.CompileAssemblyFromSource(options, strSource);
if( result.Errors.Count == 0 )
{
System.Reflection.Assembly asm = result.CompiledAssembly ;
myAssemblIEs.Add( asm );
// 創建內置的數據 庫對象操作對象
foreach( Type RecordType in RecordTypes )
{
Type t = asm.GetType( nsName + "." + RecordType.Name + "ORMHelper" );
RecordORMHelper helper = ( RecordORMHelper ) System.Activator.CreateInstance( t );
myRecordHelpers[ RecordType ] = helper ;
System.Console.WriteLine("FastORM為\"" + RecordType.FullName + "\"創建操作幫 助對象");
}
}
else
{
System.Console.WriteLine("ORM框架動態編譯錯 誤" );
foreach( string strLine in result.Output )
{
System.Console.WriteLine( strLine );
}
}
provider.Dispose();
return RecordTypes.Count ;
}