public async Task <IActionResult> ResendEmailVerification() { User user = _context.Users.FirstOrDefault(); if (user == null) { return(View(nameof(Register))); } var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); var confirmationLink = Url.Action(nameof(ConfirmEmail), "Account", new { token, email = user.Email }, Request.Scheme); //send email var variables = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>(Constants.EmailValues.Name, $"{user.FirstName} {user.LastName}"), new KeyValuePair <string, string>(Constants.EmailValues.ConfirmationLink, confirmationLink) }; var message = TemplateReader.GetTemplate(Constants.EmailTemplates.ConfirmationLinkTemplate, variables); _emailService.Send(user.Email, "Confirm your email", message, true); return(View(nameof(EmailVerificationSent))); }
public void Generate(IEnumerable <ClassDefinition> classDefinitions) { var interfaceTemplate = TemplateReader.Read("IRepositoryTemplate.cs.txt"); var classTemplate = TemplateReader.Read("RepositoryTemplate.cs.txt"); foreach (var classDefinition in classDefinitions) { var domainObjectName = classDefinition.Name; var className = domainObjectName + "Repository"; var interfaceName = "I" + className; interfaceTemplate.TypeName = interfaceName; interfaceTemplate.Set("[[InterfaceName]]", interfaceName); interfaceTemplate.Set("[[ClassName]]", className); interfaceTemplate.Set("[[DomainObjectName]]", domainObjectName); ProjectFileWriter.WriteToProject( TargetFolderPath, "Repositories", null, interfaceTemplate); classTemplate.TypeName = className; classTemplate.Set("[[InterfaceName]]", interfaceName); classTemplate.Set("[[ClassName]]", className); classTemplate.Set("[[DomainObjectName]]", domainObjectName); ProjectFileWriter.WriteToProject( TargetFolderPath, "Repositories", null, classTemplate); } }
public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = await _userManager.FindByEmailAsync(model.Email); if (user == null) { return(RedirectToAction(nameof(ForgotPasswordConfirmation))); } var token = await _userManager.GeneratePasswordResetTokenAsync(user); var link = Url.Action(nameof(ResetPassword), "Account", new { token, email = user.Email }, Request.Scheme); var variables = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>(Constants.EmailValues.Name, $"{user.FirstName} {user.LastName}"), new KeyValuePair <string, string>(Constants.EmailValues.PasswordResetLink, link) }; var message = TemplateReader.GetTemplate(Constants.EmailTemplates.PasswordResetTemplate, variables); _emailService.Send(user.Email, "BlogCore Password Reset", message, true); return(RedirectToAction(nameof(ForgotPasswordConfirmation))); }
public override string RenderTag(string line, TemplateReader reader, Dictionary <string, object> parameters, int patternIndex) { Match lineMatch = Regex.Match(line.Trim(), RegularExpressionPatterns[patternIndex]); String statment = lineMatch.Groups["statment"].Value; return(eachParser(statment, reader, parameters)); }
public void TemplateFileTest() { var t = new TemplateReader(); var content = t.GenerateTemplateContent(); Assert.IsNotNull(content); }
public void ReadStylesTest() { var reader = new TemplateReader( @"C:\Users\Sunny\Documents\GitHub\mdocwriter\MDocWriter.WinFormMain\bin\Debug\templates", Template.TemplateFileSearchPattern); var templateContent = reader.GetTemplateContent(reader.Templates.First()); var image = reader.GetPreviewImage(reader.Templates.First()); }
private string render(String line, TemplateReader reader, String pattern, Dictionary <string, object> parameters, bool renderWithTextBlock = false) { Match lineMatch = Regex.Match(line.Trim(), pattern); String tag = "div"; String text = ""; List <string> attributes = new List <string>(); int level = reader.Level; if (lineMatch.Groups["tag"].Success) { tag = lineMatch.Groups["tag"].Value; } if (lineMatch.Groups["text"].Success) { text = lineMatch.Groups["text"].Value; } StringBuilder textBuilder = new StringBuilder(); if (text.Length > 0) { textBuilder.Append(TemplateRendererUtils.CreateIndent(renderer.LineIndent + 1)); textBuilder.Append(text); textBuilder.Append("\n"); } renderer.LineIndent++; String sourceBlock; if (renderWithTextBlock || textBlockTags.Contains(tag)) { sourceBlock = reader.ReadBlockWithIndent(renderer.LineIndent); sourceBlock = sourceBlock.TrimEnd('\n'); if (sourceBlock.Length > 0) { textBuilder.Append(sourceBlock); textBuilder.Append("\n"); } } else { sourceBlock = reader.ReadBlock(); textBuilder.Append(renderer.RenderBlock(sourceBlock)); } renderer.LineIndent--; if (lineMatch.Groups["id"].Success) { attributes.Add("id=\"" + lineMatch.Groups["id"].Value + "\""); } if (lineMatch.Groups["class"].Success) { attributes.Add("class=\"" + lineMatch.Groups["class"].Value + "\""); } foreach (Capture cap in lineMatch.Groups["attr"].Captures) { attributes.Add(cap.Value.Trim()); } return(generateTag(tag, attributes, textBuilder.ToString())); }
public override void ExportProject(Dictionary <string, FileOutput> output, IList <LibraryForExport> libraries, ResourceDatabase resourceDatabase, Options options) { Dictionary <string, string> replacements = this.GenerateReplacementDictionary(options, resourceDatabase); TemplateReader templates = new TemplateReader(new PkgAwareFileUtil(), this); TemplateSet vmTemplates = templates.GetVmTemplates(); string functions = vmTemplates.GetText("functions.php"); string structs = vmTemplates.GetText("structs.php"); string byteCode = ConvertStringToVariableSetterFile(resourceDatabase.ByteCodeFile.TextContent, "_CRAYON_BYTE_CODE"); string resourceManifest = ConvertStringToVariableSetterFile(resourceDatabase.ResourceManifestFile.TextContent, "_CRAYON_RESOURCE_MANIFEST"); output["crayon_gen/bytecode.php"] = FileOutput.OfString(byteCode); output["crayon_gen/resource_manifest.php"] = FileOutput.OfString(resourceManifest); output["crayon_gen/functions.php"] = FileOutput.OfString(functions); output["crayon_gen/structs.php"] = FileOutput.OfString(structs); output["index.php"] = FileOutput.OfString(this.LoadTextResource("Resources/index.php", replacements)); output[".htaccess"] = FileOutput.OfString(this.LoadTextResource("Resources/htaccess.txt", replacements)); List <string> libsIncluder = new List <string>() { "<?php" }; foreach (LibraryForExport library in libraries.Where(lib => lib.HasNativeCode)) { foreach (string key in library.ExportEntities.Keys) { foreach (ExportEntity entity in library.ExportEntities[key]) { switch (key) { case "COPY_CODE": string target = entity.Values["target"]; string fileContent = entity.FileOutput.TextContent; int lastLine = fileContent.LastIndexOf('\n'); fileContent = fileContent.Substring(0, lastLine); // trim off '?>' fileContent = fileContent.TrimEnd() + string.Join("\n", new string[] { "", "", "\t$_CRAYON_LIBS['" + library.Name + "'] = crayon_generateFunctionLookup('CrayonLibWrapper_" + library.Name + "');", "?>", }); output["crayon_gen/" + target] = FileOutput.OfString(fileContent); libsIncluder.Add("\trequire 'crayon_gen/" + target + "';"); break; default: throw new System.NotImplementedException(); } } } } libsIncluder.Add("?>"); output["crayon_gen/libs.php"] = FileOutput.OfString(string.Join("\n", libsIncluder)); }
public async Task <IActionResult> Register(RegisterViewModel model) { User admin = _context.Users.FirstOrDefault(); if (admin == null) { model.RegisterEnabled = true; if (model.Password != model.ConfirmPassword) { ModelState.TryAddModelError("PasswordMismatch", "The password fields must match."); } if (!ModelState.IsValid) { return(View(model)); } var user = new User { FirstName = model.FirstName, LastName = model.LastName, UserName = model.Email, Email = model.Email }; IdentityResult result = await _userManager.CreateAsync(user, model.Password); if (!result.Succeeded) { foreach (var error in result.Errors) { ModelState.TryAddModelError(error.Code, error.Description); } return(View(model)); } var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); var confirmationLink = Url.Action(nameof(ConfirmEmail), "Account", new { token, email = user.Email }, Request.Scheme); //send email var variables = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>(Constants.EmailValues.Name, $"{user.FirstName} {user.LastName}"), new KeyValuePair <string, string>(Constants.EmailValues.ConfirmationLink, confirmationLink) }; var message = TemplateReader.GetTemplate(Constants.EmailTemplates.ConfirmationLinkTemplate, variables); _emailService.Send(user.Email, "Confirm your email", message, true); await _userManager.AddToRoleAsync(user, "Visitor"); return(RedirectToAction(nameof(SuccessRegistration))); } return(View(model)); }
public override string RenderTag(string line, TemplateReader reader, Dictionary <string, object> parameters, int patternIndex) { if (patternIndex < 3) { return(declareMixin(line, reader, patternIndex)); } else { return(callMixin(line, reader, parameters, patternIndex)); } }
private string eachParser(string statment, TemplateReader reader, Dictionary <string, object> parameters) { string variable = @"([a-zA-Z_][a-zA-Z0-9_]*)([\.]([a-zA-Z_][a-zA-Z0-9_]*))*"; string indexPattern = "(,[ ]*(?<index>" + variable + "))"; string iteratorPattern = "(?<iterator>" + variable + ")"; string collectionPattern = "(?<collection>" + variable + ")"; string optional = "?"; string regex = iteratorPattern + "[ ]*" + indexPattern + optional + "[ ]+in[ ]+" + collectionPattern; Match m = Regex.Match(statment, regex); StringBuilder builder = new StringBuilder(); if (m.Success) { String indexName = null; bool isWithIndex = m.Groups["index"].Success; if (isWithIndex) { indexName = m.Groups["index"].Value; } var iteratorName = m.Groups["iterator"].Value; var collectionName = m.Groups["collection"].Value; string codeBlock = reader.ReadBlock(); if (codeBlock.Length == 0) { return(""); } int index = 0; dynamic collection = parameters[collectionName]; if (isWithIndex) { parameters.Add(indexName, 0); } foreach (var it in collection) { parameters.Add(iteratorName, it); if (isWithIndex) { parameters[indexName] = index; } index++; builder.Append(renderer.RenderBlock(codeBlock)); parameters.Remove(iteratorName); } if (isWithIndex) { parameters.Remove(indexName); } } else { throw new TemplateException("Can't parse each statment."); } return(builder.ToString()); }
public void ReadTemplateTest_NoBaseTroopError() { string contents = File.ReadAllText(flyingMonkeyJson); //Setup base monkey troop TroopReader troopReader = new TroopReader(); TemplateReader reader = new TemplateReader(contents, troopReader.TroopTypes); Assert.Throws <InvalidOperationException>(() => { TroopType flyingMonkey = reader.Read(); }); }
public void GenerationAndCompile() { var compiler = new Compiler(); var template = new TemplateReader(); GenerateMoreOrLess(); string code = template.GenerateTemplateContent(); var res = compiler.Compile(code); var type = res.CompiledAssembly.GetType("DNAI.Behaviour.Behaviour"); Assert.IsNotNull(type); }
public void ExtractTemplateResources() { if (this.document == null) { throw new InvalidOperationException("There is no document opened in the workspace."); } var templateId = this.document.TemplateId; var templateReader = new TemplateReader(); var template = templateReader.GetTemplate(templateId); if (template != null && template.Resources != null && template.Resources.Length > 0) { // prepare the directory under working directory to store the resources var templateResourceDirectory = Path.Combine( this.workingDirectory, string.Format(TemplateTempDirectoryPattern, templateId.ToString().ToUpper().Replace("-", "_"))); if (Directory.Exists(templateResourceDirectory)) { Directory.Delete(templateResourceDirectory, true); } Directory.CreateDirectory(templateResourceDirectory); // read all the entries in the zip file, and find the resource items using (var templateFileStream = File.OpenRead(template.MDocxTemplateFileName)) using (var zipFile = new ZipFile(templateFileStream)) { foreach (ZipEntry zipEntry in zipFile) { var zipEntryName = zipEntry.Name.Replace('/', '\\'); if (zipEntry.IsFile && template.Resources.Any(r => string.Equals(zipEntryName, r))) { var outputFileName = Path.Combine(templateResourceDirectory, zipEntryName); var outputDirectoryName = Path.GetDirectoryName(outputFileName); if (!string.IsNullOrEmpty(outputDirectoryName) && !Directory.Exists(outputDirectoryName)) { Directory.CreateDirectory(outputDirectoryName); } using (var zipEntryStream = zipFile.GetInputStream(zipEntry)) using (var outputFileStream = File.OpenWrite(outputFileName)) { var buffer = new byte[4096]; StreamUtils.Copy(zipEntryStream, outputFileStream, buffer); } } } } } }
private void GetLibraryCode( TemplateReader templateReader, string baseDir, LibraryForExport library, List <LangCSharp.DllFile> dllsOut, HashSet <string> dotNetRefs, Dictionary <string, FileOutput> filesOut) { string libraryName = library.Name; TemplateSet libTemplates = templateReader.GetLibraryTemplates(library); List <string> libraryLines = new List <string>(); string libraryDir = baseDir + "Libraries/" + libraryName; foreach (string structKey in libTemplates.GetPaths("gen/structs/")) { string structFileName = structKey.Substring(structKey.LastIndexOf('/') + 1); string structName = System.IO.Path.GetFileNameWithoutExtension(structFileName); filesOut[libraryDir + "/" + structName + ".cs"] = new FileOutput() { Type = FileOutputType.Text, TextContent = libTemplates.GetText(structKey), }; } foreach (string helperFile in libTemplates.GetPaths("source/")) { filesOut[libraryDir + "/" + helperFile.Substring("source/".Length)] = new FileOutput() { Type = FileOutputType.Text, TextContent = libTemplates.GetText(helperFile), }; } filesOut[libraryDir + "/LibraryWrapper.cs"] = new FileOutput() { Type = FileOutputType.Text, TextContent = libTemplates.GetText("gen/LibraryWrapper.cs"), }; foreach (ExportEntity dllFile in library.ExportEntities["DOTNET_DLL"]) { dllsOut.Add(new LangCSharp.DllFile(dllFile)); } foreach (ExportEntity dotNetRef in library.ExportEntities["DOTNET_REF"]) { dotNetRefs.Add(dotNetRef.StringValue); } }
public string declareMixin(string line, TemplateReader reader, int patternIndex) { Match m = Regex.Match(line.Trim(), RegularExpressionPatterns[patternIndex]); Mixin mixin = new Mixin(); String mixinName = m.Groups["name"].Value; foreach (Capture cap in m.Groups["attr_name"].Captures) { mixin.parameters.Add(cap.Value); } String block = reader.ReadBlockWithIndent(0); mixin.block = block; mixins.Add(mixinName, mixin); return(""); }
public string callMixin(string line, TemplateReader reader, Dictionary <string, object> parameters, int patternIndex) { Match m = Regex.Match(line.Trim(), RegularExpressionPatterns[patternIndex]); List <object> mixinParams = new List <object>(); String mixinName = m.Groups["name"].Value; Mixin mixin = mixins[mixinName]; var interpreter = new Interpreter(); Dictionary <string, object> outerParameters = new Dictionary <string, object>(); foreach (var element in parameters) { interpreter.SetVariable(element.Key, element.Value, element.Value.GetType()); } foreach (Capture cap in m.Groups["param"].Captures) { var result = interpreter.Eval(cap.Value); mixinParams.Add(result); } if (mixinParams.Count != mixin.parameters.Count) { throw new TemplateException("Missmatch number of mixin arguments"); } for (int i = 0; i < mixinParams.Count; i++) { if (parameters.ContainsKey(mixin.parameters[i])) { outerParameters.Add(mixin.parameters[i], parameters[mixin.parameters[i]]); parameters[mixin.parameters[i]] = mixinParams[i]; } else { parameters.Add(mixin.parameters[i], mixinParams[i]); } } String blockRendered = renderer.RenderBlock(mixin.block); foreach (var n in mixin.parameters) { parameters.Remove(n); } foreach (var p in outerParameters) { parameters.Add(p.Key, p.Value); } return(blockRendered); }
private void GenerateStartupFile(List <string> addServiceCommands) { var startupTemplate = TemplateReader.Read("StartupTemplate.cs.txt"); var startupLineSeparator = Environment.NewLine + " "; var addServiceCommandString = string.Join(startupLineSeparator, addServiceCommands); startupTemplate.TypeName = "Startup"; startupTemplate.Set("[[AddServiceCommands]]", addServiceCommandString); ProjectFileWriter.WriteToProject( TargetFolderPath, "WebApi", null, startupTemplate); }
public override string RenderTag(string line, TemplateReader reader, Dictionary <string, object> parameters, int patternIndex) { Match m = Regex.Match(line.Trim(), RegularExpressionPatterns[patternIndex]); String type = m.Groups["statment"].Value; type = type.Trim(); string realType; switch (type) { case "xml": realType = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"; break; case "transitional": realType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"; break; case "strict": realType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"; break; case "frameset": realType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">"; break; case "1.1": realType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">"; break; case "basic": realType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML Basic 1.1//EN\" \"http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd\">"; break; case "mobile": realType = "<!DOCTYPE html PUBLIC \"-//WAPFORUM//DTD XHTML Mobile 1.2//EN\" \"http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd\">"; break; default: realType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML Basic 1.1//EN\" \"http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd\">"; break; } return(realType + "\n"); }
private void button1_Click(object sender, EventArgs e) { var googleSerch = new GoogleSearchParser(); var youTube = new SearchYoutube(); var searchTermBuilder = new SearchTermBuilder(); var googleSuggest = new GoogleSuggest(); var TemplateReader = new TemplateReader(textBoxContentFile.Text); var SnipetReader = new TemplateReader(textBoxSnipetFile.Text); var TitlesReader = new TemplateReader(textBoxTitleFile.Text); var CraditReader = new TemplateReader(textBoxCredit.Text); var postBuilder = new PostBuilder(textBoxURL.Text, textBoxUserName.Text, textBoxPassword.Text); var program = new ProgramFlow(textBoxSubject.Text, textBoxURL.Text, CraditReader, googleSerch, searchTermBuilder, SnipetReader, TitlesReader, googleSuggest, TemplateReader, postBuilder, youTube); program.run(); }
/// <summary> /// If in child template collect blocks /// If in parrent render blocks using child blocks /// </summary> /// <param name="line"></param> /// <param name="reader"></param> /// <param name="parameters"></param> /// <param name="patternIndex"></param> /// <returns></returns> public override string RenderTag(string line, TemplateReader reader, Dictionary <string, object> parameters, int patternIndex) { Match lineMatch = Regex.Match(line.Trim(), RegularExpressionPatterns[patternIndex]); String statment = lineMatch.Groups["statment"].Value; if (!renderer.GetPlugin <ExtendsPlugin>().IsInParrent) { blocks.Add(statment, reader.ReadBlock()); return(""); } StringBuilder renderedSource = new StringBuilder(); renderedSource.Append(renderer.RenderBlock(reader.ReadBlock())); if (blocks.ContainsKey(statment)) { renderedSource.Append(renderer.RenderBlock(blocks[statment])); } return(renderedSource.ToString()); }
public override string RenderTag(string line, TemplateReader reader, Dictionary <string, object> parameters, int patternIndex) { Match lineMatch = Regex.Match(line.Trim(), RegularExpressionPatterns[patternIndex]); String condition = lineMatch.Groups["condition"].Value; var interpreter = new Interpreter(); foreach (var element in parameters) { interpreter.SetVariable(element.Key, element.Value, element.Value.GetType()); } var result = interpreter.Eval <bool>(condition); if (result) { return(renderer.RenderBlock(reader.ReadBlock())); } reader.ReadBlock(); return(""); }
public void ReadTemplateTest_Valid() { string monkeyData = File.ReadAllText(monkeyJson); string contents = File.ReadAllText(flyingMonkeyJson); //Setup base monkey troop TroopReader troopReader = new TroopReader(); troopReader.AddJson(monkeyData); TroopType monkey = troopReader.TroopTypes["Monkey"]; TemplateReader reader = new TemplateReader(contents, troopReader.TroopTypes); TroopType flyingMonkey = reader.Read(); Assert.AreEqual(flyingMonkey.Damage, monkey.Damage); Assert.AreEqual(flyingMonkey.Health, monkey.Health); Assert.AreEqual(flyingMonkey.Type, "Air"); Assert.AreEqual(flyingMonkey.PreferredTarget, "Air"); }
private bool GenerateOutputFile() { string templateFile = Program.Config.GetTemplateFilePath(); if (templateFile == null) { lastOutputGenError = Lang.Get["LoadProjectErrorNoTemplate"]; return(false); } outputFile = Program.Config.GetOutputFilePath(); TemplateList templateList; try{ templateList = new TemplateReader(templateFile).ReadTemplates(); }catch (TemplateException e) { lastOutputGenError = e.Message; return(false); } GenerateHtml generator = new GenerateHtml(templateList, variables); switch (generator.ToFile(outputFile)) { case GenerateHtml.Result.Succeeded: return(true); case GenerateHtml.Result.TemplateError: lastOutputGenError = Lang.Get["LoadProjectErrorInvalidTemplate", generator.LastError]; return(false); case GenerateHtml.Result.IoError: lastOutputGenError = Lang.Get["LoadProjectErrorIO", generator.LastError]; return(false); default: lastOutputGenError = Lang.Get["LoadProjectErrorUnknown"]; return(false); } }
public void Generate(IEnumerable <ClassDefinition> classDefinitions) { var template = TemplateReader.Read("ViewModelTemplate.cs.txt"); foreach (var classDefinition in classDefinitions) { var propertiesString = CreatePropertiesString(classDefinition.Properties); var viewModelClassName = classDefinition.Name + "ViewModel"; template.TypeName = viewModelClassName; template.Set("[[ClassName]]", viewModelClassName); template.Set("[[Properties]]", propertiesString); ProjectFileWriter.WriteToProject( TargetFolderPath, "ViewModels", null, template); } }
public override string RenderTag(string line, TemplateReader reader, Dictionary <string, object> parameters, int patternIndex) { Match lineMatch = Regex.Match(line.Trim(), RegularExpressionPatterns[patternIndex]); String statment = lineMatch.Groups["statment"].Value; if (statment.Contains(" ")) { throw new TemplateException("Name of template can't contains space"); } Parent = statment; IsInParrent = false; String childSource = reader.ReadToEnd(); renderer.RenderBlock(childSource); TextReader fileReader = File.OpenText(statment + ".fte"); String parrentSource = fileReader.ReadToEnd(); fileReader.Close(); IsInParrent = true; return(renderer.RenderBlock(parrentSource)); }
private string Transform(IEnumerable <KeyValuePair <string, string> > parameters) { var templateReader = new TemplateReader(); var template = templateReader.GetTemplate(this.document.TemplateId); if (template != null) { var templateContent = templateReader.GetTemplateContent(template); foreach (var kvp in parameters) { if (templateContent.IndexOf(kvp.Key, StringComparison.Ordinal) > 0) { templateContent = templateContent.Replace(kvp.Key, kvp.Value); } } return(templateContent); } var keyValuePairs = parameters as KeyValuePair <string, string>[] ?? parameters.ToArray(); return(keyValuePairs.Any(p => p.Key.Equals(Template.MacroDocumentBody)) ? keyValuePairs.First(p => p.Key.Equals(Template.MacroDocumentBody)).Value : null); }
public void GenerationFromController() { var compiler = new Compiler(); var template = new TemplateReader(); var _manager = new BinaryManager(); var variables = new List <Entity>(); var functions = new List <Entity>(); var dataTypes = new List <Entity>(); //GenerateDulyFile(); GenerateMoreOrLess(); _manager.LoadCommandsFrom("More Or Less.dnai"); //GenerateMoreOrLess(_manager, out variables, out functions); var ids = _manager.Controller.GetIds(EntityType.CONTEXT | EntityType.PUBLIC); foreach (var id in ids) { dataTypes.AddRange(_manager.Controller.GetEntitiesOfType(ENTITY.DATA_TYPE, id)); variables.AddRange(_manager.Controller.GetEntitiesOfType(ENTITY.VARIABLE, id)); functions.AddRange(_manager.Controller.GetEntitiesOfType(ENTITY.FUNCTION, id)); } //variables = _manager.Controller.GetEntitiesOfType(ENTITY.VARIABLE, ids[1]); //functions = _manager.Controller.GetEntitiesOfType(ENTITY.FUNCTION, ids[1]); //GenerateMoreOrLess(_manager, out List<Entity> variables, out List<Entity> functions); string code = template.GenerateTemplateContent(_manager, variables, functions, dataTypes); var res = compiler.Compile(code); res = compiler.Compile(code); var type = res.CompiledAssembly.GetType("DNAI.MoreOrLess.MoreOrLess"); Assert.IsNotNull(type); var func = type.GetMethod("ExecutePlay"); Assert.IsNotNull(func); }
public override string RenderTag(string line, TemplateReader reader, Dictionary <string, object> parameters, int patternIndex) { switch (patternIndex) { case 0: return(render(line, reader, RegularExpressionPatterns[patternIndex], parameters)); case 1: return(render(line, reader, RegularExpressionPatterns[patternIndex], parameters)); case 2: return(render(line, reader, RegularExpressionPatterns[patternIndex], parameters)); case 3: return(render(line, reader, RegularExpressionPatterns[patternIndex], parameters)); case 4: return(render(line, reader, RegularExpressionPatterns[patternIndex], parameters, true)); case 5: return(render(line, reader, RegularExpressionPatterns[patternIndex], parameters, true)); case 6: return(render(line, reader, RegularExpressionPatterns[patternIndex], parameters)); case 7: return(render(line, reader, RegularExpressionPatterns[patternIndex], parameters)); case 8: return(render(line, reader, RegularExpressionPatterns[patternIndex], parameters, true)); case 9: return(render(line, reader, RegularExpressionPatterns[patternIndex], parameters, true)); } throw new TemplateException("Can't parse html tag."); }
private void ExportInterpreter( TemplateReader templateReader, string baseDir, Dictionary <string, FileOutput> output) { TemplateSet vmTemplates = templateReader.GetVmTemplates(); foreach (string structKey in vmTemplates.GetPaths("structs/")) { string structFileName = structKey.Substring(structKey.LastIndexOf('/') + 1); string structName = System.IO.Path.GetFileNameWithoutExtension(structFileName); output[baseDir + "Structs/" + structName + ".cs"] = new FileOutput() { Type = FileOutputType.Text, TextContent = vmTemplates.GetText(structKey), }; } output[baseDir + "Vm/CrayonWrapper.cs"] = new FileOutput() { Type = FileOutputType.Text, TextContent = vmTemplates.GetText("CrayonWrapper.cs"), }; }
public void Generate(IEnumerable <ClassDefinition> classDefinitions) { var interfaceTemplate = TemplateReader.Read("IMapTemplate.cs.txt"); var classTemplate = TemplateReader.Read("MapTemplate.cs.txt"); foreach (var classDefinition in classDefinitions) { var domainObjectName = classDefinition.Name; var className = domainObjectName + "Map"; var interfaceName = "I" + className; interfaceTemplate.TypeName = interfaceName; interfaceTemplate.Set("[[DomainObjectName]]", domainObjectName); ProjectFileWriter.WriteToProject( TargetFolderPath, "Services", null, interfaceTemplate); classTemplate.TypeName = className; classTemplate.Set("[[DomainObjectName]]", domainObjectName); classTemplate.Set( "[[DomainToViewModelMappings]]", GenerateMappingString("domain", "viewModel", classDefinition.Properties)); classTemplate.Set( "[[ViewModelToDomainMappings]]", GenerateMappingString("viewModel", "domain", classDefinition.Properties)); ProjectFileWriter.WriteToProject( TargetFolderPath, "Services", null, classTemplate); } }