private TemplateDocument LoadDocument(int documentId, string filePath) { TemplateDocument Document = RenderDocumentCache.GetRenderDocument(documentId); if (Document == null) { string newContent = FileUtils.ReadText(filePath); Document = new TemplateDocument(newContent, GlobalContext.WebRootPath, filePath); // RenderDocumentCache.AddRenderDocument(10005, Document); } string upperTableName = GetUpperCanelName(table.entity_name); string lowTableName = upperTableName.Substring(0, 1).ToLower() + upperTableName.Substring(1); string roletag = table.entity_name.Replace("-", ""); //加入基本信息 Document.Variables.SetValue("this", this); Document.Variables.SetValue("table", table); Document.Variables.SetValue("columns", columns); Document.Variables.SetValue("gentime", DateTime.Now); Document.Variables.SetValue("upperTableName", upperTableName); Document.Variables.SetValue("lowTableName", lowTableName); Document.Variables.SetValue("roletag", roletag); Document.RegisterGlobalFunction(this.GetColumnAttr); Document.RegisterGlobalFunction(this.GetCsType); return(Document); }
public void FindsContentControlAndReplacesSingulars() { var filePath = this.CurrentFolder() + "SingularsTestDoc.docx"; using var doc = new TemplateDocument(filePath); var json = File.ReadAllText(this.CurrentFolder() + "TemplatingsTestSingularsData.json"); var src = new VariableSource(); src.LoadDataFromJson(json); var singularReplacer = new SingularDropdownControlReplacer(); singularReplacer.ReplaceAll(doc, src); var c1 = doc.WordprocessingDocument.FindContentControl(singularReplacer.TagName + "_sellers"); var c2 = doc.WordprocessingDocument.FindContentControl(singularReplacer.TagName + "_buyers"); Assert.NotNull(c1); Assert.NotNull(c2); Assert.AreEqual("sellers are", c1.GetTextElement().Text); Assert.AreEqual("buyer", c2.GetTextElement().Text); doc.WordprocessingDocument.AssertValid(); doc.SaveAs(this.CurrentFolder() + "result.docx"); doc.Close(); }
public void ReplacedConditionalDropdownContentControls() { var filePath = this.CurrentFolder() + "Doc.docx"; using var doc = new TemplateDocument(filePath); var json = File.ReadAllText(this.CurrentFolder() + "data.json"); var src = new VariableSource(); src.LoadDataFromJson(json); var replacer = new ConditionalRemoveControlReplacer(); replacer.ReplaceAll(doc, src); doc.SaveAs(this.CurrentFolder() + "result.docx"); Assert.IsNull(doc.WordprocessingDocument.FindContentControl(replacer.TagName + "_enabled1")); Assert.NotNull(doc.WordprocessingDocument.FindContentControl(replacer.TagName + "_enabled2")); Assert.NotNull(doc.WordprocessingDocument.FindContentControl(replacer.TagName + "_enabled3")); Assert.NotNull(doc.WordprocessingDocument.FindContentControl(replacer.TagName + "_enabled1_or_enabled2")); Assert.NotNull(doc.WordprocessingDocument.FindContentControl(replacer.TagName + "_enabled3_or_enabled2")); Assert.IsNull(doc.WordprocessingDocument.FindContentControl(replacer.TagName + "_enabled1_and_enabled2")); Assert.NotNull(doc.WordprocessingDocument.FindContentControl(replacer.TagName + "_enabled1_not_and_enabled2")); Assert.IsNull(doc.WordprocessingDocument.FindContentControl(replacer.TagName + "_enabled2_and_enabled3_not")); doc.WordprocessingDocument.AssertValid(); doc.Close(); }
public async Task <ActionResult> Actions() { var msg = new JsonMessage(); var model = new TemplateDocument(); switch (DoAction) { case ActionType.Add: UpdateModel(model); model.IsShow = true; model.IsDelete = false; model.DateCreate = DateTime.Now.TotalSeconds(); _da.Add(model); _da.Save(); break; case ActionType.Edit: model = _da.GetById(ArrId.FirstOrDefault()); UpdateModel(model); await _api.Update(model); break; case ActionType.Delete: var lst = string.Join(",", ArrId); msg = _api.Delete(lst); break; default: msg.Message = "Không có hành động nào được thực hiện."; msg.Erros = true; break; } return(Json(msg, JsonRequestBehavior.AllowGet)); }
public override void LoadCurrentTemplate() { //是否是手机端网页 string filePath = this.Request.Url.AbsolutePath; bool isMobi = isMobilePage(out filePath); //if (isMobi) filePath = filePath.Substring(prefix.Length); //取模板对象 WeiSha.Common.Templates.TemplateBank curr = isMobi ? WeiSha.Common.Template.ForMobile.SetCurrent(this.Organ.Org_TemplateMobi) : WeiSha.Common.Template.ForWeb.SetCurrent(this.Organ.Org_Template); if (curr == null) { throw new Exception("没有任何模板可用!"); } //当前模板的所在路径 string tmFile = curr.Path.Physics + filePath + ".htm"; //装载模板 this.Document = null; if (!System.IO.File.Exists(tmFile)) { tmFile = WeiSha.Common.Template.ForWeb.Default.Path.Physics + filePath + ".htm"; if (!System.IO.File.Exists(tmFile)) { tmFile = curr.Path.Physics + "Notfound.htm"; } this.Document = new TemplateDocument(tmFile, Encoding.UTF8, this.DocumentConfig); } else { this.Document = TemplateDocument.FromFileCache(tmFile, Encoding.UTF8, this.DocumentConfig); } }
static FwkGeneratorHelper() { roottemplate = Path.Combine(HelperFunctions.ProgramFilesx86(), @"Fwk Software Factory\5.0\FwkTemplates\tt\"); _TemplateDocument = (TemplateDocument)HelperFunctions.DeserializeFromXml(typeof(TemplateDocument), GetFileTemplate("Templates.xml")); _MappingTypes = (MappingTypes)HelperFunctions.DeserializeFromXml(typeof(MappingTypes), GetFileTemplate("MappingType.xml")); NotSupportTypes_ToIncludeInBackEnd = "xml,timestamp,sql_variant"; NotSupportTypes_ToSearchInStoreProcedure = "xml,timestamp,sql_variant,varbinary,binary,image"; NotSupportTypes_ToInsertStoreProcedure = "xml,timestamp,sql_variant"; _Entity_Envelope_tt = FwkGeneratorHelper.GetFileTemplate("Entity.txt"); _Entity_Property_TemplateBinary_tt = _TemplateDocument.GetTemplate("Property_Binary").Content; _Entity_Property_tt = _TemplateDocument.GetTemplate("Property").Content; _Entity_Member_tt = " private [TYPENAME][NullToken] _[Property_Name];"; UserDefinedTypes = new UserDefinedTypes(); }
public ActionResult ProjectEventPaymentGenerator(int RepperID, int BudgetID) { if (RepperID > 0 && BudgetID > 0) { ReportPeriodListR repper = GetRepper(RepperID, BudgetID); ProjectEventService pes = new ProjectEventService(); ProjectEvent o = new ProjectEvent(); o.CompletedDate = repper.PaymentDate; o.EventDescription = "Payment Request"; o.ProjectID = BudgetID; //o.EventType = GetPaymentEventType(); o.EventTypeID = GetPaymentEventType().EventTypeID; o.ReportPeriodID = RepperID; o.SSPOrGrantee = true; o.EventStatus = 0; pes.Insert(o); EventTemplate eh = new EventTemplate(); TemplateService ts = new TemplateService(); TemplateDocument td1 = null; td1 = ts.GetTemplateDocument("Запрос на Оплату"); if (td1 != null) { eh.CreateFromTemplate(td1.TemplateDocsID, BudgetID, o.EventID, RepperID); } } return(RedirectToAction("Reppers", new { id = BudgetID })); }
/// <summary> /// 通用获取数据方法 /// </summary> /// <returns></returns> public static DataRowView GetSingleData() { TemplateDocument td = TemplateDocument.CurrentRenderingDocument; if (td != null) { if (td.CurrentRenderingTag != null) { Tag tag = td.CurrentRenderingTag; string tablename = tag.Attributes.GetValue("table"); string filedshow = tag.Attributes.GetValue("show"); string strwhere = tag.Attributes.GetValue("where"); string para = tag.Attributes.GetValue("para"); if (!string.IsNullOrEmpty(para)) { // strwhere = strwhere.Replace("?", para); } try { return(BLL.DataBaseHelper.instance.GetModelView(tablename, filedshow, strwhere)); } catch { return(null); } } } return(null); }
internal CompiledEvaluationDelegate <TContext> CompileTemplate([NotNull] TemplateDocument document) { Debug.Assert(document != null, "Argument document cannot be null."); /* Construct the combined node for all the children. */ return(CompileTemplateNodes(document.Children)); }
static FwkGeneratorHelper() { //roottemplate = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates"); //Path.Combine(HelperFunctions.ProgramFilesx86(), @"Allus Global BPO\FwkTemplates\tt\"); roottemplate = Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Templates"); _TemplateDocument = (TemplateDocument)HelperFunctions.DeserializeFromXml(typeof(TemplateDocument), GetFileTemplate("Templates.xml")); _MappingTypes = (MappingTypes)HelperFunctions.DeserializeFromXml(typeof(MappingTypes), GetFileTemplate("MappingType.xml")); NotSupportTypes_ToIncludeInBackEnd = "xml,timestamp,sql_variant"; NotSupportTypes_ToSearchInStoreProcedure = "xml,timestamp,sql_variant,varbinary,binary,image"; NotSupportTypes_ToInsertStoreProcedure = "xml,timestamp,sql_variant"; _Entity_Envelope_tt = FwkGeneratorHelper.GetFileTemplate("Entity.txt"); _Entity_Property_TemplateBinary_tt = _TemplateDocument.GetTemplate("Property_Binary").Content; _Entity_Property_tt = _TemplateDocument.GetTemplate("Property").Content; _Entity_Member_tt = " private [TYPENAME][NullToken] _[Property_Name];"; }
public ActionResult DocumentBuildWithParam(DocumentModel document, string type) { if (document != null) { Document baseDocument = db.Documents.Include(o => o.Template).First(o => o.Id == document.Id); baseDocument = document.GetDocument(baseDocument); db.SaveChanges(); TemplateDocument templateDocument = new TemplateDocument(baseDocument); List <ReplaceItem> items = new List <ReplaceItem>(templateDocument.ItemsValue.Select(o => new ReplaceItem { Key = o.Key, Value = o.Value })); FileStream fileStream = System.IO.File.OpenRead(HttpContext.Server.MapPath("/Content/Projects/templates/" + type + ".docx")); byte[] data = new byte[fileStream.Length]; fileStream.Read(data, 0, data.Length); UploadHelper.UploadReplace(data, "протокол.docx", baseDocument.AttachPath, items); fileStream.Close(); DocumentModel model = new DocumentModel(baseDocument); return(Content(JsonConvert.SerializeObject(new { State = true, document = model }, Formatting.Indented, new JsonSerializerSettings() { DateFormatString = "dd.MM.yyyy HH:mm" }))); return(Json(new { State = true, document = model }, JsonRequestBehavior.AllowGet)); } return(Content(bool.FalseString)); }
public ActionResult DocumentBuild(DocumentModel document) { if (document != null) { Document baseDocument = db.Documents.Include(o => o.Template).First(o => o.Id == document.Id); baseDocument = document.GetDocument(baseDocument); db.SaveChanges(); TemplateDocument templateDocument = new TemplateDocument(baseDocument); List <ReplaceItem> items = new List <ReplaceItem>(templateDocument.ItemsValue.Select(o => new ReplaceItem { Key = o.Key, Value = o.Value })); FileStream fileStream = System.IO.File.OpenRead(HttpContext.Server.MapPath("/Content/Projects/Project" + baseDocument.ProjectType + ".docx")); byte[] data = new byte[fileStream.Length]; fileStream.Read(data, 0, data.Length); if (document.RemarkId == 1) { items.FirstOrDefault(i => i.Key == "Comment1").Value = !string.IsNullOrEmpty(document.RemarkText1)?"1) " + document.RemarkText1:""; items.FirstOrDefault(i => i.Key == "Comment2").Value = !string.IsNullOrEmpty(document.RemarkText2) ? "2) " + document.RemarkText2 : ""; items.FirstOrDefault(i => i.Key == "Comment3").Value = !string.IsNullOrEmpty(document.RemarkText3) ? "3) " + document.RemarkText3 : ""; UploadHelper.UploadReplace(data, "Замечания.docx", baseDocument.AttachPath, items); } else if (document.RemarkId == 2) { fileStream = System.IO.File.OpenRead(HttpContext.Server.MapPath("/Content/Projects/Parley.docx")); data = new byte[fileStream.Length]; fileStream.Read(data, 0, data.Length); items.AddRange(new List <ReplaceItem> { new ReplaceItem { Key = "ParleyStartDate", Value = document.ParleyStartDate.ToString("d MMM yyyy", CultureInfo.CurrentCulture) }, new ReplaceItem { Key = "ParleyEndDate", Value = document.ParleyEndDate.ToString("d MMM yyyy", CultureInfo.CurrentCulture) } }); UploadHelper.UploadReplace(data, "Приглашение на переговоры.docx", baseDocument.AttachPath, items); } else { UploadHelper.UploadReplace(data, "Проект.docx", baseDocument.AttachPath, items); } fileStream.Close(); DocumentModel model = new DocumentModel(baseDocument); return(Content(JsonConvert.SerializeObject(new { State = true, document = model }, Formatting.Indented, new JsonSerializerSettings() { DateFormatString = "dd.MM.yyyy HH:mm" }))); return(Json(new { State = true, document = model }, JsonRequestBehavior.AllowGet)); } return(Content(bool.FalseString)); }
public void ReplacedConditionalDropdownContentControls() { var filePath = this.CurrentFolder() + "Doc.docx"; using var doc = new TemplateDocument(filePath); var json = File.ReadAllText(this.CurrentFolder() + "data.json"); var src = new VariableSource(); src.LoadDataFromJson(json); var replacer = new ConditionalDropdownControlReplacer(); replacer.ReplaceAll(doc, src); var c1 = doc.WordprocessingDocument.FindContentControl("conditional_isValid"); var c2 = doc.WordprocessingDocument.FindContentControl("conditional_isInvalid"); var c3 = doc.WordprocessingDocument.FindContentControl("conditional_isInvalid_or_isValid"); Assert.NotNull(c1); Assert.NotNull(c2); Assert.NotNull(c3); Assert.AreEqual("THIS IS VALID", c1.GetTextElement().Text); Assert.AreEqual("THIS IS VALID", c2.GetTextElement().Text); Assert.AreEqual("THIS IS VALID", c3.GetTextElement().Text); doc.WordprocessingDocument.AssertValid(); doc.SaveAs(this.CurrentFolder() + "result.docx"); doc.Close(); }
internal CompiledTemplate([NotNull] TemplateDocument document, [NotNull] CompiledEvaluationDelegate <TContext> evaluationDelegate) { Debug.Assert(document != null, "Argument document cannot be null."); Debug.Assert(evaluationDelegate != null, "Argument evaluationDelegate cannot be null."); _document = document; _evaluationDelegate = evaluationDelegate; }
/// <summary> /// Replaces all matching content controls in the template document with the matched data from the VariableSource /// </summary> /// <param name="doc">The template document</param> /// <param name="variableSource">The data source for variables</param> public void ReplaceAll(TemplateDocument doc, IVariableSource variableSource) { //Enumerate the collections to list in case we add more to the lists while replacing Enqueue(ReplacesOnlyFirstOrderChildren ? new ControlReplacementExecutionData(doc.FirstOrderContentControls.ToList(), variableSource) : new ControlReplacementExecutionData(doc.AllContentControls.ToList(), variableSource)); ExecuteQueue(); }
/// <summary> /// 处理模板中的标签 /// </summary> /// <param name="doc">模板对象</param> public static void Start(TemplateDocument doc) { Song.Entities.Organization org = Business.Do <IOrganization>().OrganCurrent(); //列表标签的处理 ElementCollection <Tag> tags = doc.GetCustomTags("list,repeat"); foreach (Element item in tags) { if (item is Tag) { Tag tag = (Tag)item; //如果已经指定了数据来源,则不再继续往下走了 string from = tag.Attributes.GetValue("from"); if (!string.IsNullOrWhiteSpace(from)) { continue; } //如果没有数据源,则通过以下解析,指定数据源 string tagname = tag.TagName; //标签名称 string tagSpace = string.Empty; //要实现标签解析的命名空间名称 if (tagname == "list") { tagSpace = "ListTag"; } if (tagname == "repeat") { tagSpace = "RepeaterTag"; } if (tagname == "detail") { tagSpace = "DetailTag"; } //组件标签类的完整路径名 string classFullName = "Song.Template.Tags.{0}.{1}"; classFullName = String.Format(classFullName, tagSpace, tag.Type); Type info = System.Type.GetType(classFullName); //创建反射 if (info == null) { continue; } object obj = System.Activator.CreateInstance(info); //实例化标签对象 Song.Template.Tags.TagElement el = (Song.Template.Tags.TagElement)obj; if (el == null) { continue; } el.Organ = org; el.Type = tag.Type; el.Tag = tag; el.DataBind(); //绑定数据源 } } //注册方法 RegisterFunction.Register(doc); }
/// <summary> /// 装载页面模版文件 /// </summary> /// <param name="filename">要读取的文件地址</param> /// <param name="encoding">读取文件时使用的编码</param> public virtual void LoadTemplateFromFile(string filename, Encoding encoding) { filename = Utility.ToAbsolutePath(filename); this._Document = TemplateDocument.FromFileCache(filename, encoding, this.DocumentConfig); this._Document.Variables.SetValue("Page", this); this._Document.Variables.SetValue("Page.SitePath", this.Configuration.ToRelativeSitePath("")); this._Document.Variables.SetValue("Page.SiteUrl", this.Configuration.ToRelativeSiteUrl("")); this._Document.Variables.SetValue("Page.TemplatePath", this.Configuration.ToRelativeTemplatePath("")); }
/// <summary> /// 添加渲染模板缓存 /// </summary> /// <param name="channel"></param> public static void AddRenderDocument(int templateId, TemplateDocument douments) { if (_douments.ContainsKey(templateId)) { _douments[templateId] = douments; return; } _douments.TryAdd(templateId, douments); }
public static void Register(TemplateDocument doc) { //一些个常用方法 doc.RegisterGlobalFunction(Path); //获取路径 doc.RegisterGlobalFunction(getCourses); doc.RegisterGlobalFunction(getCoursePrice); //产品价格 doc.RegisterGlobalFunction(getArticle); doc.RegisterGlobalFunction(getLinks); //友情链接 doc.RegisterGlobalFunction(ClearHtml); //清理html标签 }
/// <summary> /// 返回渲染后的模板文件 /// </summary> /// <param name="content"></param> /// <param name="template"></param> /// <returns></returns> public void GenerateHomeHtml() { try { var templateModel = TemplateManagerCache.GetHomeTemplate(); if (templateModel.id == 0) { throw new Exception("找不到模板"); } //加载模板 //this.LoadTemplate(templateModel.template_content); string templateFile = Path.Combine(GlobalParamsDto.WebRoot, templateModel.template_file); this.Document = new TemplateDocument(templateModel.template_content, GlobalParamsDto.WebRoot, templateFile); this.Document.Variables.SetValue("this", this); //设置顶部导航条数据 var navigations = _generateContentApp.GetChannelTree(); this.Document.Variables.SetValue("navigations", navigations); //获取栏目文章模板 ElementCollection <Template> templates = this.Document.GetChildTemplatesByName("channels"); foreach (Template template in templates) { string total = template.Attributes.GetValue("total", "10"); //根据模板块里定义的type属性条件取得新闻数据 var data = _generateContentApp.GetContentSummary(template.Attributes.GetValue("type"), 1, int.Parse(total)); //设置变量newsdata的值 template.Variables.SetValue("contents", data); //取得模板块下Id为newslist的标签(也即是在cnblogs_newsdata.html文件中定义的foreach标签) //Tag tag = template.GetChildTagById("newslist"); //if (tag is ForEachTag) //{ // //如果标签为foreach标签则设置其BeforeRender事件用于设置变量表达式{$:#.news.url}的值 // tag.BeforeRender += new System.ComponentModel.CancelEventHandler(Tag_BeforeRender); //} } string contentFilePath = Path.Combine(GlobalParamsDto.WebRoot, "index.html"); using (var filestream = new FileStream(contentFilePath, FileMode.Create, FileAccess.ReadWrite)) { string renderHtml = this.Document.GetRenderText(); using (StreamWriter writer = new StreamWriter(filestream, Encoding.UTF8)) { writer.WriteLine(renderHtml); writer.Flush(); } } } catch (Exception ex) { LogNHelper.Exception(ex); } }
public MainWindow() { InitializeComponent(); var templates = TemplateDocument.Load(); _viewModel = new SqlTemplateOptionViewModel(templates); _viewModel.OnSave += viewModel_OnSave; _viewModel.OnCancel += _viewModel_OnCancel; DataContext = _viewModel; }
public ActionResult Edit(int id) { if (!session.LoggedIn) { return(RedirectToAction("Login", "SSPStaff")); } TemplateDocument t = ts.GetTemplateDocument(id); return(View(t)); }
/// <summary> /// 通用获取数据方法 /// </summary> /// <returns></returns> public static DataView GetMenuData() { TemplateDocument td = TemplateDocument.CurrentRenderingDocument; if (td != null) { if (td.CurrentRenderingTag != null) { Tag tag = td.CurrentRenderingTag; try { if (BaseWeb.instance.AdminId == 0) { return(null); } DataTable dt; DataTable mytable; GetMenuByCache(out dt, out mytable); DataView dv = dt.DefaultView; dv.RowFilter = "ParentId is NULL "; string curid = tag.Attributes.GetValue("id"); string flag = tag.Attributes.GetValue("flag"); if (!string.IsNullOrEmpty(flag) && flag == "1") { string pid = tag.Attributes.GetValue("pid"); DataView dv1 = mytable.DefaultView; dv1.RowFilter = "ParentId='" + pid + "'"; return(dv1); } else { if (string.IsNullOrEmpty(curid)) { dv.RowFilter = "ParentId is NULL "; } else { dv.RowFilter = "menuid='" + curid + "'"; } return(dv); } } catch { return(null); } } } return(null); }
public ActionResult Create(int EventTypeID) { if (!session.LoggedIn) { return(RedirectToAction("Login", "SSPStaff")); } TemplateDocument t = new TemplateDocument(); t.EventTypeID = EventTypeID; return(View(t)); }
/// <summary> /// 装载模板文件 /// </summary> /// <param name="fileName"></param> protected virtual void LoadTemplateFile(string fileName) { this.Document = null; try { this.Document = TemplateDocument.FromFileCache(fileName, Encoding.UTF8, this.DocumentConfig); } catch { this.Document = new TemplateDocument(fileName, Encoding.UTF8, this.DocumentConfig); } }
/// <summary> /// 装载当前页面的模板文档 /// </summary> public virtual void LoadCurrentTemplate() { //是否是手机端网页 string filePath = this.Request.Url.AbsolutePath; bool isMobi = isMobilePage(out filePath); //处理后filePath为文件名(不含扩展名) if (isMobi && LoginState.Accounts.IsLogin) { LoginState.Accounts.Refresh(LoginState.Accounts.CurrentUser); } //取模板对象 if (this.Organ != null) { this.TmBank = isMobi ? WeiSha.Common.Template.ForMobile.SetCurrent(this.Organ.Org_TemplateMobi) : WeiSha.Common.Template.ForWeb.SetCurrent(this.Organ.Org_Template); } else { this.TmBank = isMobi ? WeiSha.Common.Template.ForMobile.Default : WeiSha.Common.Template.ForWeb.Default; } if (TmBank == null) { throw new Exception("没有任何模板库可用!"); } //是否是公共页面 if (TmBank.Config.Public == null) { throw new Exception("未找到公共模板库!"); } bool isPublic = TmBank.Config.Public.PageExists(filePath); if (isPublic) { TmBank = TmBank.Config.Public; } //当前模板的所在路径 string tmFile = TmBank.Path.Physics + filePath + ".htm"; //装载模板 this.Document = null; if (!System.IO.File.Exists(tmFile)) { tmFile = TmBank.Config.Default.Path.Physics + filePath + ".htm"; if (!System.IO.File.Exists(tmFile)) { tmFile = TmBank.Config.Public.Path.Physics + "Notfound.htm"; } } this.Document = TemplateDocument.FromFileCache(tmFile, Encoding.UTF8, this.DocumentConfig); //this.Document = new TemplateDocument(tmFile, Encoding.UTF8, this.DocumentConfig); //不采用缓存 }
/// <summary> /// 装载模板文件 /// </summary> /// <param name="fileName"></param> protected virtual void LoadTemplateFile(string fileName) { this.Document = null; if ("cache".Equals(this.TestType, StringComparison.InvariantCultureIgnoreCase) || this.IsLoadCacheTemplate) { //测试缓存模板文档 this.Document = TemplateDocument.FromFileCache(fileName, Encoding.UTF8, this.DocumentConfig); } else { //测试实例模板文档 this.Document = new TemplateDocument(fileName, Encoding.UTF8, this.DocumentConfig); } }
/// <summary> /// 返回渲染后的页面文件 /// </summary> /// <param name="content"></param> /// <param name="template"></param> /// <returns></returns> public (bool genStatus, string contentHtml) GenerateContentHtml(int channelId, int id) { try { Stopwatch watcher = new Stopwatch(); watcher.Start(); var templateModel = ChannelManagerCache.GetContentTemplate(channelId); if (templateModel == null) { return(false, ""); } var content = _contentApp.GetContentInfo(id); if (content == null) { return(false, ""); } //加载模板 先取缓存,没有再初始化一个并且加入缓存 this.Document = RenderDocumentCache.GetRenderDocument(templateModel.id); if (this.Document == null) { string templateFile = Path.Combine(GlobalContext.WebRootPath, templateModel.template_file); this.Document = new TemplateDocument(templateModel.template_content, GlobalContext.WebRootPath, templateFile); RenderDocumentCache.AddRenderDocument(templateModel.id, this.Document); } this.Document.Variables.SetValue("this", this); //站点基本信息 var site = SiteManagerCache.GetSiteInfo(); this.Document.Variables.SetValue("site", site); //设置顶部导航条数据 var navigations = _contentApp.GetChannelTree(); this.Document.Variables.SetValue("navigations", navigations); //获取当前文章信息 this.Document.Variables.SetValue("content", content); string renderHtml = this.Document.GetRenderText(); renderHtml = HtmlPlayerHandler.CreateVideo(renderHtml); watcher.Stop(); string msg = $"渲染内容页耗时:{watcher.ElapsedMilliseconds} ms"; LoggerHelper.Info(msg); return(true, renderHtml); } catch (Exception ex) { LoggerHelper.Exception(ex); } return(false, ""); }
public ActionResult Edit(TemplateDocument item, string fileextension) { if (!session.LoggedIn) { return(RedirectToAction("Login", "SSPStaff")); } TemplateDocument t = ts.GetTemplateDocument(item.TemplateDocsID); t.TemplateDocName = item.TemplateDocName; t.EventTypeID = item.EventTypeID; t.TemplateFile.fileextension = fileextension; if (Request.Files.Count != 0) { if (!String.IsNullOrEmpty(Request.Files[0].FileName)) { //TemplateFile tf = new TemplateFile(); t.TemplateFile.Author = session.CurrentUser.FirstName + " " + session.CurrentUser.LastName + " " + session.CurrentUser.MiddleName;; t.TemplateFile.CreatedDate = DateTime.Now; /*string ext; * string[] a = Request.Files[0].FileName.ToLower().Split('.'); * ext = a[a.Length - 1];*/ t.TemplateFile.FileName = Request.Files[0].FileName; string dir = ConfigurationManager.AppSettings["PhysicalPath"]; try { System.IO.File.Delete(dir + t.TemplateFile.PhysicalVirtualPath); } catch (Exception ex) { } string virtdir = "Templates/"; dir += virtdir.Replace("/", "\\"); if (!(Directory.Exists(dir))) { Directory.CreateDirectory(dir); } Request.Files[0].SaveAs(dir + Request.Files[0].FileName); t.TemplateFile.PhysicalVirtualPath = "\\" + virtdir.Replace("/", "\\") + Request.Files[0].FileName; t.TemplateFile.UpdatedDate = DateTime.Now; t.TemplateFile.WebVirtualPath = "/" + virtdir + Request.Files[0].FileName; } } ts.UpdateTemplateDocument(t); return(RedirectToAction("Templates", new { EventTypeID = item.EventTypeID })); }
/// <summary> /// 用于给模板调用的方法(静态方法) /// </summary> /// <returns></returns> public static List <News> GetStaticNewsData() { //获取正在呈现数据的文档 TemplateDocument document = TemplateDocument.CurrentRenderingDocument; string type = "relating"; //默认的 if (document != null) { if (document.CurrentRenderingTag != null) { //正在呈现的标签不为null.也就是此函数是通过标签调用的 type = document.CurrentRenderingTag.Attributes.GetValue("dbtype"); } } return(NewsDbProvider.GetNewsData(type)); }
/// <summary> /// 通用获取数据方法 /// </summary> /// <returns></returns> public static void Go2Url() { TemplateDocument td = TemplateDocument.CurrentRenderingDocument; if (td != null) { if (td.CurrentRenderingTag != null) { Tag tag = td.CurrentRenderingTag; string url = tag.Attributes.GetValue("url"); if (BaseWeb.instance.UserId == 0) { HttpContext.Current.Response.Redirect(url); } } } }
/// <summary> /// 装载模板文件 /// </summary> /// <param name="fileName"></param> protected virtual void LoadTemplateFile(string fileName) { this.Document = null; if (this.IsLoadCacheTemplate) { //缓存模板文档 this.Document = TemplateDocument.FromFileCache(fileName, Encoding.UTF8, this.DocumentConfig); } else { //实例模板文档 this.Document = new TemplateDocument(fileName, Encoding.UTF8, this.DocumentConfig); } //设置当前页面对象的值 this.Document.SetValue("Page", this); }