-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamicCreator.cs
91 lines (87 loc) · 3.56 KB
/
DynamicCreator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.IO;
using System.Reflection;
using System.Collections;
namespace CodeCreator
{
public class DynamicCreator
{
public static string Create(string srcCodePath, string ClassFullName, string CreateMethod)
{
System.CodeDom.Compiler.CompilerParameters parameters = new System.CodeDom.Compiler.CompilerParameters();
string srcCode = "";
ParseSrc(srcCodePath, ref srcCode, parameters);
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
using (var provider = new CSharpCodeProvider())
{
System.CodeDom.Compiler.ICodeCompiler compiler = provider.CreateCompiler();
CompilerResults results = compiler.CompileAssemblyFromSource(parameters, srcCode);
CompilerErrorCollection errorcollection = results.Errors;
foreach (CompilerError error in errorcollection)
{
if (error.IsWarning == true)
{
WriteLog("编译模板错误 Line: " + error.Line.ToString() + " Warning Number: " + error.ErrorNumber + " Warning Message: " + error.ErrorText);
}
else if (error.IsWarning == false)
{
WriteLog("编译模板错误 Line: " + error.Line.ToString() + " Error Number: " + error.ErrorNumber + " Error Message: " + error.ErrorText);
}
return "编译模板错误,请查看日志!";
}
try
{
Assembly asm = results.CompiledAssembly;
object objSrcCreateClass = asm.CreateInstance(ClassFullName);
Type SrcCreateType = objSrcCreateClass.GetType();
object obj = SrcCreateType.GetMethod(CreateMethod).Invoke(objSrcCreateClass, new object[] { (Hashtable)DataTransfer.data });
return obj.ToString();
}
catch (Exception ex)
{
WriteLog("编译模板后,调用方法错误:");
WriteLog(ex.ToString());
return "编译模板后,调用方法错误,请查看日志!";
}
}
}
public static void ParseSrc(string srcCodePath, ref string srcCode, CompilerParameters parameters)
{
string[] lines = File.ReadAllLines(srcCodePath);
srcCode = "";
bool b = true;
foreach (var item in lines)
{
string tmp = item.Trim(' ');
if (tmp.StartsWith("//#import"))
{
if (b)
{
tmp = tmp.Substring(9).Trim(' ');
parameters.ReferencedAssemblies.Add(tmp);
}
}
else
{
b = false;
srcCode += "\r\n" + tmp;
}
}
}
public static void WriteLog(string mess)
{
if (!Directory.Exists("logs"))
{
Directory.CreateDirectory("logs");
}
string fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".log";
File.AppendAllText("logs/" + fileName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+":"+ mess+"\r\n");
}
}
}