private static void RunMustacheSpecs(MustacheSpec.MustacheTest test) { TemplateLocator testDataTemplateLocator = name => { if (test.Partials != null && test.Partials[name] != null) { var template = new Template(); template.Load(new StringReader(test.Partials[name].ToString())); return template; }; return null; }; var rendered = Render.StringToString(test.Template, test.Example, testDataTemplateLocator); Assert.AreEqual(test.Expected, rendered, "JSON object rendering failed for " + test.Description); rendered = Render.StringToString(test.Template, test.StronglyTypedExample, testDataTemplateLocator); Assert.AreEqual(test.Expected, rendered, "Strongly typed rendering failed for " + test.Description); var templ = new Template(); templ.Load(new StringReader(test.Template)); if (!test.Name.ToLower().Contains("context miss") && !test.Name.ToLower().Contains("broken chain") && !(test.SpecName == "inverted" && (test.Name == "List" || test.Name == "Context"))) { try { var compiledTemplate = templ.Compile( test.StronglyTypedExample != null ? test.StronglyTypedExample.GetType() : typeof(object), testDataTemplateLocator); rendered = compiledTemplate(test.StronglyTypedExample); Assert.AreEqual(test.Expected, rendered, "Compiled Template rendering failed for " + test.Description); } catch (Nustache.Core.NustacheException ex) { if (ex.Message.StartsWith("Unsupported:")) { Assert.Inconclusive(ex.Message); } } } else { bool gotException = false; try { var compiledTemplate = templ.Compile( test.StronglyTypedExample != null ? test.StronglyTypedExample.GetType() : typeof(object), testDataTemplateLocator); } catch (Compilation.CompilationException) { gotException = true; } Assert.IsTrue(gotException, "Expected test to throw a compilation exception for an invalid template"); } }
public List<IResource> GetResources(int folderId) { IResource template1 = new Template { Name = "Template1", Description = "Template1 description" }; // Just return a List of simple templates for now return new List<IResource> { template1 }; }
public void It_handles_nested_sections_with_the_same_name() { var parser = new Parser(); var template = new Template(); parser.Parse(template, new Part[] { new LiteralText("before foo 1"), new Block("foo"), new LiteralText("before foo 2"), new Block("foo"), new LiteralText("inside foo 2"), new EndSection("foo"), new LiteralText("after foo 2"), new EndSection("foo"), new LiteralText("after foo 1") }); template.Parts.IsEqualTo(new LiteralText("before foo 1"), new Block("foo", new LiteralText("before foo 2"), new Block("foo", new LiteralText("inside foo 2"), new EndSection("foo")), new LiteralText("after foo 2"), new EndSection("foo")), new LiteralText("after foo 1")); }
public static TemplateGenerationStatusEventArgs CreateWaiting(Template template) { if (template == null) throw new ArgumentNullException("template"); return new TemplateGenerationStatusEventArgs(template, GenerationStatus.Waiting); }
public void It_can_include_templates_over_three_levels_with_external_includes() { var baseTemplate = new Template("Base"); baseTemplate.Load(new StringReader("Base{{>BaseContent}}")); var masterTemplate = new Template("Master"); masterTemplate.Load(new StringReader("{{<BaseContent}}Master{{>MasterContent}}{{/BaseContent}}{{>Base}}")); var templates = new Dictionary<string, Template>(); templates.Add("Base", baseTemplate); templates.Add("Master", masterTemplate); TemplateLocator locateTemplate = name => { Template ret; templates.TryGetValue(name, out ret); if (ret == null) throw new KeyNotFoundException(string.Format("The view '{0}' could not be found.", name)); return ret; }; var result = Render.StringToString("{{<MasterContent}}Hello{{/MasterContent}}{{>Master}}", null, locateTemplate); Assert.AreEqual("BaseMasterHello", result); }
public virtual Template GetMessageTemplate(bool verbose) { Template messageST = new Template(GetErrorType().msg); messageST.impl.Name = errorType.Name; messageST.Add("verbose", verbose); object[] args = GetArgs(); for (int i = 0; i < args.Length; i++) { string attr = "arg"; if (i > 0) attr += i + 1; messageST.Add(attr, args[i]); } if (args.Length < 2) messageST.Add("arg2", null); // some messages ref arg2 Exception cause = GetCause(); if (cause != null) { messageST.Add("exception", cause); messageST.Add("stackTrace", cause.StackTrace); } else { messageST.Add("exception", null); // avoid ST error msg messageST.Add("stackTrace", null); } return messageST; }
public virtual IUimlElement Resolve(Template t, IUimlElement placeholder) { // add all children of the template's top element to placeholder's children Console.Write("Trying to unite element '{0}' with template '{1}'... ", ((UimlAttributes) placeholder).Identifier, t.Identifier); try { // check if types are compatible if (t.Top.GetType().Equals(placeholder.GetType())) { // TODO: check for children with the same identifier, and resolve name conflicts! // add elements from template's top element placeholder.Children.AddRange(t.Top.Children); Console.WriteLine("OK!"); } else Console.WriteLine("Failed! -> incompatible types, no action taken"); } catch (Exception e) { Console.WriteLine("Failed!"); } return placeholder; // always return placeholder, whether it's modified or not }
public void TestComplicatedExpression() { var templateContent = "${(8+2)*(5+5) - ((2+8)/2)}"; var template = new Template(templateContent); var render = template.Render(); Assert.AreEqual("95", render); }
public void TestUnknownVariablesAreIgnored() { Template template = new Template("Hello, ${name}"); template.Set("unknown", "Hi"); template.Set("name", "Tom"); Assert.AreEqual("Hello, Tom", template.Evaluate()); }
public bool AddTemplate(Template template) { Debug.Assert(template.ImportPrecedence == 0); template.ImportPrecedence = this.importPrecedence; template.OrderNumber = this.orderNumber++; compiler.AllTemplates.Add(template); if (template.Name != null) { Template old; if (!compiler.NamedTemplates.TryGetValue(template.Name, out old)) { compiler.NamedTemplates[template.Name] = template; } else { Debug.Assert(template.ImportPrecedence <= old.ImportPrecedence, "Global objects are processed in order of decreasing import precedence"); if (old.ImportPrecedence == template.ImportPrecedence) { return false; } } } if (template.Match != null) { Templates.Add(template); } return true; }
public override Template Visit(Root root) { Template template = new Template("#include \"<header>\"\n\n<body>"); template.Add("header", this.HeaderFileName); template.Add("body", root.Block.Accept(this)); return template; }
public override Template Visit(GlobalBlock block) { Template template = new Template("<list; separator=\"\n\">"); List<Template> list = new List<Template>(); bool last = false; AstNode last_node = null; foreach (var node in block.List) { bool current = node is FuncDef || node is Class || node is Enum || node is Import || node is GlobalUsing || node is Namespace; if ((last || current) && !(last_node is Import && node is Import)) { Template tp = new Template("\n<node>"); tp.Add("node", node.Accept(this)); list.Add(tp); } else { list.Add(node.Accept(this)); } last = current; last_node = node; } template.Add("list", list); return template; }
private void FileSaved(string path) { if (!FileChanged(path)) return; try { var stopwatch = Stopwatch.StartNew(); Log.Debug("FileSaved {0}", path); var projectItem = dte.Solution.FindProjectItem(path); var template = new Template(projectItem); foreach (var item in GetReferencedProjectItems(projectItem, ".cs")) { eventQueue.Enqueue(generationEvent => Render(template, generationEvent), GenerationType.Render, item.Path()); } template.SaveProjectFile(); stopwatch.Stop(); Log.Debug("FileSaved completed in {0} ms", stopwatch.ElapsedMilliseconds); } catch (Exception e) { Log.Debug(e.Message); } }
public static TemplateMetrics Compute(Template template) { TemplateMetrics metrics = new TemplateMetrics(template); foreach (TemplateOutputDefinitionFilenameResult outputFilename in template.GetOutputFilenames()) { metrics.FileCount++; if (File.Exists(outputFilename.Value)) { FileInfo fileInfo = new FileInfo(outputFilename.Value); metrics.TotalFileSize += fileInfo.Length; using (StreamReader reader = File.OpenText(outputFilename.Value)) { while (!reader.EndOfStream) { metrics.CharacterCount += reader.ReadLine().ValueOrDefault(s => s.Length); metrics.LineCount++; } } } } return metrics; }
public void Rendering_untemplated_text_replaces_nothing() { var text = "${TemplateKey"; var text2 = "{TemplateKey}"; var text3 = "$TemplateKey}"; var text4 = "TemplateKey"; var template = new Template(_name, text, _factory); var template2 = new Template(_name, text2, _factory); var template3 = new Template(_name, text3, _factory); var template4 = new Template(_name, text4, _factory); _templateModel.Stub(m => m.GetProperty("TemplateKey")).Return("Different value") .Repeat.Times(4); template.PrepareDynamicRendering(); template2.PrepareDynamicRendering(); template3.PrepareDynamicRendering(); template4.PrepareDynamicRendering(); var renderedText = template.Render(_viewModel); var renderedText2 = template2.Render(_viewModel); var renderedText3 = template3.Render(_viewModel); var renderedText4 = template4.Render(_viewModel); Assert.AreEqual(text, renderedText); Assert.AreEqual(text2, renderedText2); Assert.AreEqual(text3, renderedText3); Assert.AreEqual(text4, renderedText4); }
public ActionResult Create(Template template) { var templateToCreate = new Template(); Mapper.Map(template, templateToCreate); templateToCreate.Seminar = SiteService.GetLatestSeminar(Site, true); ModelState.Clear(); templateToCreate.TransferValidationMessagesTo(ModelState); if (ModelState.IsValid) { // inactivate all old templates foreach (var t in _templateRepository.Queryable.Where(a => a.NotificationType == templateToCreate.NotificationType)) { t.IsActive = false; _templateRepository.EnsurePersistent(t); } _templateRepository.EnsurePersistent(templateToCreate); Message = "Template Created Successfully"; return RedirectToAction("Index"); } var viewModel = TemplateViewModel.Create(Repository, templateToCreate); return View(viewModel); }
public override Template Visit(TemplateType type) { Template template = new Template("<type>\\<<list; separator=\", \">>"); template.Add("type", type.Type.Accept(this)); template.Add("list", type.Args.Select(x => x.Accept(this))); return template; }
/// <summary> /// Creates a new session for assembling documents using the HotDocs Cloud Services Rest API. /// </summary> /// <param name="template">The template to use with the session.</param> /// <param name="billingRef">This parameter lets you specify information that will be included in usage logs for this call. For example, you can use a string to uniquely identify the end user that initiated the request and/or the context in which the call was made. When you review usage logs, you can then see which end users initiated each request. That information could then be used to pass costs on to those end users if desired.</param> /// <param name="answers">The answers to use.</param> /// <param name="markedVariables">An array of variable names, whose prompts should be "marked" when displayed in an interview.</param> /// <param name="interviewFormat">The format to use when displaying an interview.</param> /// <param name="outputFormat">The format to use when assembling a document.</param> /// <param name="settings">The settings to use with the session.</param> /// <param name="theme">The interview theme.</param> /// <param name="showDownloadLinks">Indicates whether or not links for downloading the assembled document(s) should appear at the end of the interview.</param> /// <returns></returns> public string CreateSession( Template template, string billingRef = null, string answers = null, string[] markedVariables = null, InterviewFormat interviewFormat = InterviewFormat.JavaScript, OutputFormat outputFormat = OutputFormat.Native, Dictionary<string, string> settings = null, string theme = null, bool showDownloadLinks = true ) { return (string)TryWithoutAndWithPackage( (uploadPackage) => CreateSessionImpl( template, billingRef, answers, markedVariables, interviewFormat, outputFormat, settings, theme, showDownloadLinks, uploadPackage) ); }
public static void InvokeTemplateDeleted(TemplateProfile profile, Template template) { if (profile != null && !profile.Deleted && template != null && OnTemplateDeleted != null) { OnTemplateDeleted(profile, template); } }
public void SetUp() { var source1 = new TestSource { Name = "-artist-", GetAllItemsFunc = c => new[] { new DynamicItem("beatles", new [] { new ContextItem("artist-id", "1") }), new DynamicItem("beach-boys", new [] { new ContextItem("artist-id", "2") }) } }; var source2 = new TestSource { Name = "-album-", GetAllItemsFunc = c => { return c.Any(i => i.Name == "artist-id" && i.Value == "1") ? new[] { new DynamicItem("revolver") } : new[] { new DynamicItem("pet-sounds") }; } }; var dynamicSourceProvider = MockRepository.GenerateMock<IDynamicSourceProvider>(); dynamicSourceProvider.Stub(p => p.Get("-artist-")).Return(source1); dynamicSourceProvider.Stub(p => p.Get("-album-")).Return(source2); var pathInstanceBuilder = new PathInstanceBuilder(dynamicSourceProvider); var template = new Template(new[] { "static", "-artist-", "-album-" }); template.BuildInstancePaths(pathInstanceBuilder); this.resource = new TemplateResourceBuilder().Build(template) as TemplateResource; }
public void Init(Template template, App app, ModuleInfo hostingModule, IDataSource dataSource, InstancePurposes instancePurposes, SxcInstance sexy) { var templatePath = VirtualPathUtility.Combine(Internal.TemplateManager.GetTemplatePathRoot(template.Location, app) + "/", template.Path); // Throw Exception if Template does not exist if (!File.Exists(HostingEnvironment.MapPath(templatePath))) // todo: rendering exception throw new SexyContentException("The template file '" + templatePath + "' does not exist."); Template = template; TemplatePath = templatePath; App = app; ModuleInfo = hostingModule; DataSource = dataSource; InstancePurposes = instancePurposes; Sexy = sexy; // check common errors CheckExpectedTemplateErrors(); // check access permissions - before initializing or running data-code in the template CheckTemplatePermissions(sexy.AppPortalSettings); // Run engine-internal init stuff Init(); // call engine internal feature to optionally change what data is actually used or prepared for search... CustomizeData(); // check if rendering is possible, or throw exceptions... CheckExpectedNoRenderConditions(); if(PreRenderStatus == RenderStatusType.Unknown) PreRenderStatus = RenderStatusType.Ok; }
public static void InvokeTemplateSelected(TemplateProfile profile, Template oldTemplate) { if (profile != null && !profile.Deleted && OnTemplateSelected != null) { OnTemplateSelected(profile, oldTemplate); } }
public static void RunTest(string template, string expected, string errMsg) { string actual = new Template(template).Render(globals); actual = actual.Replace("{", "{{").Replace("}", "}}"); Assert.AreEqual(expected, actual, "{1} - {0}template: {2}{0}actual: {3}{0}expected: {4}", Environment.NewLine, errMsg, template, actual, expected); }
public void renders_the_template() { var theValue = TemplateValue.For("field", "FirstName"); var theTemplate = new Template(StringToken.FromKeyString("Test", "{field} is required"), theValue); theTemplate.Render().ShouldBe("FirstName is required"); }
public DefaultServerDetailLayoutOptions( ContextualizedHelpers helpers, IList<RowType> rows, IList<KeyValuePair<string, string>> toolbars, Template<LayoutTemplateOptions> layoutTemplate, IEnumerable<Template<LayoutTemplateOptions>> subTemplates, IHtmlContent mainContent, string id, string prefix, string cssClass, Type localizerType, bool editMode, string formAction, string formMethod, bool? antiforgery, bool noSubmit=false ) : base(rows, toolbars, layoutTemplate, subTemplates, mainContent) { this.helpers = helpers; Id = id; Prefix = prefix; CssClass = cssClass; LocalizerType = localizerType; Localizer = LocalizerType != null ? helpers.LocalizerFactory.Create(LocalizerType) : null; EditMode = editMode; Antiforgery = antiforgery; FormAction = formAction; FormMethod = formMethod; NoSubmit = noSubmit; }
/// <summary> /// Creates a new ReportAbstract, it used in children as base() when contructing. /// </summary> /// <param name="Filename">The output file's path</param> /// <param name="layout">The layout (list of columns) of the report.</param> /// <param name="ConfigParams">Misc configuration parameters vary for each ReportFormat</param> public ReportAbstract(Stream output, Layout layout, Template template, Dictionary<string, string> configParams) { m_Output = output; m_Layout = layout; m_Template = template; m_ConfigParams = configParams; }
public TemplateTreeNode(ProjectSchemaTreeNode parent, Template template) : base(parent) { this.Template = template; Initialize(); }
public DefaultServerGridLayoutOptions( ContextualizedHelpers helpers, IList<RowType> rows, IList<KeyValuePair<string, string>> toolbars, Template<LayoutTemplateOptions> layoutTemplate, IEnumerable<Template<LayoutTemplateOptions>> subTemplates, IHtmlContent mainContent, GridType type, string id, string prefix, GridErrorMessages messages, string cssClass, string caption, Type localizerType ) : base(rows, toolbars, layoutTemplate, subTemplates, mainContent) { this.helpers = helpers; Type = type; Messages = messages; Id = id; Prefix = prefix; CssClass = cssClass; Caption = caption; var first = rows.FirstOrDefault(); MustAddButtonColumn = first.MustAddButtonColumn(helpers, Type== GridType.Batch); VisibleColumns = first.VisibleColumns(helpers, Type == GridType.Batch); LocalizerType = localizerType; Localizer = LocalizerType != null ? helpers.LocalizerFactory.Create(LocalizerType) : null; }
// Guardar template actual private void SaveBtn_Click(object sender, EventArgs e) { var template = new Template() { Name = TemplateNameTxt.Text, Packages = PackageBoxTxt.Lines }; // Editando if (_selectedTemplate != null) { if (!ValidateTemplate(template, true)) return; var index = _templates.IndexOf(_selectedTemplate); _templates[index] = template; _selectedTemplate = template; } // Creando else { if (!ValidateTemplate(template)) return; _templates.Add(template); } _selectedTemplate = template; DeleteBtn.Enabled = true; LoadTemplateButtons(_templates); OptionsPage.TemplatesJson = JsonConvert.SerializeObject(_templates); }
public static void GenerateMain(string entryType, string entryNamespace, bool inputArgs) { StreamWriter writer = new StreamWriter(FileWritterManager.WorkingPath + "main.cpp"); string txt; Template template; string altTools = Environment.GetEnvironmentVariable("ALTERNATIVE_TOOLS_PATH"); if(altTools == null) altTools = Path.Combine(Environment.CurrentDirectory, (@"..\..\..\Tools").Replace('\\','/')); StreamReader sr = new StreamReader((altTools + @"\Templates\Code\main.stg").Replace('\\', '/')); txt = sr.ReadToEnd(); template = new Template(txt); StreamReader fs = new StreamReader(Path.Combine(altTools, "Text/notice")); string notice = fs.ReadToEnd(); template.Add("NOTICE", notice); template.Add("ENTRY_TYPE", entryType); template.Add("ENTRY_NAMESPACE_NEEDED", !String.IsNullOrEmpty(entryNamespace)); template.Add("ENTRY_NAMESPACE", entryNamespace); template.Add("INPUT_ARGS", inputArgs); string output = template.Render(); writer.Write(output); writer.Flush(); writer.Close(); FileWritterManager.AddSourceFile("main.cpp"); }
/// <inheritdoc/> public override void OnApplyTemplate() { base.OnApplyTemplate(); searchTextBox = Template.FindName("PART_searchTextBox", this) as TextBox; }
/// <summary> /// Gets a list of all templates in the database, excluding the specified template. /// </summary> /// <param name="excludeTemplate">The template instance that should not be returned as part of the list</param> public static List <LookupTemplate> GetTemplatesExcluding(Template excludeTemplate) { return(GetTemplatesExcluding(excludeTemplate.Id)); }
public TemplateManager(DataGridViewRow row, Template template, string lastTestFile, string testFileDefaultFolder) : base(template, lastTestFile, testFileDefaultFolder) { Row = row; }
/// <summary> /// Method that will be run at Rock startup /// </summary> public override void OnStartup() { Template.RegisterShortcode <Scripturize>("scripturize"); }
public void BuildDoorTemplateAboveFloorTest() { Template testTemplate = new Template("TEST", 2, 1, 1.9F, ComponentType.DOOR); }
/// <summary> /// When overridden in a derived class, is invoked whenever application code or internal processes call <see cref="M:System.Windows.FrameworkElement.ApplyTemplate"/>. /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); minimizeButton = (Button)Template.FindName("MinimizeButton", this); maximizeButton = (Button)Template.FindName("MaximizeButton", this); closeButton = (Button)Template.FindName("CloseButton", this); buttonsPanel = (StackPanel)Template.FindName("ButtonsPanel", this); if (minimizeButton != null) { minimizeButton.Click += minimizeButton_Click; } if (maximizeButton != null) { maximizeButton.Click += maximizeButton_Click; } if (closeButton != null) { closeButton.Click += closeButton_Click; } Thumb dragThumb = (Thumb)Template.FindName("DragThumb", this); if (dragThumb != null) { dragThumb.DragStarted += Thumb_DragStarted; dragThumb.DragDelta += dragThumb_DragDelta; dragThumb.MouseDoubleClick += (sender, e) => { if (WindowState == WindowState.Minimized) { minimizeButton_Click(null, null); } else if (WindowState == WindowState.Normal) { maximizeButton_Click(null, null); } }; } Thumb resizeLeft = (Thumb)Template.FindName("ResizeLeft", this); Thumb resizeTopLeft = (Thumb)Template.FindName("ResizeTopLeft", this); Thumb resizeTop = (Thumb)Template.FindName("ResizeTop", this); Thumb resizeTopRight = (Thumb)Template.FindName("ResizeTopRight", this); Thumb resizeRight = (Thumb)Template.FindName("ResizeRight", this); Thumb resizeBottomRight = (Thumb)Template.FindName("ResizeBottomRight", this); Thumb resizeBottom = (Thumb)Template.FindName("ResizeBottom", this); Thumb resizeBottomLeft = (Thumb)Template.FindName("ResizeBottomLeft", this); if (resizeLeft != null) { resizeLeft.DragStarted += Thumb_DragStarted; resizeLeft.DragDelta += ResizeLeft_DragDelta; } if (resizeTop != null) { resizeTop.DragStarted += Thumb_DragStarted; resizeTop.DragDelta += ResizeTop_DragDelta; } if (resizeRight != null) { resizeRight.DragStarted += Thumb_DragStarted; resizeRight.DragDelta += ResizeRight_DragDelta; } if (resizeBottom != null) { resizeBottom.DragStarted += Thumb_DragStarted; resizeBottom.DragDelta += ResizeBottom_DragDelta; } if (resizeTopLeft != null) { resizeTopLeft.DragStarted += Thumb_DragStarted; resizeTopLeft.DragDelta += (sender, e) => { ResizeTop_DragDelta(null, e); ResizeLeft_DragDelta(null, e); Container.InvalidateSize(); }; } if (resizeTopRight != null) { resizeTopRight.DragStarted += Thumb_DragStarted; resizeTopRight.DragDelta += (sender, e) => { ResizeTop_DragDelta(null, e); ResizeRight_DragDelta(null, e); Container.InvalidateSize(); }; } if (resizeBottomRight != null) { resizeBottomRight.DragStarted += Thumb_DragStarted; resizeBottomRight.DragDelta += (sender, e) => { ResizeBottom_DragDelta(null, e); ResizeRight_DragDelta(null, e); Container.InvalidateSize(); }; } if (resizeBottomLeft != null) { resizeBottomLeft.DragStarted += Thumb_DragStarted; resizeBottomLeft.DragDelta += (sender, e) => { ResizeBottom_DragDelta(null, e); ResizeLeft_DragDelta(null, e); Container.InvalidateSize(); }; } MinimizeBoxValueChanged(this, new DependencyPropertyChangedEventArgs(MinimizeBoxProperty, true, MinimizeBox)); MaximizeBoxValueChanged(this, new DependencyPropertyChangedEventArgs(MaximizeBoxProperty, true, MaximizeBox)); CloseBoxValueChanged(this, new DependencyPropertyChangedEventArgs(CloseBoxProperty, true, CloseBox)); }
public async Task <IActionResult> Edit(string sourceName, TemplateViewModel model, string submit, string returnUrl = null) { if (!model.AdminTemplates && !await _authorizationService.AuthorizeAsync(User, Permissions.ManageTemplates)) { return(Forbid()); } if (model.AdminTemplates && !await _authorizationService.AuthorizeAsync(User, AdminTemplatesPermissions.ManageAdminTemplates)) { return(Forbid()); } var templatesDocument = model.AdminTemplates ? await _adminTemplatesManager.LoadTemplatesDocumentAsync() : await _templatesManager.LoadTemplatesDocumentAsync() ; if (ModelState.IsValid) { if (String.IsNullOrWhiteSpace(model.Name)) { ModelState.AddModelError(nameof(TemplateViewModel.Name), S["The name is mandatory."]); } else if (!model.Name.Equals(sourceName, StringComparison.OrdinalIgnoreCase) && templatesDocument.Templates.ContainsKey(model.Name)) { ModelState.AddModelError(nameof(TemplateViewModel.Name), S["A template with the same name already exists."]); } else if (String.IsNullOrWhiteSpace(model.Content)) { ModelState.AddModelError(nameof(TemplateViewModel.Content), S["The content is mandatory."]); } } if (!templatesDocument.Templates.ContainsKey(sourceName)) { return(NotFound()); } if (ModelState.IsValid) { var template = new Template { Content = model.Content, Description = model.Description }; await(model.AdminTemplates ? _adminTemplatesManager.RemoveTemplateAsync(sourceName) : _templatesManager.RemoveTemplateAsync(sourceName) ); await(model.AdminTemplates ? _adminTemplatesManager.UpdateTemplateAsync(model.Name, template) : _templatesManager.UpdateTemplateAsync(model.Name, template) ); if (submit != "SaveAndContinue") { return(RedirectToReturnUrlOrIndex(returnUrl)); } } // If we got this far, something failed, redisplay form ViewData["ReturnUrl"] = returnUrl; return(View(model)); }
void BGW_DoWork(object sender, DoWorkEventArgs e) { //開始列印學生清單 #region 資料整理 //取得需連線學校 LoginSchoolList = tool._A.Select <LoginSchool>(); // 取得社團老師資料 key : DSNS Dictionary <string, ClubTeacher> clubTeacherDic = new Dictionary <string, ClubTeacher>(); // 2018/01/23 羿均 新增 取得學校相關資料 SchoolClubDic = tool.SchoolClubDetail(LoginSchoolList); foreach (AcrossRecord Across in SchoolClubDic.Values) { foreach (OnlineClub club in Across.ClubDic.Values) { if (!Mergerdic.ContainsKey(club.ClubName)) { OnlineMergerClub Mclub = new OnlineMergerClub(tool.Point); Mergerdic.Add(club.ClubName, Mclub); Mclub.AddClub(club); } Mergerdic[club.ClubName].AddClub(club); } } //選擇了哪些社團(使用名稱進行比對) List <string> ClubIDList = K12.Club.Volunteer.ClubAdmin.Instance.SelectedSource; List <CLUBRecord> ClubRecordList = tool._A.Select <CLUBRecord>(ClubIDList); //社團名稱清單 List <string> ClubNameList = new List <string>(); foreach (CLUBRecord club in ClubRecordList) { ClubNameList.Add(club.ClubName); } //社團名稱 + 社團參與記錄學生 Dictionary <string, List <OnlineSCJoin> > dic = new Dictionary <string, List <OnlineSCJoin> >(); List <string> ClubNewNameList = new List <string>(); foreach (LoginSchool school in LoginSchoolList) { schoolMark = school.Remark; Connection me = new Connection(); me.Connect(school.School_Name, tool._contract, FISCA.Authentication.DSAServices.PassportToken); Dictionary <string, OnlineSCJoin> ScjList = RunService.GetSCJoinByClubName(me, ClubNameList); foreach (OnlineSCJoin each in ScjList.Values) { // 2018/01/24 羿均 紀錄:主要連線學校社團老師 if (school.School_Name == tool.Point) { if (!clubTeacherDic.ContainsKey(school.School_Name)) { ClubTeacher ct = new ClubTeacher(); ct.SchoolName = school.School_Name; ct.Teacher1 = each.TeacherName; ct.Teacher2 = each.TeacherName2; ct.Teacher3 = each.TeacherName3; clubTeacherDic.Add(school.School_Name, ct); } } string name = each.ClubName; if (!dic.ContainsKey(name)) { dic.Add(name, new List <OnlineSCJoin>()); ClubNewNameList.Add(name); } // 2018/01/23 羿均 新增部別欄位 each.SchoolReMark = school.Remark; dic[name].Add(each); } } ClubNewNameList.Sort(); #endregion #region 報表範本整理 Campus.Report.ReportConfiguration ConfigurationInCadre = new Campus.Report.ReportConfiguration(ConfigName); Aspose.Words.Document Template; if (ConfigurationInCadre.Template == null) { //如果範本為空,則建立一個預設範本 Campus.Report.ReportConfiguration ConfigurationInCadre_1 = new Campus.Report.ReportConfiguration(ConfigName); ConfigurationInCadre_1.Template = new Campus.Report.ReportTemplate(Properties.Resources.社團點名單_週報表樣式範本, Campus.Report.TemplateType.Word); Template = ConfigurationInCadre_1.Template.ToDocument(); } else { //如果已有範本,則取得樣板 Template = ConfigurationInCadre.Template.ToDocument(); } #endregion #region 範本再修改 List <string> config = new List <string>(); XmlElement day = (XmlElement)e.Argument; if (day == null) { MsgBox.Show("第一次使用報表請先進行[日期設定]"); return; } else { config.Clear(); foreach (XmlElement xml in day.SelectNodes("item")) { config.Add(xml.InnerText); } } SCJoinDataLoad scjoinData = new SCJoinDataLoad(); DataTable table = new DataTable(); table.Columns.Add("學校名稱"); table.Columns.Add("社團名稱"); table.Columns.Add("學年度"); table.Columns.Add("學期"); table.Columns.Add("上課地點"); table.Columns.Add("社團類型"); table.Columns.Add("社團代碼"); //table.Columns.Add("社團老師"); table.Columns.Add("社團老師1"); table.Columns.Add("社團老師2"); table.Columns.Add("社團老師3"); table.Columns.Add("列印日期"); table.Columns.Add("上課開始"); table.Columns.Add("上課結束"); table.Columns.Add("人數"); for (int x = 1; x <= 日期多少天; x++) { table.Columns.Add(string.Format("日期_{0}", x)); } for (int x = 1; x <= 學生多少個; x++) { table.Columns.Add(string.Format("社團_{0}", x)); } for (int x = 1; x <= 學生多少個; x++) { table.Columns.Add(string.Format("部別名稱_{0}", x)); } for (int x = 1; x <= 學生多少個; x++) { table.Columns.Add(string.Format("班級_{0}", x)); } for (int x = 1; x <= 學生多少個; x++) { table.Columns.Add(string.Format("座號_{0}", x)); } for (int x = 1; x <= 學生多少個; x++) { table.Columns.Add(string.Format("姓名_{0}", x)); } for (int x = 1; x <= 學生多少個; x++) { table.Columns.Add(string.Format("學號_{0}", x)); } for (int x = 1; x <= 學生多少個; x++) { table.Columns.Add(string.Format("性別_{0}", x)); } #endregion foreach (string each in scjoinData.CLUBRecordDic.Keys) { //社團資料 CLUBRecord cr = scjoinData.CLUBRecordDic[each]; } foreach (string each in ClubNewNameList) { DataRow row = table.NewRow(); row["學校名稱"] = K12.Data.School.ChineseName; row["學年度"] = School.DefaultSchoolYear; row["學期"] = School.DefaultSemester; row["列印日期"] = DateTime.Today.ToShortDateString(); row["上課開始"] = config[0]; row["上課結束"] = config[config.Count - 1]; row["社團名稱"] = each; // 2018/01/23 羿均 新增合併欄位: row["上課地點"] = Mergerdic[each].Location; row["社團類型"] = Mergerdic[each].ClubCategory; row["社團代碼"] = Mergerdic[each].ClubNumber; row["社團老師1"] = clubTeacherDic[tool.Point].Teacher1; row["社團老師2"] = clubTeacherDic[tool.Point].Teacher2; row["社團老師3"] = clubTeacherDic[tool.Point].Teacher3; //特殊 //if (dic[each].Count > 0) //row["社團老師"] = dic[each][0].TeacherName; for (int x = 1; x <= config.Count; x++) { row[string.Format("日期_{0}", x)] = config[x - 1]; } dic[each].Sort(SortStudentSCJoin); int y = 1; foreach (OnlineSCJoin scjoin in dic[each]) { if (y <= 學生多少個) { row[string.Format("部別名稱_{0}", y)] = scjoin.SchoolReMark; row[string.Format("班級_{0}", y)] = scjoin.ClassName; row[string.Format("座號_{0}", y)] = scjoin.SeatNo; row[string.Format("姓名_{0}", y)] = scjoin.StudentName; row[string.Format("學號_{0}", y)] = scjoin.StudentNumber; row[string.Format("性別_{0}", y)] = scjoin.Gender; y++; } } row["人數"] = y - 1; table.Rows.Add(row); } Document PageOne = (Document)Template.Clone(true); PageOne.MailMerge.Execute(table); e.Result = PageOne; }
protected override SyncAttempt <ITemplate> DeserializeCore(XElement node, SyncSerializerOptions options) { var key = node.GetKey(); var alias = node.GetAlias(); var name = node.Element("Name").ValueOrDefault(string.Empty); var item = default(ITemplate); var details = new List <uSyncChange>(); if (key != Guid.Empty) { item = fileService.GetTemplate(key); } if (item == null) { item = fileService.GetTemplate(alias); } if (item == null) { item = new Template(shortStringHelper, name, alias); details.AddNew(alias, alias, "Template"); if (ShouldGetContentFromNode(node, options)) { logger.LogDebug("Getting content for Template from XML"); item.Content = GetContentFromConfig(node); } else { logger.LogDebug("Loading template content from disk"); var templatePath = ViewPath(alias); if (_viewFileSystem.FileExists(templatePath)) { logger.LogDebug("Reading {0} contents", templatePath); item.Content = GetContentFromFile(templatePath); item.Path = templatePath; } else { if (!options.GetSetting <bool>("UsingRazorViews", false)) { // template is missing // we can't create logger.LogWarning("Failed to create template {path} the local file is missing", templatePath); return(SyncAttempt <ITemplate> .Fail(name, ChangeType.Import, $"The template {templatePath} file is missing.")); } else { // template is not on disk, we could use the viewEngine to find the view // if this finds the view it tells us that the view is somewhere else ? logger.LogDebug("Failed to find content, but UsingRazorViews so will create anyway, then delete the file"); item.Content = $"<!-- [uSyncMarker:{this.Id}] template content - will be removed -->"; } } } } if (item == null) { // creating went wrong logger.LogWarning("Failed to create template"); return(SyncAttempt <ITemplate> .Fail(name, ChangeType.Import, "Failed to create template")); } if (item.Key != key) { details.AddUpdate("Key", item.Key, key); item.Key = key; } if (item.Name != name) { details.AddUpdate("Name", item.Name, name); item.Name = name; } if (item.Alias != alias) { details.AddUpdate("Alias", item.Alias, alias); item.Alias = alias; } if (ShouldGetContentFromNode(node, options)) { var content = GetContentFromConfig(node); if (content != item.Content) { details.AddUpdate("Content", item.Content, content); item.Content = content; } } //var master = node.Element("Parent").ValueOrDefault(string.Empty); //if (master != string.Empty) //{ // var masterItem = fileService.GetTemplate(master); // if (masterItem != null) // item.SetMasterTemplate(masterItem); //} // Deserialize now takes care of the save. // fileService.SaveTemplate(item); return(SyncAttempt <ITemplate> .Succeed(item.Name, item, ChangeType.Import, details)); }
public TemplateBuilder(string name, string templateId) { this.template = new Template(name, templateId); }
private async Task <IActionResult> SetTemplateDetails(TemplateVersion templateVersion, Template template, VersionCreateInputModel model) { long? preprocessGitId = null; string preprocessRepository = null; string preprocessOwner = null; string preprocessBranch = null; string preprocessCommitId = null; string preprocessGitToken = null; long trainingGitId = 0; string trainingRepository = null; string trainingOwner = null; string trainingBranch = null; string trainingCommitId = null; string trainingGitToken = null; long? evaluationGitId = null; string evaluationRepository = null; string evaluationOwner = null; string evaluationBranch = null; string evaluationCommitId = null; string evaluationGitToken = null; if (model.PreprocessGitModel != null) { preprocessGitId = model.PreprocessGitModel.GitId ?? CurrentUserInfo.SelectedTenant.DefaultGit?.Id; preprocessRepository = model.PreprocessGitModel.Repository; preprocessOwner = model.PreprocessGitModel.Owner; preprocessBranch = model.PreprocessGitModel.Branch; preprocessCommitId = model.PreprocessGitModel.CommitId; // コミットIDが指定されていなければ、ブランチのHEADからコミットIDを取得する if (string.IsNullOrEmpty(preprocessCommitId)) { preprocessCommitId = await gitLogic.GetCommitIdAsync(preprocessGitId.Value, model.PreprocessGitModel.Repository, model.PreprocessGitModel.Owner, model.PreprocessGitModel.Branch); if (string.IsNullOrEmpty(preprocessCommitId)) { // コミットIDが特定できなかったらエラー return(JsonNotFound($"The branch {preprocessBranch} for {preprocessGitId.Value}/{model.PreprocessGitModel.Owner}/{ model.PreprocessGitModel.Repository} is not found.")); } } preprocessGitToken = model.PreprocessGitModel.Token; } if (model.TrainingGitModel != null) { trainingGitId = (model.TrainingGitModel.GitId ?? CurrentUserInfo.SelectedTenant.DefaultGit?.Id).Value; trainingRepository = model.TrainingGitModel.Repository; trainingOwner = model.TrainingGitModel.Owner; trainingBranch = model.TrainingGitModel.Branch; trainingCommitId = model.TrainingGitModel.CommitId; // コミットIDが指定されていなければ、ブランチのHEADからコミットIDを取得する if (string.IsNullOrEmpty(trainingCommitId)) { trainingCommitId = await gitLogic.GetCommitIdAsync(trainingGitId, model.TrainingGitModel.Repository, model.TrainingGitModel.Owner, model.TrainingGitModel.Branch); if (string.IsNullOrEmpty(trainingCommitId)) { // コミットIDが特定できなかったらエラー return(JsonNotFound($"The branch {trainingBranch} for {trainingGitId}/{model.TrainingGitModel.Owner}/{ model.TrainingGitModel.Repository} is not found.")); } } trainingGitToken = model.TrainingGitModel.Token; } if (model.EvaluationGitModel != null) { evaluationGitId = (model.EvaluationGitModel.GitId ?? CurrentUserInfo.SelectedTenant.DefaultGit?.Id).Value; evaluationRepository = model.EvaluationGitModel.Repository; evaluationOwner = model.EvaluationGitModel.Owner; evaluationBranch = model.EvaluationGitModel.Branch; evaluationCommitId = model.EvaluationGitModel.CommitId; // コミットIDが指定されていなければ、ブランチのHEADからコミットIDを取得する if (string.IsNullOrEmpty(evaluationCommitId)) { evaluationCommitId = await gitLogic.GetCommitIdAsync(evaluationGitId.Value, model.EvaluationGitModel.Repository, model.EvaluationGitModel.Owner, model.EvaluationGitModel.Branch); if (string.IsNullOrEmpty(evaluationCommitId)) { // コミットIDが特定できなかったらエラー return(JsonNotFound($"The branch {evaluationBranch} for {evaluationGitId}/{model.EvaluationGitModel.Owner}/{ model.EvaluationGitModel.Repository} is not found.")); } } evaluationGitToken = model.EvaluationGitModel.Token; } long? preprocessRegistryId = null; string preprocessImage = null; string preprocessTag = null; string preprocessRegistryToken = null; if (model.PreprocessContainerImage != null) { preprocessRegistryId = model.PreprocessContainerImage.RegistryId ?? CurrentUserInfo.SelectedTenant.DefaultRegistry?.Id; preprocessImage = model.PreprocessContainerImage.Image; preprocessTag = model.PreprocessContainerImage.Tag; preprocessRegistryToken = model.PreprocessContainerImage.Token; } long trainingRegistryId = 0; string trainingImage = null; string trainingTag = null; string trainingRegistryToken = null; if (model.TrainingContainerImage != null) { trainingRegistryId = (model.TrainingContainerImage.RegistryId ?? CurrentUserInfo.SelectedTenant.DefaultRegistry?.Id).Value; trainingImage = model.TrainingContainerImage.Image; trainingTag = model.TrainingContainerImage.Tag; trainingRegistryToken = model.TrainingContainerImage.Token; } long? evaluationRegistryId = null; string evaluationImage = null; string evaluationTag = null; string evaluationRegistryToken = null; if (model.EvaluationContainerImage != null) { evaluationRegistryId = (model.EvaluationContainerImage.RegistryId ?? CurrentUserInfo.SelectedTenant.DefaultRegistry?.Id).Value; evaluationImage = model.EvaluationContainerImage.Image; evaluationTag = model.EvaluationContainerImage.Tag; evaluationRegistryToken = model.EvaluationContainerImage.Token; } templateVersion.TemplateId = template.Id; templateVersion.Version = template.LatestVersion; templateVersion.PreprocessEntryPoint = model.PreprocessEntryPoint; templateVersion.PreprocessContainerRegistryId = preprocessRegistryId; templateVersion.PreprocessContainerImage = preprocessImage; templateVersion.PreprocessContainerTag = preprocessTag; // latestは運用上使用されていないハズなので、そのまま直接代入 templateVersion.PreprocessContainerToken = preprocessRegistryToken; templateVersion.PreprocessRepositoryGitId = preprocessGitId; templateVersion.PreprocessRepositoryName = preprocessRepository; templateVersion.PreprocessRepositoryOwner = preprocessOwner; templateVersion.PreprocessRepositoryBranch = preprocessBranch; templateVersion.PreprocessRepositoryCommitId = preprocessCommitId; templateVersion.PreprocessRepositoryToken = preprocessGitToken; templateVersion.PreprocessCpu = model.PreprocessCpu; templateVersion.PreprocessMemory = model.PreprocessMemory; templateVersion.PreprocessGpu = model.PreprocessGpu; templateVersion.TrainingEntryPoint = model.TrainingEntryPoint; templateVersion.TrainingContainerRegistryId = trainingRegistryId; templateVersion.TrainingContainerImage = trainingImage; templateVersion.TrainingContainerTag = trainingTag; // latestは運用上使用されていないハズなので、そのまま直接代入 templateVersion.TrainingContainerToken = trainingRegistryToken; templateVersion.TrainingRepositoryGitId = trainingGitId; templateVersion.TrainingRepositoryName = trainingRepository; templateVersion.TrainingRepositoryOwner = trainingOwner; templateVersion.TrainingRepositoryBranch = trainingBranch; templateVersion.TrainingRepositoryCommitId = trainingCommitId; templateVersion.TrainingRepositoryToken = trainingGitToken; templateVersion.TrainingCpu = model.TrainingCpu; templateVersion.TrainingMemory = model.TrainingMemory; templateVersion.TrainingGpu = model.TrainingGpu; templateVersion.EvaluationEntryPoint = model.EvaluationEntryPoint; templateVersion.EvaluationContainerRegistryId = evaluationRegistryId; templateVersion.EvaluationContainerImage = evaluationImage; templateVersion.EvaluationContainerTag = evaluationTag; // latestは運用上使用されていないハズなので、そのまま直接代入 templateVersion.EvaluationContainerToken = evaluationRegistryToken; templateVersion.EvaluationRepositoryGitId = evaluationGitId; templateVersion.EvaluationRepositoryName = evaluationRepository; templateVersion.EvaluationRepositoryOwner = evaluationOwner; templateVersion.EvaluationRepositoryBranch = evaluationBranch; templateVersion.EvaluationRepositoryCommitId = evaluationCommitId; templateVersion.EvaluationRepositoryToken = evaluationGitToken; templateVersion.EvaluationCpu = model.EvaluationCpu; templateVersion.EvaluationMemory = model.EvaluationMemory; templateVersion.EvaluationGpu = model.EvaluationGpu; return(null); }
static LiquidTemplate() { Template.RegisterTag <TemplateTag>(TemplateTagName); }
public TemplateRenderer(Template <T> template) : base(template as ITemplate) { }
public void BuildZeroLengthTemplateTest() { Template testTemplate = new Template("TEST", 0, 2, 2, ComponentType.WINDOW); }
private async Task GenerateClientSideCode(CodeModelCs codeModel) { CompositeTypeCs.DefaultPropertyTypeSelectionStrategy = new WrappedPropertyTypeSelectionStrategy(); var usings = new List <string>(); var methodGroups = codeModel.Operations.Cast <MethodGroupCs>(); var methods = codeModel.Methods.Where(m => m.Group.IsNullOrEmpty()).Cast <MethodCs>().ToList(); var project = new ProjectModel { RootNameSpace = codeModel.Namespace }; var metricsTemplate = new MetricsTemplate { Model = methods }; var metricsFilePath = "Metrics.cs"; await Write(metricsTemplate, metricsFilePath); var brokenRuleTemplate = new BrokenRuleTemplate(); var brokenRuleFilePath = "BrokenRule.cs"; await Write(brokenRuleTemplate, brokenRuleFilePath); var responseTemplate = new ResponseTemplate(); var responseFilePath = "Response.cs"; await Write(responseTemplate, responseFilePath); usings.AddRange(new[] { "System", "System.Collections.Generic", "System.Linq", "System.Threading", "System.Threading.Tasks", "Microsoft.Rest", "System.IO", "Microsoft.Rest.Serialization", "Agoda.RoundRobin", "Newtonsoft.Json", $"{codeModel.Namespace}.Models", "Agoda.RoundRobin.Constants", "System.ComponentModel", "AutoRest.CSharp.LoadBalanced.Json" }); usings = usings.Where(u => !string.IsNullOrWhiteSpace(u)).Distinct().ToList(); codeModel.Usings = usings; var clients = methods.GroupBy(m => m.Tags.First()).ToArray(); var libPath = Path.Combine(Settings.Instance.OutputDirectory, "lib"); await new LibFolderCreator(libPath).ExecuteAsync(); foreach (var client in clients) { var clientName = $"{client.Key.ToPascalCase()}Client"; var clientMethods = client.ToArray(); var clientClassFileName = $"{clientName}{ImplementationFileExtension}"; var clientInterfaceFileName = $"I{clientClassFileName}"; var model = new Tuple <CodeModelCs, string, MethodCs[]>(codeModel, clientName, clientMethods); // Service client interface var serviceClientInterfaceTemplate = new ServiceClientInterfaceTemplate { Model = model }; await Write(serviceClientInterfaceTemplate, clientInterfaceFileName); // Service client var serviceClientTemplate = new ServiceClientTemplate { Model = model }; await Write(serviceClientTemplate, clientClassFileName); } var apiBaseTemplate = new ApiBaseTemplate { Model = codeModel }; var apiBaseCsPath = "ApiBase.cs"; await Write(apiBaseTemplate, apiBaseCsPath); var badRequestExceptionTemplate = new BadRequestExceptionTemplate(); var badRequestPath = "BadRequestException.cs"; await Write(badRequestExceptionTemplate, badRequestPath); // operations foreach (var methodGroup in methodGroups) { if (methodGroup.Name.IsNullOrEmpty()) { continue; } // Operation var operationsTemplate = new MethodGroupTemplate { Model = methodGroup }; var operationsFilePath = $"{operationsTemplate.Model.TypeName}{ImplementationFileExtension}"; await Write(operationsTemplate, operationsFilePath); // Operation interface var operationsInterfaceTemplate = new MethodGroupInterfaceTemplate { Model = methodGroup }; var operationsInterfacePath = $"I{operationsInterfaceTemplate.Model.TypeName}{ImplementationFileExtension}"; await Write(operationsInterfaceTemplate, operationsInterfacePath); } // Models var models = codeModel.ModelTypes.Union(codeModel.HeaderTypes).Cast <CompositeTypeCs>(); foreach (var model in models) { if (model.Extensions.ContainsKey(SwaggerExtensions.ExternalExtension) && (bool)model.Extensions[SwaggerExtensions.ExternalExtension]) { continue; } Template <CompositeTypeCs> modelTemplate = null; if (model.PropertyTypeSelectionStrategy.IsCollection(model)) { modelTemplate = new CollectionModelTemplate { Model = model }; } else { modelTemplate = new ModelTemplate { Model = model }; } var modelPath = Path.Combine(Settings.Instance.ModelsName, $"{model.Name}{ImplementationFileExtension}"); await Write(modelTemplate, modelPath); } // Enums foreach (EnumTypeCs enumType in codeModel.EnumTypes) { var enumTemplate = new EnumTemplate { Model = enumType }; var enumFilePath = Path.Combine(Settings.Instance.ModelsName, $"{enumTemplate.Model.Name}{ImplementationFileExtension}"); await Write(enumTemplate, enumFilePath); } // Exceptions foreach (CompositeTypeCs exceptionType in codeModel.ErrorTypes) { var exceptionTemplate = new ExceptionTemplate { Model = exceptionType, }; var exceptionFilePath = Path.Combine(Settings.Instance.ModelsName, $"{exceptionTemplate.Model.ExceptionTypeDefinitionName}{ImplementationFileExtension}"); await Write(exceptionTemplate, exceptionFilePath); } // CB models var couchbaseModels = codeModel.ModelTypes.Union(codeModel.HeaderTypes).Cast <CompositeTypeCs>(); foreach (var model in couchbaseModels) { model.isCouchbaseModel = true; if (model.Extensions.ContainsKey(SwaggerExtensions.ExternalExtension) && (bool)model.Extensions[SwaggerExtensions.ExternalExtension]) { continue; } Template <CompositeTypeCs> modelTemplate = null; if (model.PropertyTypeSelectionStrategy.IsCollection(model)) { modelTemplate = new CollectionModelTemplate { Model = model }; } else { modelTemplate = new ModelTemplate { Model = model }; } var modelPath = Path.Combine(Settings.Instance.ModelsName, $"Couchbase/{model.Name}{ImplementationFileExtension}"); project.FilePaths.Add(modelPath); await Write(modelTemplate, modelPath); } }
public void BuildInvalidLengthTemplateTest() { Template testTemplate = new Template("TEST", 4, 0, 3, ComponentType.DOOR); }
public void BuildOutOfWallTemplateTest() { Template testTemplate = new Template("TEST", 2, 2, 2, ComponentType.WINDOW); }
public void BuildNegativeLengthTemplateTest() { Template testTemplate = new Template("TEST", -2, 2, 2, ComponentType.WINDOW); }
public void BuildEmptyNameTemplateTest() { Template testTemplate = new Template("", 1, 1, 1, ComponentType.WINDOW); }
public void BuildNegativeHeightAboveFloorTemplateTest() { Template testTemplate = new Template("TEST", 2, -1, 2, ComponentType.WINDOW); }
public void BuildHeigherThanWallTemplateTest() { Template testTemplate = new Template("TEST", 2, 0, 5, ComponentType.DOOR); }
public void BuildNegativeHeightTemplateTest() { Template testTemplate = new Template("TEST", 2, 0, -2, ComponentType.DOOR); }
static void Main(string[] args) { System.Data.DataTable dataTable = new System.Data.DataTable(); dataTable.Columns.Add("Column1"); dataTable.Columns.Add("Column2"); System.Data.DataRow dataRow = dataTable.NewRow(); dataRow["Column1"] = "Hello"; dataRow["Column2"] = "World"; dataTable.Rows.Add(dataRow); dataRow = dataTable.NewRow(); dataRow["Column1"] = "Bonjour"; dataRow["Column2"] = "le monde"; dataTable.Rows.Add(dataRow); string json = JsonConvert.SerializeObject(dataTable); Console.WriteLine("Json: " + json); var parsed = JsonConvert.DeserializeObject(json); Console.WriteLine("Parsed: " + parsed); string myTemplate = @" [ { {{ for tbr in tb }} ""N"": {{tbr.Column1}}, ""M"": {{tbr.Column2}} {{ end }} }, ] {{tb}} "; { var template = Template.Parse(myTemplate); //var result = template.Render(new {tb = parsed}); //Console.WriteLine(result); var context = new TemplateContext(); context.MemberRenamer = name => name; var scriptObject = new ScriptObject(); scriptObject.Import(new { tb = parsed }); context.PushGlobal(scriptObject); template.Render(context); Console.WriteLine(context.Output.ToString()); } { var a1 = new Author { Name = "John" }; var b = new Book[2]; b[0] = new Book { Title = "Book1", Author = a1 }; b[1] = new Book { Title = "Book2", Author = a1 }; var globalFunction = new ScriptObject(); var template = Template.Parse(@"This {{books[0].Title}} {{ ""is"" | string.upcase }} from scriban!"); var model = new { books = b }; var context = new TemplateContext(); context.MemberRenamer = name => name; context.PushGlobal(globalFunction); var localFunction = new ScriptObject(); localFunction.Import(model); context.PushGlobal(localFunction); template.Render(context); context.PopGlobal(); } }
public void BuildInvalidTypeTemplate() { Template testTemplate = new Template("TEST", 2, 0, 2, ComponentType.WALL); }
public ExcelTemplate(Template template) : base(template.ID, template.Name, template.Entity, template.FileName, template.Content, template.Fields) { }
/// <summary> /// Render template by content and parameters /// </summary> /// <param name="templateContent"></param> /// <param name="parameters"></param> /// <returns></returns> public ValueTask <string> RenderTemplateAsync(string templateContent, string templatePath, object context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (!(context is IScriptObject scriptObject)) { throw new StorefrontException($"{ nameof(context) } must implement IScriptObject"); } if (string.IsNullOrEmpty(templateContent)) { return(new ValueTask <string>(templateContent)); } var isLiquidTemplate = _isLiquid.Match(templateContent); if (!isLiquidTemplate.Success) { return(new ValueTask <string>(templateContent)); } //TODO: Handle _options.RethrowLiquidRenderErrors var cacheKey = CacheKey.With(GetType(), "ParseTemplate", templatePath ?? templateContent); var parsedTemplate = _memoryCache.GetOrCreate(cacheKey, (cacheItem) => { if (!string.IsNullOrEmpty(templatePath)) { cacheItem.AddExpirationToken(new CompositeChangeToken(new[] { ThemeEngineCacheRegion.CreateChangeToken(), _themeBlobProvider.Watch(templatePath) })); } else { cacheItem.AddExpirationToken(ThemeEngineCacheRegion.CreateChangeToken()); } return(Template.ParseLiquid(templateContent, templatePath)); }); if (parsedTemplate.HasErrors) { throw new InvalidOperationException(string.Join("\n", parsedTemplate.Messages)); } var templateContext = new TemplateContext() { TemplateLoader = this, EnableRelaxedMemberAccess = true, NewLine = Environment.NewLine, TemplateLoaderLexerOptions = new LexerOptions { Mode = ScriptMode.Liquid } }; templateContext.PushGlobal(scriptObject); var result = parsedTemplate.Render(templateContext); return(new ValueTask <string>(result)); }
private void Nouveau() { int i = 1; string originalName = ""; switch (CurrentType) { case DBItemType.Template: ManagedItem = Template.NewTemplate(); originalName = ManagedItem.Name; while (true) { if (ListTemplates.Any(t => t.Nom == ManagedItem.Name) || ListTemplates.Any(t => t.Nom == ManagedItem.Name + " (" + i + ")")) { ((Template)ManagedItem).Nom = originalName + " (" + i + ")"; i++; } else { break; } } FirePropertyChanged("ManagedItem"); ListTemplates.Add((Template)ManagedItem); break; case DBItemType.Macro: ManagedItem = Macro.newMacro(); originalName = ManagedItem.Name; while (true) { if (ListMacros.Any(t => t.Nom == ManagedItem.Name) || ListMacros.Any(t => t.Nom == ManagedItem.Name + " (" + i + ")")) { ((Macro)ManagedItem).Nom = originalName + " (" + i + ")"; i++; } else { break; } } ListMacros.Add((Macro)ManagedItem); break; case DBItemType.Meta: ManagedItem = Meta.newMeta(); originalName = ManagedItem.Name; while (true) { if (ListMetas.Any(t => t.Nom == ManagedItem.Name) || ListMetas.Any(t => t.Nom == ManagedItem.Name + " (" + i + ")")) { ((Meta)ManagedItem).Nom = originalName + " (" + i + ")"; i++; } else { break; } } ListMetas.Add((Meta)ManagedItem); break; case DBItemType.Environment: ManagedItem = LTG_Entity.Environment.newEnvironment(); originalName = ManagedItem.Name; while (true) { if (ListEnvironments.Any(t => t.Nom == ManagedItem.Name) || ListEnvironments.Any(t => t.Nom == ManagedItem.Name + " (" + i + ")")) { ((LTG_Entity.Environment)ManagedItem).Nom = originalName + " (" + i + ")"; i++; } else { break; } } ListEnvironments.Add((LTG_Entity.Environment)ManagedItem); break; default: break; } ManagedList.Add(ManagedItem); try { SaveDB(); //_dialogCoordinator.ShowMessageAsync(this, "Information", "les articles ont été sauvés"); } catch (Exception e) { Console.WriteLine(e); _dialogCoordinator.ShowMessageAsync(this, "Erreur", "Le nouvel élément n'a pas pu être créé"); } //ArticleCourant = Article.NouvelArticle(); //ListeArticles.Add(ArticleCourant); }
public IEnumerable <ITextUnit> GetTextUnits(ComponentPart componentPart, Template template, Citation citation, out bool handled) { //change the following to "true", if you want "id.", "eid.", "ead.", "eaed." written in italics or other font styles bool outputInItalics = true; bool outputInSmallCaps = false; bool outputInBold = false; bool outputUnderlined = false; //NOTE: If you want a prefix such as "In: " and a suffix " (Hrsg)", you can define them as group prefix and suffix on the field element inside the component part editor handled = false; if (componentPart == null) { return(null); } if (componentPart.Elements == null || componentPart.Elements.Count == 0) { return(null); } if (citation == null) { return(null); } Reference reference = citation.Reference; if (reference == null) { return(null); } Reference parentReference = reference.ParentReference; if (parentReference == null) { return(null); } //get editor person field elements (or authors in case of CollectedWorks) and make it a separate List<>, since we are going to change that collection below List <PersonFieldElement> editorPersonFieldElements = parentReference.ReferenceType == ReferenceType.CollectedWorks ? componentPart.Elements.OfType <PersonFieldElement>().Where(element => element.PropertyId == ReferencePropertyId.Authors).ToList() : componentPart.Elements.OfType <PersonFieldElement>().Where(element => element.PropertyId == ReferencePropertyId.Editors).ToList(); if (editorPersonFieldElements == null || editorPersonFieldElements.Count() == 0) { return(null); } //we DO have a valid citation/reference that is a parent's child ReferencePersonCollection childAuthorsCollection = reference.Authors; if (childAuthorsCollection == null || childAuthorsCollection.Count == 0) { return(null); } List <Person> childAuthors = new List <Person>(childAuthorsCollection); ReferencePersonCollection parentEditorsCollection = parentReference.ReferenceType == ReferenceType.CollectedWorks ? parentReference.Authors : parentReference.Editors; if (parentEditorsCollection == null || parentEditorsCollection.Count == 0) { return(null); } List <Person> parentEditors = new List <Person>(parentEditorsCollection); bool usePlural = parentEditors.Count() > 1; PersonEquality equality = CheckPersonEquality(childAuthors, parentEditors); if (equality == PersonEquality.None) { return(null); } //we DO have some equality, so let's check what we need to output instead of the person's name(s) var textIdem = string.Empty; switch (equality) { //see http://en.wiktionary.org/wiki/idem#Inflection case PersonEquality.M: case PersonEquality.N: textIdem = "id."; break; case PersonEquality.F: textIdem = "ead."; break; case PersonEquality.NN: textIdem = "ead."; break; case PersonEquality.MM: textIdem = "iid."; break; case PersonEquality.MN: case PersonEquality.FM: case PersonEquality.FMN: textIdem = "eid."; break; case PersonEquality.FF: case PersonEquality.FN: textIdem = "eaed."; break; } foreach (PersonFieldElement editors in editorPersonFieldElements) { TextUnitCollection output = new TextUnitCollection(); #region GroupPrefix if (usePlural && !string.IsNullOrEmpty(editors.GroupPrefixPlural.Text)) { output.Add(new LiteralTextUnit(editors.GroupPrefixPlural.Text, editors.GroupPrefixPlural.FontStyle)); } else if (!usePlural & !string.IsNullOrEmpty(editors.GroupPrefixSingular.Text)) { output.Add(new LiteralTextUnit(editors.GroupPrefixSingular.Text, editors.GroupPrefixSingular.FontStyle)); } #endregion GroupPrefix SwissAcademic.Drawing.FontStyle fontStyle; fontStyle = SwissAcademic.Drawing.FontStyle.Neutral; if (outputInItalics) { fontStyle |= SwissAcademic.Drawing.FontStyle.Italic; } if (outputInSmallCaps) { fontStyle |= SwissAcademic.Drawing.FontStyle.SmallCaps; } if (outputInBold) { fontStyle |= SwissAcademic.Drawing.FontStyle.Bold; } if (outputUnderlined) { fontStyle |= SwissAcademic.Drawing.FontStyle.Underline; } var fontStyleNeutral = SwissAcademic.Drawing.FontStyle.Neutral; output.Add(new LiteralTextUnit(textIdem, fontStyle)); #region GroupSuffix if (usePlural && !string.IsNullOrEmpty(editors.GroupSuffixPlural.Text)) { output.Add(new LiteralTextUnit(editors.GroupSuffixPlural.Text, editors.GroupSuffixPlural.FontStyle)); } else if (!usePlural && !string.IsNullOrEmpty(editors.GroupSuffixSingular.Text)) { output.Add(new LiteralTextUnit(editors.GroupSuffixSingular.Text, editors.GroupSuffixSingular.FontStyle)); } #endregion GroupSuffix //inject this as LiteralElements into the componentPart, replacing the editors person field element componentPart.Elements.ReplaceItem(editors, TextUnitsToLiteralElements(output, componentPart)); //for some reason this does not work } handled = false; return(null); }
public async Task <IActionResult> CreatePost(TemplateViewModel model, string submit, string returnUrl = null) { if (!model.AdminTemplates && !await _authorizationService.AuthorizeAsync(User, Permissions.ManageTemplates)) { return(Forbid()); } if (model.AdminTemplates && !await _authorizationService.AuthorizeAsync(User, AdminTemplatesPermissions.ManageAdminTemplates)) { return(Forbid()); } ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { if (String.IsNullOrWhiteSpace(model.Name)) { ModelState.AddModelError(nameof(TemplateViewModel.Name), S["The name is mandatory."]); } else if (String.IsNullOrWhiteSpace(model.Content)) { ModelState.AddModelError(nameof(TemplateViewModel.Content), S["The content is mandatory."]); } else { var templatesDocument = model.AdminTemplates ? await _adminTemplatesManager.GetTemplatesDocumentAsync() : await _templatesManager.GetTemplatesDocumentAsync() ; if (templatesDocument.Templates.ContainsKey(model.Name)) { ModelState.AddModelError(nameof(TemplateViewModel.Name), S["A template with the same name already exists."]); } } } if (ModelState.IsValid) { var template = new Template { Content = model.Content, Description = model.Description }; await(model.AdminTemplates ? _adminTemplatesManager.UpdateTemplateAsync(model.Name, template) : _templatesManager.UpdateTemplateAsync(model.Name, template) ); _notifier.Success(H["The \"{0}\" template has been created.", model.Name]); if (submit == "SaveAndContinue") { return(RedirectToAction(nameof(Edit), new { name = model.Name, adminTemplates = model.AdminTemplates, returnUrl })); } else { return(RedirectToReturnUrlOrIndex(returnUrl)); } } // If we got this far, something failed, redisplay form return(View(model)); }
public override void OnApplyTemplate() { colon = Template.FindName("PART_Colon", this) as UIElement; base.OnApplyTemplate(); }