public void TestGenerateForLoop() { var gen = new CodeUnitGenerator("TestCodeGen"); var classGen = new ClassGenerator("TestClass") .SetIsSealed(true); var method = new MethodGenerator("IterateStuff"); method.AddStatement(new StatementBuilder() .AddVariable(typeof(string[]), "myStuff", true) .AddVariable(typeof(bool), "myBool", true) .AddVariable(typeof(int), "myInt", 1) .AddSnippet("//Snippet") .AddForLoop("i", 10, new StatementBuilder() .AddSnippet("Debug.Log()") .AddAssignement(new VariableTarget("myInt"), new VariableTarget("i")) .InvokeMethod(new VariableTarget("myStuff"), new ClassTarget("UnityEngine"), "GetAllStuff", new ParamBuilder() .AddVariable("myInt")))); classGen.AddMethod(method); gen.AddType(classGen); var ccu = gen.GenerateCompileUnit(); var output = StringCompiler.CompileToString(ccu); Debug.Log(output); Assert.IsTrue(output.Contains("for (i = 0")); Assert.IsTrue(output.Contains("(i < 10")); Assert.IsTrue(output.Contains("myStuff = UnityEngine.GetAllStuff(")); }
public void TestGenerateDelegateEvents() { var gen = new CodeUnitGenerator("TestCodeGen"); var classGen = new ClassGenerator("TestClass"); var delegateGen = new DelegateGenerator("MyEventHandler") .AddParameter("TestClass", "myRef") .AddReturnType(typeof(bool)); var eventGen = new EventGenerator("OnSomeTrigger", delegateGen.delegateType); classGen.AddEvent(eventGen); var fireEventMethod = new MethodGenerator("FireEvent") .AddStatement(new StatementBuilder() //.AddSnippetExpression("Debug.Log();DoMoreStuff();")); .InvokeEvent(eventGen, new ParamBuilder() .AddPrimitiveExpression("new TestClass()"))); classGen.AddMethod(fireEventMethod); gen.AddType(delegateGen); gen.AddType(classGen); var classSubscriber = new ClassGenerator("MySubscribeClass"); var field = new FieldGenerator("TestClass", "eventSource"); classSubscriber.AddField(field); var constructor = new ConstructorGenerator(classSubscriber.classType); classSubscriber.AddMethod(constructor); var eventHandler = new MethodGenerator("OnSomeTrigger", delegateGen) .AddStatement(new StatementBuilder() .AddSnippet("Debug.Log(\"Expression1\");") .AddSnippet("Debug.Log(\"Expression2\");")); var subscribeMethod = new MethodGenerator("AddListener") .AddStatement(new StatementBuilder() .AttachEvent(eventHandler, new FieldTarget(field), eventGen)); classSubscriber.AddMethod( new MethodGenerator("Unsubscribe").AddStatement( new StatementBuilder() .DetachEvent(eventHandler, new FieldTarget(field), eventGen))); classSubscriber.AddMethod(eventHandler); classSubscriber.AddMethod(subscribeMethod); gen.AddType(classSubscriber); var ccu = gen.GenerateCompileUnit(); var output = StringCompiler.CompileToString(ccu); //Debug.Log(output); Assert.IsTrue(output.Contains("OnSomeTrigger")); Assert.IsTrue(output.Contains("FireEvent")); Assert.IsTrue(output.Contains("+=")); Assert.IsTrue(output.Contains("-=")); Assert.IsTrue(output.Contains("delegate")); Assert.IsTrue(output.Contains("event")); }
public void TestGenerateAttributes() { var gen = new CodeUnitGenerator("TestCodeGen"); var attributeGen = new ClassGenerator("MyAttribute") .AddBaseType("Attribute"); var classGen = new ClassGenerator("TestClass"); classGen.SetCustomAttribute("MyAttribute", new ParamBuilder()); var field = new FieldGenerator(typeof(int), "MyField"); field.SetCustomAttribute("MyAttribute", new ParamBuilder()); var property = new AutoPropertyGenerator("TestClass", "MyProp"); property.SetCustomAttribute("MyAttribute", new ParamBuilder()); classGen.AddAutoProperty(property); classGen.AddField(field); gen.AddType(attributeGen); gen.AddType(classGen); var ccu = gen.GenerateCompileUnit(); var output = StringCompiler.CompileToString(ccu); Debug.Log(output); Assert.IsTrue(output.Contains("MyAttribute")); }
public void TestGenerateClassImplementation() { var gen = new CodeUnitGenerator("TestCodeGen"); var classGen = new ClassGenerator("TestClass") .SetIsPartial(true) .SetIsAbstract(true) .AddBaseType("IComponent"); var field = new FieldGenerator(typeof(int), "MyField"); var property = new AutoPropertyGenerator("TestClass", "MyProp"); var constructor = new ConstructorGenerator() .AddBaseCall("BaseArg") .AddParameter(field.FieldType, field.Name) .AddParameter(property.Name, property.PropertyType) .AddStatement(new StatementBuilder() .AddConstructorFieldAssignement(field.Name, field.Name) .AddConstructorPropertyAssignement(property.Name, property.Name)); classGen.AddAutoProperty(property); classGen.AddField(field); classGen.AddMethod(constructor); gen.AddType(classGen); var ccu = gen.GenerateCompileUnit(); var output = StringCompiler.CompileToString(ccu); Debug.Log(output); Assert.IsTrue(output.Contains("base(")); Assert.IsTrue(output.Contains("BaseArg")); }
public void CompilePageTemplateTest() { var errors = new ConcurrentBag <string>(); Page page = this._RepositoryService.FindPageInDb("Example", "Page1"); string jsonModel = null; using (var stringCompiler = new StringCompiler()) { stringCompiler.CompilePageModel(page.Model); if (stringCompiler.IsValid) { jsonModel = stringCompiler.ToString(); } } if (!string.IsNullOrEmpty(jsonModel)) { page.CompileTemplate(ref errors, page.Template, jsonModel); } else { errors.Add("Error compiling Model"); } Assert.IsTrue(!errors.Any()); Assert.IsNotNull(page.CompiledTemplate); }
public void SimpleNonStaticMethod() { // Create assembly var stringCompiler = new StringCompiler(); var assembly = stringCompiler.Compile(SIMPLE_NONSTATIC_METHOD); Assert.IsNotNull(assembly); // Verify that the class exists var exportedType = assembly.ExportedTypes.FirstOrDefault(); Assert.IsNotNull(exportedType); Assert.AreEqual("SimpleNonStatic", exportedType.Name); // Get the contructor info and call it var constructor = exportedType.GetConstructors().FirstOrDefault(); Assert.IsNotNull(constructor); var instance = constructor.Invoke(new object[] { "My String!" }); Assert.IsNotNull(instance); // Verify that the method exists & returns the injected string var constructorStringMethod = exportedType.GetMethods().FirstOrDefault(m => m.Name == "GetAString" && !m.GetParameters().Any()); Assert.IsNotNull(constructorStringMethod); Assert.AreEqual("My String!", constructorStringMethod.Invoke(instance, null)); // Verify that the overloaded method works as well var parameterStringMethod = exportedType.GetMethods().FirstOrDefault(m => m.Name == "GetAString" && m.GetParameters().Count() == 1); Assert.IsNotNull(parameterStringMethod); Assert.AreEqual("Injected String!", parameterStringMethod.Invoke(instance, new object[] { "Injected String!" })); }
public void CompilePageModelTest() { Page page = this._RepositoryService.FindPageInDb("Example", "Page1"); using (var stringCompiler = new StringCompiler()) { stringCompiler.CompilePageModel(page.Model); Assert.IsTrue(stringCompiler.IsValid); } }
public void TestStringCompiler() { var model = "var Model = new { test = \"object\" };"; using (var stringCompiler = new StringCompiler()) { stringCompiler.CompilePageModel(model); Assert.IsTrue(stringCompiler.IsValid); } }
public void SimpleStaticFailureMethod() { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; // Create class assembly var stringCompiler = new StringCompiler(); var bytes = stringCompiler.CompileToByteArray(SIMPLE_STATIC_FAILURE_METHOD); Assert.IsNotNull(bytes); var codeAssembly = Assembly.Load(bytes); _assemblies[codeAssembly.FullName] = codeAssembly; var testAssembly = stringCompiler.Compile(SIMPLE_STATIC_METHOD_TEST, new[] { bytes }); Assert.IsNotNull(testAssembly); // Verify that the class exists var exportedType = testAssembly.ExportedTypes.FirstOrDefault(); Assert.IsNotNull(exportedType); Assert.AreEqual("SimpleStaticTests", exportedType.Name); // Get the contructor info and call it var constructor = exportedType.GetConstructors().FirstOrDefault(); Assert.IsNotNull(constructor); var instance = constructor.Invoke(new object[] { }); Assert.IsNotNull(instance); // Verify that the method exists & returns the appropriate response var getAStringMethod = exportedType.GetMethod("SimpleStatic_GetAString"); Assert.IsNotNull(getAStringMethod); try { getAStringMethod.Invoke(instance, null); } catch (Exception ex) { while (ex.InnerException != null) { ex = ex.InnerException; } Assert.AreEqual("Assert.AreEqual failed. Expected:<A String>. Actual:<A Failure>. ", ex.Message); } }
public void TestGenerateClassWithImports() { var gen = new CodeUnitGenerator("TestCodeGen"); gen.NamespaceImports.Add("System"); ClassGenerator classGen = new ClassGenerator("MyCodeDOMTestClass"); gen.AddType(classGen); var ccu = gen.GenerateCompileUnit(); string output = StringCompiler.CompileToString(ccu); Assert.IsTrue(output.Length > 0); Assert.IsTrue(output.Contains("System")); Assert.IsTrue(output.Contains("TestCodeGen")); Assert.IsTrue(output.Contains("MyCodeDOMTestClass")); }
public void TestGenerateEnum() { var gen = new CodeUnitGenerator("TestCodeGen"); var interfaceGen = new EnumGenerator("MyEnum"); interfaceGen.AddOption("Option1"); interfaceGen.AddOption("Option2"); gen.AddType(interfaceGen); var ccu = gen.GenerateCompileUnit(); var output = StringCompiler.CompileToString(ccu); Debug.Log(output); Assert.IsTrue(output.Contains("enum MyEnum")); Assert.IsTrue(output.Contains("Option1")); Assert.IsTrue(output.Contains("Option2")); }
public void TestGenerateInterface() { var gen = new CodeUnitGenerator("TestCodeGen"); var interfaceGen = new InterfaceGenerator("IMyInterface"); var method = new MethodGenerator("MyInterfaceMethod") .AddParameter(new CodeTypeReference(typeof(bool)), "arg"); interfaceGen.AddMember(method.Method); gen.AddType(interfaceGen); var ccu = gen.GenerateCompileUnit(); var output = StringCompiler.CompileToString(ccu); Debug.Log(output); Assert.IsTrue(output.Contains("interface IMyInterface")); Assert.IsTrue(output.Contains("void MyInterfaceMethod(bool arg);")); }
public void TestGenerateClassWithMethod() { var gen = new CodeUnitGenerator("TestCodeGen"); gen.NamespaceImports.Add("System"); ClassGenerator classGen = new ClassGenerator("MyCodeDOMTestClass") .SetIsSealed(true) .SetIsSealed(false); MethodGenerator method = new MethodGenerator("DoStuff"); classGen.AddMethod(method); gen.AddType(classGen); var ccu = gen.GenerateCompileUnit(); var output = StringCompiler.CompileToString(ccu); Assert.IsFalse(output.Contains("sealed")); Assert.IsTrue(output.Contains("DoStuff")); }
public void SimpleStaticMethod() { // Create assembly var stringCompiler = new StringCompiler(); var assembly = stringCompiler.Compile(SIMPLE_STATIC_METHOD); Assert.IsNotNull(assembly); // Verify that the class exists var exportedType = assembly.ExportedTypes.FirstOrDefault(); Assert.IsNotNull(exportedType); Assert.AreEqual("SimpleStatic", exportedType.Name); // Verify that the method exists & returns the appropriate response var getAStringMethod = exportedType.GetMethod("GetAString"); Assert.IsNotNull(getAStringMethod); Assert.AreEqual("A String", getAStringMethod.Invoke(null, null)); }
public void TestWhileLoop() { var gen = new CodeUnitGenerator("TestCodeGen"); var classGen = new ClassGenerator("TestClass") .SetIsSealed(true); var method = new MethodGenerator("IterateStuff"); method.AddStatement(new StatementBuilder() .AddVariable(typeof(string[]), "myStuff", true) .AddVariable(typeof(bool), "myBool", true) .AddWhile(new CodeSnippetExpression("iterator.MoveNext(myBool)"), new StatementBuilder() .AddSnippet("Debug.Log(myBool)"))); classGen.AddMethod(method); gen.AddType(classGen); var ccu = gen.GenerateCompileUnit(); var output = StringCompiler.CompileToString(ccu); Debug.Log(output); }
public void TestGenerateStructWithPublicFields() { var gen = new CodeUnitGenerator("TestCodeGen"); var structGen = new StructGenerator("TestComponent") .SetIsSealed(false); var field = new FieldGenerator(typeof(int), "MyField", true); structGen.AddField(field); var field2 = new FieldGenerator(typeof(int), "MyField2", true); structGen.AddField(field2); gen.AddType(structGen); var ccu = gen.GenerateCompileUnit(); var output = StringCompiler.CompileToString(ccu); Assert.IsTrue(output.Contains("struct")); Assert.IsTrue(output.Contains("MyField")); Assert.IsTrue(output.Contains("MyField2")); Debug.Log(output); }
public void TestGenerateClassWithFieldPropertyMethod() { var gen = new CodeUnitGenerator("TestCodeGen"); var classGen = new ClassGenerator("TestClass"); var field = new FieldGenerator(typeof(int), "MyField"); var property = new AutoPropertyGenerator("TestClass", "MyProp"); var method = new MethodReturnField(field); method.AddStatement("Debug.Log(\"This is a string\""); classGen.AddAutoProperty(property); classGen.AddField(field); classGen.AddMethod(method); gen.AddType(classGen); var ccu = gen.GenerateCompileUnit(); var output = StringCompiler.CompileToString(ccu); //Debug.Log(output); Assert.IsTrue(output.Contains("MyProp")); Assert.IsTrue(output.Contains("MyField")); Assert.IsTrue(output.Contains("GetMyField")); }
public void SimpleStaticMethodUnitTest() { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; // Create class assembly var stringCompiler = new StringCompiler(); var bytes = stringCompiler.CompileToByteArray(SIMPLE_STATIC_METHOD); Assert.IsNotNull(bytes); var codeAssembly = Assembly.Load(bytes); _assemblies[codeAssembly.FullName] = codeAssembly; var testAssembly = stringCompiler.Compile(SIMPLE_STATIC_METHOD_TEST, new [] { bytes }); Assert.IsNotNull(testAssembly); // Verify that the class exists var exportedType = testAssembly.ExportedTypes.FirstOrDefault(); Assert.IsNotNull(exportedType); Assert.AreEqual("SimpleStaticTests", exportedType.Name); // Get the contructor info and call it var constructor = exportedType.GetConstructors().FirstOrDefault(); Assert.IsNotNull(constructor); var instance = constructor.Invoke(new object[] {}); Assert.IsNotNull(instance); // Verify that the method exists & returns the appropriate response var getAStringMethod = exportedType.GetMethod("SimpleStatic_GetAString"); Assert.IsNotNull(getAStringMethod); getAStringMethod.Invoke(instance, null); }
public async Task <ActionResult> Save(PageRequest pageRequest) { var page = new Page(pageRequest); if (ModelState.IsValid) { if (!string.IsNullOrEmpty(page.Model)) { // compile the model from the string Model declaration in pageRequest // always want to compile model before saving to catch any compile errors using (var stringCompiler = new StringCompiler()) { stringCompiler.CompilePageModel(page.Model); if (stringCompiler.IsValid) { page.CompiledModel = stringCompiler.ToString(); } else { Errors.AddRange(stringCompiler.Errors); } } // end using StringCompiler } // end if page.Model not empty if (Errors.Count == 0) { page = await _CompileTemplateAndSavePage(page, saveAsFile : pageRequest.CreateTemplateFile); } // end if no errors after compiling model } // end if valid model state else { Errors.Add("Invalid parameters"); } return(Json(new { Status = Errors.Count == 0, Errors, Updated = page.Updated.ToString() })); }
public void SimpleStaticMethod() { // Create assembly var stringCompiler = new StringCompiler(); var assembly = stringCompiler.Compile(SIMPLE_STATIC_METHOD); Assert.IsNotNull(assembly); // Verify that the class exists var exportedType = assembly.ExportedTypes.FirstOrDefault(); Assert.IsNotNull(exportedType); Assert.AreEqual("SimpleStatic", exportedType.Name); // Verify that the method exists & returns the appropriate response var getAStringMethod = exportedType.GetMethod("GetAString"); Assert.IsNotNull(getAStringMethod); Assert.AreEqual("A String", getAStringMethod.Invoke(null,null)); }
public void SimpleStaticFailureMethod() { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; // Create class assembly var stringCompiler = new StringCompiler(); var bytes = stringCompiler.CompileToByteArray(SIMPLE_STATIC_FAILURE_METHOD); Assert.IsNotNull(bytes); var codeAssembly = Assembly.Load(bytes); _assemblies[codeAssembly.FullName] = codeAssembly; var testAssembly = stringCompiler.Compile(SIMPLE_STATIC_METHOD_TEST, new[] { bytes }); Assert.IsNotNull(testAssembly); // Verify that the class exists var exportedType = testAssembly.ExportedTypes.FirstOrDefault(); Assert.IsNotNull(exportedType); Assert.AreEqual("SimpleStaticTests", exportedType.Name); // Get the contructor info and call it var constructor = exportedType.GetConstructors().FirstOrDefault(); Assert.IsNotNull(constructor); var instance = constructor.Invoke(new object[] { }); Assert.IsNotNull(instance); // Verify that the method exists & returns the appropriate response var getAStringMethod = exportedType.GetMethod("SimpleStatic_GetAString"); Assert.IsNotNull(getAStringMethod); try { getAStringMethod.Invoke(instance, null); } catch(Exception ex) { while (ex.InnerException != null) { ex = ex.InnerException; } Assert.AreEqual("Assert.AreEqual failed. Expected:<A String>. Actual:<A Failure>. ", ex.Message); } }
public void SimpleNonStaticMethod() { // Create assembly var stringCompiler = new StringCompiler(); var assembly = stringCompiler.Compile(SIMPLE_NONSTATIC_METHOD); Assert.IsNotNull(assembly); // Verify that the class exists var exportedType = assembly.ExportedTypes.FirstOrDefault(); Assert.IsNotNull(exportedType); Assert.AreEqual("SimpleNonStatic", exportedType.Name); // Get the contructor info and call it var constructor = exportedType.GetConstructors().FirstOrDefault(); Assert.IsNotNull(constructor); var instance = constructor.Invoke(new object[] {"My String!"}); Assert.IsNotNull(instance); // Verify that the method exists & returns the injected string var constructorStringMethod = exportedType.GetMethods().FirstOrDefault(m => m.Name == "GetAString" && !m.GetParameters().Any()); Assert.IsNotNull(constructorStringMethod); Assert.AreEqual("My String!", constructorStringMethod.Invoke(instance, null)); // Verify that the overloaded method works as well var parameterStringMethod = exportedType.GetMethods().FirstOrDefault(m => m.Name == "GetAString" && m.GetParameters().Count() == 1); Assert.IsNotNull(parameterStringMethod); Assert.AreEqual("Injected String!", parameterStringMethod.Invoke(instance, new object[] {"Injected String!"})); }
/// <summary> /// Returns view with the template for the passed in name and variable. The /// PageTemplate model is passed to the view. /// </summary> /// <param name="name"></param> /// <param name="section"></param> /// <param name="param"></param> /// <param name="param2"></param> /// <returns></returns> // GET: /Section/Name public ActionResult View(string section, string name, string param = null, string param2 = null) { Page page = null; // will store the page once we find it Func <Page, bool> templateNeedsCompiled = iPage => (string.IsNullOrEmpty(iPage.CompiledTemplate) && (!string.IsNullOrEmpty(iPage.CompiledModel)) && !string.IsNullOrEmpty(iPage.Template)) || iPage.HasInclude; // templage model that will be passed to the View var template = new PageTemplate { Content = string.Empty }; // if AllowCache enabled in Web.Config look for the page in cache if (this.AllowCache) { PageCacheModel cachedPage = this.CacheManager.FindPage(name, section, param, param2, this.QueryStringParams); if (cachedPage != null && cachedPage.CompiledTemplate != null) { page = cachedPage.ToPage(); } } // if we couldn't get the page from cache get it from the db if (page == null || page.CompiledTemplate == null) { page = this._repository.FindPage(section, name); if (page.HasParams) { page.CompiledTemplate = null; } } // when page doesn't have parameters can use pre-compiled template var templateIsCompiled = page != null && !templateNeedsCompiled(page) && !page.HasParams; if (templateIsCompiled) { template.Content = page.CompiledTemplate ?? page.Template; } else if (page != null && (page.HasParams || templateNeedsCompiled(page))) { // if page has url params pass them to model and compile it if (page.HasParams || string.IsNullOrEmpty(page.CompiledModel)) { using (var stringCompiler = new StringCompiler()) { stringCompiler.CompilePageModel(page.Model, param, param2); if (stringCompiler.IsValid) { page.CompiledModel = stringCompiler.ToString(); } else { this.Errors.AddRange(stringCompiler.Errors); } } // end using stringCompiler } // end if page.HasParams and page / param are not null if (templateNeedsCompiled(page)) { ConcurrentBag <string> errors = this.Errors; page.CompileTemplate(ref errors, page.Template, page.CompiledModel); } template.Content = page.CompiledTemplate; } // end else if page has paramaters // cache page before returning template if enabled if (this.AllowCache) { if (page != null && !this.CacheManager.PageCacheExists(page.Name, page.Section, param, param2, this.QueryStringParams)) { this.CacheManager.AddPage(page, param, param2); } } // return the page with a template if it is found if (!string.IsNullOrEmpty(template.Content)) { return(View(template)); } if (Errors.Count > 0) { return(View("~/Views/ServerError.cshtml", Errors)); } // return 404 view if could not find page in db or files return(View("~/Views/NotFound.cshtml")); }