public static object Get(string value) { string codeSnippet = @"using System; namespace hz { public class _Eval { public object GetValue() { return " + value + @"; } } }"; CodeSnippetCompileUnit unit = new CodeSnippetCompileUnit(codeSnippet); CompilerParameters para = new CompilerParameters(); para.ReferencedAssemblies.Add("System.dll"); para.GenerateInMemory = true; para.GenerateExecutable = false; //para.OutputAssembly = "Eval.dll"; Assembly asm = new CSharpCodeProvider().CompileAssemblyFromDom(para, unit).CompiledAssembly; Type type = asm.GetType("hz._Eval"); MethodInfo mi = type.GetMethod("GetValue", BindingFlags.Public | BindingFlags.Instance); object obj = Activator.CreateInstance(type); return(mi.Invoke(obj, null)); }
public void Generate(EntityType entity, string projectPath) { string templateText = ModelGeneratorResource.ModelTemplate; var template = Template.Parse(templateText); var result = template.Render(new { EntityName = entity.Name, entity.Properties, NavProperties = entity.NavigationProperties, IsUserEntity = entity.NavigationProperties.Any(p => p.Name == "ApplicationUser" && p.Multiplicity == "1") }); result = ArrangeUsingRoslyn(result); var csu = new CodeSnippetCompileUnit(result); var fileName = $"{entity.Name}.cs"; var folderName = "Models"; var absolutePath = Path.Combine(projectPath, folderName); GenerateCSharpCode(fileName, absolutePath, csu); var relativePath = Path.Combine(folderName, fileName); proj.AddToItemGroup(relativePath); }
protected override CodeCompileUnit GetCodeCompileUnit(out IDictionary linePragmasTable) { CodeSnippetCompileUnit ccu = parser.GetCodeModel() as CodeSnippetCompileUnit; linePragmasTable = parser.GetLinePragmasTable(); return(ccu); }
void CopyFileWithChecksum(Stream input, string to, string from, ICodePragmaGenerator pragmaGenerator) { if (pragmaGenerator == null) { // This is BAD, BAD, BAD! CodeDOM API is really no good in this // instance. string filedata; using (StreamReader sr = new StreamReader(input, WebEncoding.FileEncoding)) { filedata = sr.ReadToEnd(); } var snippet = new CodeSnippetCompileUnit(filedata); snippet.LinePragma = new CodeLinePragma(from, 1); filedata = null; AddCodeCompileUnit(snippet); snippet = null; return; } MD5 checksum = MD5.Create(); using (FileStream fs = new FileStream(to, FileMode.Create, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) { using (StreamReader sr = new StreamReader(input, WebEncoding.FileEncoding)) { int count = pragmaGenerator.ReserveSpace(from); char[] src; if (count > COPY_BUFFER_SIZE) { src = new char [count]; } else { src = new char [COPY_BUFFER_SIZE]; } sw.Write(src, 0, count); do { count = sr.Read(src, 0, COPY_BUFFER_SIZE); if (count == 0) { UpdateChecksum(src, 0, checksum, true); break; } sw.Write(src, 0, count); UpdateChecksum(src, count, checksum, false); }while (true); src = null; } } } pragmaGenerator.DecorateFile(to, from, checksum, Encoding.UTF8); }
private void ValidateSnippetCompileUnit(CodeSnippetCompileUnit e) { if (e.LinePragma != null) { this.ValidateLinePragmaStart(e.LinePragma); } }
// Generate a compile unit snippet. protected virtual void GenerateSnippetCompileUnit (CodeSnippetCompileUnit e) { LinePragmaStart(e.LinePragma); Output.WriteLine(e.Value); LinePragmaEnd(e.LinePragma); }
public void Make(string resourceFile) { string starterTemplate = GetStarterTemplate(); starterTemplate = starterTemplate.Replace("// This is a template. Do not remove //# strings", string.Empty); starterTemplate = SetStarterVersion(starterTemplate); starterTemplate = SetNETVersion(starterTemplate); starterTemplate = AppendPrivatePath(starterTemplate); starterTemplate = RemoveZipCode(starterTemplate); starterTemplate = SetZipTemplate(starterTemplate, genData); starterTemplate = OptimizeSelf(starterTemplate); if (genData.Console) { starterTemplate = starterTemplate.Replace( "using System.Windows.Forms;", string.Empty); starterTemplate = starterTemplate.Replace( "MessageBox.Show(null, s, \"Error\")", "Console.WriteLine(s)"); } if (genData.BatchMode) { BatchMode(genData.Console, starterTemplate); } else { CodeCompileUnit cu = new CodeSnippetCompileUnit(MixTemplate(starterTemplate, genData.AssemblyInfo)); CompileCU(genData.Console, resourceFile, cu); } }
/// <summary> /// 根据映射的类名获取CDSSSystemData.GlobalData中成员数据 /// 返回值类型不定,由CDSSSystemData.GlobalData中成员数据类型决定 /// </summary> /// <param name="value"></param> /// <returns></returns> public static object GetMapperValue(string strClassName) { CodeSnippetCompileUnit unit = ConstructAndCompileCode(strClassName); ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler(); CompilerParameters para = new CompilerParameters(); para.ReferencedAssemblies.Add(CONST_IMPORT_SYSTEM_DLL); para.ReferencedAssemblies.Add(CONST_IMPORT_CDSS_SYSTEM_DATA_DLL); para.GenerateInMemory = true; para.GenerateExecutable = false; CompilerResults cr = compiler.CompileAssemblyFromDom(para, unit); if (cr.Errors.Count > 0) { string str = "编译文件出错: " + cr.PathToAssembly + ": \r\n"; foreach (CompilerError ce in cr.Errors) { str = ce.ToString(); } return(false); } else { Assembly asm = cr.CompiledAssembly; Type type = asm.GetType( CONST_GENERATECODE_NAMESPACE + "." + CONST_GENERATECODE_CLASSNAME); MethodInfo mi = type.GetMethod( CONST_GENERATECODE_METHODNAME_OBTAIN_SYSTEM_DATA, BindingFlags.Public | BindingFlags.Instance); object obj = asm.CreateInstance( CONST_GENERATECODE_NAMESPACE + "." + CONST_GENERATECODE_CLASSNAME); return(mi.Invoke(obj, null)); } }
protected internal virtual CodeCompileUnit GetCodeCompileUnit(out IDictionary linePragmasTable) { CodeSnippetCompileUnit unit = new CodeSnippetCompileUnit(Util.StringFromVirtualPath(this.VirtualPathObject)); LinePragmaCodeInfo info = new LinePragmaCodeInfo(1, 1, 1, -1, false); linePragmasTable = new Hashtable(); linePragmasTable[1] = info; return(unit); }
public void Constructor0_Deny_Unrestricted() { CodeSnippetCompileUnit cscu = new CodeSnippetCompileUnit(); Assert.IsNull(cscu.LinePragma, "LinePragma"); cscu.LinePragma = new CodeLinePragma(); Assert.AreEqual(String.Empty, cscu.Value, "Value"); cscu.Value = "mono"; }
public void Constructor1_Deny_Unrestricted() { CodeSnippetCompileUnit cscu = new CodeSnippetCompileUnit("mono"); Assert.IsNull(cscu.LinePragma, "LinePragma"); cscu.LinePragma = new CodeLinePragma(String.Empty, Int32.MaxValue); Assert.AreEqual("mono", cscu.Value, "Value"); cscu.Value = String.Empty; }
private void EnsureCodeCompileUnit() { if (this._snippetCompileUnit == null) { string str = Util.StringFromVirtualPath(base.VirtualPathObject); this._snippetCompileUnit = new CodeSnippetCompileUnit(str); this._snippetCompileUnit.LinePragma = BaseCodeDomTreeGenerator.CreateCodeLinePragmaHelper(base.VirtualPath, 1); } }
private void EnsureCodeCompileUnit() { if (_snippetCompileUnit == null) { // Read the contents of the file string sourceString = Util.StringFromVirtualPath(VirtualPathObject); _snippetCompileUnit = new CodeSnippetCompileUnit(sourceString); _snippetCompileUnit.LinePragma = BaseCodeDomTreeGenerator.CreateCodeLinePragmaHelper( VirtualPath, 1); } }
public override void GenerateCode(AssemblyBuilder assemblyBuilder) { try { this.EnsureDirective(); if (String.IsNullOrEmpty(this.serviceTypeName)) { return; } Assembly tempAssembly = null; if (!String.IsNullOrEmpty(this.sourceText)) { // generate a code snippet for any inline source CodeSnippetCompileUnit unit = new CodeSnippetCompileUnit(this.sourceText); unit.LinePragma = new CodeLinePragma(base.VirtualPath, this.lineNumber); // add known assembly references foreach (Assembly assembly in this.ReferencedAssemblies) { assemblyBuilder.AddAssemblyReference(assembly); if (!String.IsNullOrEmpty(assembly.Location) && !unit.ReferencedAssemblies.Contains(assembly.Location)) { unit.ReferencedAssemblies.Add(assembly.Location); } } // compile once so we can reflect and build proxy, etc. assemblyBuilder.AddCodeCompileUnit(this, unit); CompilerResults results = assemblyBuilder.CodeDomProvider.CompileAssemblyFromDom(new CompilerParameters(), unit); if (results.Errors.HasErrors) { CompilerError error = results.Errors[0]; throw new HttpParseException(error.ErrorText, null, error.FileName, "", error.Line); } tempAssembly = results.CompiledAssembly; } Type serviceType = this.GetTypeToCache(this.serviceTypeName, tempAssembly); this.GenerateServiceProxyCode(assemblyBuilder, serviceType); } catch (HttpParseException ex) { Console.Error.WriteLine(ex); throw; } catch (Exception ex) { Console.Error.WriteLine(ex); throw new HttpParseException("GenerateCode: " + ex.Message, ex, base.VirtualPath, this.sourceText, this.lineNumber); } }
internal CodeCompileUnit GetCodeModel() { if ((this.sourceString == null) || (this.sourceString.Length == 0)) { return(null); } CodeSnippetCompileUnit unit = new CodeSnippetCompileUnit(this.sourceString); string fileName = HostingEnvironmentWrapper.MapPath(this.virtualPath); unit.LinePragma = new CodeLinePragma(fileName, this.lineNumber); return(unit); }
public byte[] GenerateFromCode(string code) { CodeSnippetCompileUnit unit = new CodeSnippetCompileUnit { Value = code }; using (StringWriter writer = new StringWriter()) { CodeProvider.GenerateCodeFromCompileUnit(unit, writer, null); return(Encoding.UTF8.GetBytes(writer.ToString())); } }
private CodeCompileUnit CreateCompileUnit(string virtualPath) { var contents = GetContents(virtualPath); var unit = new CodeSnippetCompileUnit(contents); var physicalPath = _virtualPathProvider.MapPath(virtualPath); if (!string.IsNullOrEmpty(physicalPath)) { unit.LinePragma = new CodeLinePragma(physicalPath, 1); } return(unit); }
//added JJ static void SaveIndexer(List <string> indexerList) { string constVar = ""; string caseStr = ""; string temp = ""; int i = 0; foreach (string name in nameList) { temp = name.ToUpper(); // 변수명 constVar += " public const string " + temp + " = \"" + name + "\";\n"; //상수 라인 caseStr += " case " + temp + ": return " + i + ";\n"; // case 문.. i++; } string literalCode; literalCode = "\n" + "// It was auto generated...\n" + "// Do not modify this class!!!!!!!!!!!!!!!!!!!!!!!!!\n" + "public class " + fileName + "\n" + "{\n" + " static " + fileName + " instance;\n" + " public static " + fileName + " Instance {\n" + " get {\n" + " if(instance == null) { instance = new " + fileName + "(); }\n" + " return instance;\n" + " }\n" + " set { instance = value; }\n" + " }\n\n" + constVar + "\n" + " public int this[string propertyName] {\n" + " get {\n" + " switch(propertyName) {\n" + caseStr + " default: throw new System.ArgumentException(propertyName);\n" + " }\n" + " }\n" + " }\n" + "}"; CodeSnippetCompileUnit csu = new CodeSnippetCompileUnit(literalCode); // Write the code to a file. using (var fileStream = new StreamWriter(File.Create(@dirName + "/" + @fileName + ".cs"))) { var provider = new CSharpCodeProvider(); provider.GenerateCodeFromCompileUnit(csu, fileStream, null); } }
public static CodeCompileUnit CreateSnippetCompileUnit() { //<Snippet8> // Creates a compile unit using a literal sring; string literalCode; literalCode = "using System; namespace TestLiteralCode " + "{ public class TestClass { public TestClass() {} } }"; CodeSnippetCompileUnit csu = new CodeSnippetCompileUnit(literalCode); //</Snippet8> return(csu); }
private void Form1_Load(object sender, EventArgs e) { //the code template with placehoder for the code snippet. var sourceTemplate = @"using System; using System.Windows.Forms; namespace Foo { public static class Bar { public static void Execute() { @Placeholder } } }"; var snippet = "int i = 2; int j = 3; int result = i + j; MessageBox.Show(result.ToString());"; var sourceCode = sourceTemplate.Replace("@Placeholder", snippet); var snippetCompileUnit = new CodeSnippetCompileUnit(sourceCode); using (var provider = new CSharpCodeProvider(new Dictionary <String, String> { { "CompilerVersion", "v3.5" } })) { var parameters = new CompilerParameters(); parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; parameters.IncludeDebugInformation = false; var results = provider.CompileAssemblyFromDom(parameters, snippetCompileUnit); //from the compile result and reflection to run the code if (!results.Errors.HasErrors) { var type = results.CompiledAssembly.GetType("Foo.Bar"); var method = type.GetMethod("Execute"); method.Invoke(null, new object[] {}); } else { StringBuilder sb = new StringBuilder(); foreach (CompilerError compilerError in results.Errors) { sb.AppendFormat("Error in line {0}:\n\n{1}", compilerError.Line, compilerError.ErrorText); } MessageBox.Show(sb.ToString(), "Compiler Error"); } } }
protected virtual void GenerateSnippetCompileUnit(CodeSnippetCompileUnit e) { if (e.LinePragma != null) { GenerateLinePragmaStart(e.LinePragma); } output.WriteLine(e.Value); if (e.LinePragma != null) { GenerateLinePragmaEnd(e.LinePragma); } }
// This is used in the CBM scenario only /// <devdoc> /// Returns the CodeCompileUnit and sets the associated dictionary containing the line pragmas. /// </devdoc> protected internal virtual CodeCompileUnit GetCodeCompileUnit(out IDictionary linePragmasTable) { // Default implementation with code at line 1 string sourceString = Util.StringFromVirtualPath(VirtualPathObject); CodeSnippetCompileUnit snippetCompileUnit = new CodeSnippetCompileUnit(sourceString); LinePragmaCodeInfo codeInfo = new LinePragmaCodeInfo(1 /* startLine */, 1 /* startColumn */, 1 /* startGeneratedColumn */, -1 /* codeLength */, false /* isCodeNuggest */); linePragmasTable = new Hashtable(); linePragmasTable[1] = codeInfo; return(snippetCompileUnit); }
public void CodeSnippets() { var snippetStmt = new CodeSnippetStatement("blah"); AssertEqual(snippetStmt, "blah"); var snippetExpr = new CodeSnippetExpression(" blah "); AssertEqual(snippetExpr, " blah "); var snippetCu = new CodeSnippetCompileUnit(); snippetCu.Value = GetEmptyProgramSource(); AssertEqual(snippetCu, GetEmptyProgramSource()); }
public string Compute(string expression) { var source = "class Evaluator { public static string Evaluate() { return (" + expression + ").ToString(); } }"; var compileUnit = new CodeSnippetCompileUnit(source); var provider = new CSharpCodeProvider(); var parameters = new CompilerParameters(); var results = provider.CompileAssemblyFromDom(parameters, compileUnit); var type = results.CompiledAssembly.GetType("Evaluator"); var method = type.GetMethod("Evaluate"); return((string)method.Invoke(null, null)); }
public void Generate(IEnumerable <EntityType> entities, string projectPath) { string templateText = DefaultRegistryResource.DefaultRegistryTemplate; var template = Template.Parse(templateText); var result = template.Render(new { entities }); result = ArrangeUsingRoslyn(result); var csu = new CodeSnippetCompileUnit(result); var fileName = "DefaultRegistry.cs"; var folderName = "DependencyResolution"; var absolutePath = Path.Combine(projectPath, folderName); GenerateCSharpCode(fileName, absolutePath, csu); }
internal CodeCompileUnit GetCodeModel() { // Do we have something to compile? if (_sourceString == null) { return(null); } CodeSnippetCompileUnit snippetCompileUnit = new CodeSnippetCompileUnit(_sourceString); // Put in some context so that the file can be debugged. snippetCompileUnit.LinePragma = BaseCodeDomTreeGenerator.CreateCodeLinePragmaHelper( _virtualPath.VirtualPathString, _lineNumber); return(snippetCompileUnit); }
private static Assembly CompileCode(string code, string outputFilename) { EnsureOutputDirectoryExists(outputFilename); CodeCompileUnit unit = new CodeSnippetCompileUnit(code); unit.ReferencedAssemblies.Add("System"); unit.ReferencedAssemblies.Add("Common"); CompilerResults results = new CSharpCodeProvider().CompileAssemblyFromSource( new CompilerParameters( new string[] { "System.dll", typeof(IModule).Assembly.CodeBase.Replace(@"file:///", "") }, outputFilename), code); ThrowIfCompilerError(results); return(results.CompiledAssembly); }
static void Main(string[] args) { s_mappers = new Dictionary <string, IDynamicTypeNameMapper>(); var provider = new CSharpCodeProvider(); var options = new CompilerParameters(); options.ReferencedAssemblies.Add("ConsoleApplication1.exe"); options.GenerateInMemory = true; var stopwatch = new Stopwatch(); stopwatch.Start(); foreach (string keyword in csharpKeywords) { string className = "DynamicTypeNameMapper_" + keyword; string literal = "using System; using ConsoleApplication1; namespace Test { public class " + className + ": IDynamicTypeNameMapper { public string GetTypeName() { return typeof(" + keyword + ").FullName; } } }"; var snippet = new CodeSnippetCompileUnit(literal); var results = provider.CompileAssemblyFromDom(options, snippet); var typeNameMapper = results.CompiledAssembly.CreateInstance("Test." + className) as IDynamicTypeNameMapper; if (typeNameMapper != null) { s_mappers.Add(keyword, typeNameMapper); Console.WriteLine(typeNameMapper.GetTypeName()); } } stopwatch.Stop(); Console.WriteLine("Inital time: " + stopwatch.Elapsed.ToString()); stopwatch.Reset(); stopwatch.Start(); for (int i = 0; i < 1000; i++) { foreach (string keyword in csharpKeywords) { s_mappers[keyword].GetTypeName(); } } stopwatch.Stop(); Console.WriteLine("Cached time: " + stopwatch.Elapsed.ToString()); Console.ReadLine(); }
public void Constructor1() { string value = "mono"; CodeSnippetCompileUnit cscu = new CodeSnippetCompileUnit(value); Assert.IsNull(cscu.LinePragma, "#1"); Assert.IsNotNull(cscu.Value, "#2"); Assert.AreEqual(value, cscu.Value, "#3"); Assert.AreSame(value, cscu.Value, "#4"); Assert.IsNotNull(cscu.AssemblyCustomAttributes, "#5"); Assert.AreEqual(0, cscu.AssemblyCustomAttributes.Count, "#6"); Assert.IsNotNull(cscu.Namespaces, "#7"); Assert.AreEqual(0, cscu.Namespaces.Count, "#8"); Assert.IsNotNull(cscu.ReferencedAssemblies, "#9"); Assert.AreEqual(0, cscu.ReferencedAssemblies.Count, "#10"); #if NET_2_0 Assert.IsNotNull(cscu.StartDirectives, "#11"); Assert.AreEqual(0, cscu.StartDirectives.Count, "#12"); Assert.IsNotNull(cscu.EndDirectives, "#13"); Assert.AreEqual(0, cscu.EndDirectives.Count, "#14"); #endif Assert.IsNotNull(cscu.UserData, "#15"); Assert.AreEqual(typeof(ListDictionary), cscu.UserData.GetType(), "#16"); Assert.AreEqual(0, cscu.UserData.Count, "#17"); cscu.Value = null; Assert.IsNotNull(cscu.Value, "#18"); Assert.AreEqual(string.Empty, cscu.Value, "#19"); CodeLinePragma clp = new CodeLinePragma("mono", 10); cscu.LinePragma = clp; Assert.IsNotNull(cscu.LinePragma, "#20"); Assert.AreSame(clp, cscu.LinePragma, "#21"); cscu = new CodeSnippetCompileUnit((string)null); Assert.IsNotNull(cscu.Value, "#22"); Assert.AreEqual(string.Empty, cscu.Value, "#23"); }
public static Assembly CompileCode(string code, string output) { CreateOutput(output); CodeCompileUnit unit = new CodeSnippetCompileUnit(code); unit.ReferencedAssemblies.Add("System"); unit.ReferencedAssemblies.Add("Microsoft.Practices.CompositeUI"); CompilerResults results = new CSharpCodeProvider().CompileAssemblyFromSource( new CompilerParameters( new string[] { "System.dll", typeof(IModule).Assembly.CodeBase.Replace(@"file:///", "") }, output), code); ThrowIfCompilerError(results); return(results.CompiledAssembly); }
private void ValidateSnippetCompileUnit(CodeSnippetCompileUnit e) { if (e.LinePragma != null) ValidateLinePragmaStart(e.LinePragma); }
protected virtual void GenerateSnippetCompileUnit(CodeSnippetCompileUnit e) { GenerateDirectives(e.StartDirectives); if (e.LinePragma != null) { GenerateLinePragmaStart(e.LinePragma); } Output.WriteLine(e.Value); if (e.LinePragma != null) { GenerateLinePragmaEnd(e.LinePragma); } if (e.EndDirectives.Count > 0) { GenerateDirectives(e.EndDirectives); } }