protected override string RenderTemplate(string content, PageContext pageData) { var serviceConfiguration = new TemplateServiceConfiguration { TemplateManager = new IncludesResolver(FileSystem, includesPath), BaseTemplateType = typeof(ExtensibleTemplate<>), DisableTempFileLocking = true, CachingProvider = new DefaultCachingProvider(t => { }) }; serviceConfiguration.Activator = new ExtensibleActivator(serviceConfiguration.Activator, Filters, _allTags); Engine.Razor = RazorEngineService.Create(serviceConfiguration); content = Regex.Replace(content, "<p>(@model .*?)</p>", "$1"); var pageContent = pageData.Content; pageData.Content = pageData.FullContent; try { content = Engine.Razor.RunCompile(content, pageData.Page.File, typeof(PageContext), pageData); pageData.Content = pageContent; return content; } catch (Exception e) { Tracing.Error(@"Failed to render template, falling back to direct content"); Tracing.Debug(e.Message); Tracing.Debug(e.StackTrace); return content; } }
private WebAppServer CreateServer() { var resolver = new WindsorDependencyResolver(_container); var server = new WebAppServer(BaseAddress); server.HttpConfiguration.DependencyResolver = resolver; server.HttpConfiguration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; server.HttpConfiguration.Routes.MapHttpRoute( name: "DefaultAPI", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); server.HttpConfiguration.Routes.MapHttpRoute( name: "Default", routeTemplate: "{controller}/{action}", defaults: new { controller = "Home", action = "Index" }); //server.HttpConfiguration.MessageHandlers.Add(new FaviconHandler()); server.StaticFiles.Add("/Scripts", typeof (ScriptsLocator)); server.HttpConfiguration.MessageHandlers.Add(new StaticFileHandler("Scripts", "text/javascript")); var templateConfiguration = new TemplateServiceConfiguration(); templateConfiguration.Resolver = new EmbeddedTemplateResolver(typeof(ViewResourceLocator)); templateConfiguration.BaseTemplateType = typeof(CustomTemplateBase<>); Razor.SetTemplateService(new TemplateService(templateConfiguration)); return server; }
public String Render(TemplateModel templateModel) { var assembly = Assembly.GetExecutingAssembly(); string template; using (var sr = new StreamReader(assembly.GetManifestResourceStream("HotGlue.Generator.MVCRoutes.Templates.Routing.razor"))) { template = sr.ReadToEnd(); } var config = new TemplateServiceConfiguration { BaseTemplateType = typeof (JavaScriptRoutingTemplateBase<>) }; string result; try { using (var service = new TemplateService(config)) { Razor.SetTemplateService(service); result = Razor.Parse(template, templateModel); return result; } } catch (TemplateCompilationException ex) { foreach (var error in ex.Errors) { Console.WriteLine(error.ErrorText); } throw; } }
public void Start() { var config = new TemplateServiceConfiguration(); config.TemplateManager = templateManager; var service = RazorEngineService.Create(config); Engine.Razor = service; }
protected override void BeginProcessing() { WriteDebug("BeginProcessing paramSet:" + this.ParameterSetName); var config = new TemplateServiceConfiguration(); if ((this.Language ?? "").ToLower() == "vb") config.Language = global::RazorEngine.Language.VisualBasic; // VB.NET as template language. else config.Language = global::RazorEngine.Language.CSharp; WriteDebug("Selected language: " + config.Language); //config.EncodedStringFactory = new RawStringFactory(); // Raw string encoding. //config.EncodedStringFactory = new HtmlEncodedStringFactory(); // Html encoding. //config.Debug = IsDebug; config.CachingProvider = new DefaultCachingProvider(t => { }); config.DisableTempFileLocking = true; Engine.Razor = RazorEngineService.Create(config); ; if (ParameterSetName == ParamSets.External) { ValidateExternal(); } base.BeginProcessing(); }
/// <summary> /// </summary> /// <returns></returns> internal static string ConnectionList() { var fileName = FilePath + "\\ConnectionList.htm"; String content; var stream = new StreamReader(fileName); content = stream.ReadToEnd(); var connectionList = String.Empty; foreach (var item in RuntimeMongoDBContext._mongoConnectionConfigList.Values) { if (item.ReplSetName == String.Empty) { connectionList += "<li><a href = 'Connection?" + item.ConnectionName + "'>" + item.ConnectionName + "@" + (item.Host == String.Empty ? "localhost" : item.Host) + (item.Port == 0 ? String.Empty : ":" + item.Port) + "</a></li>" + Environment.NewLine; } else { connectionList += "<li><a href = 'Connection?" + item.ConnectionName + "'>" + item.ConnectionName + "</a></li>" + Environment.NewLine; } } var config = new TemplateServiceConfiguration(); //config.ReferenceResolver = (IReferenceResolver)((new UseCurrentAssembliesReferenceResolver()).GetReferences(null)); config.Debug = true; var ser = new TemplateService(config); ser.AddNamespace("MongoUtility.Core"); ser.AddNamespace("SystemUtility"); Razor.SetTemplateService(ser); content = Razor.Parse(content, new {SystemConfig.config.ConnectionList}); return content; }
static void Main(string[] agrs) { string template = "This is my sample template, Hello @Model.Name!"; string result = Razor.Parse(template, new { Name = "World" }); Console.WriteLine(result); var config = new TemplateServiceConfiguration { BaseTemplateType = typeof(CustomBaseTemplate<>), Resolver = new CustomTemplateResolver(), }; var service = new TemplateService(config); Razor.SetTemplateService(service); string template3 = "My name @Html.Raw(Model.HtmlString) @Model.HtmlString in UPPER CASE is @Model.Name"; string result3 = Razor.Parse(template3, new { Name = "Max", Email ="*****@*****.**", HtmlString = "<a href=\"/web/x.html\"> asd </a>" }); Console.WriteLine(result3); var context = new ExecuteContext(); var parsedView = Razor.Resolve("TestView").Run(context); Console.WriteLine(parsedView); Console.ReadKey(); }
private void WriteDocuments(IEnumerable<IMember> members) { var config = new TemplateServiceConfiguration { BaseTemplateType = typeof (MarkdownTemplateBase<>) }; string template = getTemplate(); // You can use the @inherits directive instead (this is the fallback if no @inherits is found). var types = members.GroupBy(m => m.TypeName); using (var razorService = RazorEngineService.Create(config)) { foreach (var typeMembers in types) { var result = razorService.RunCompile(template, "type", typeof(DocumentModel), new DocumentModel { TypeName = typeMembers.Key, Members = typeMembers }); CreateDocument((typeMembers.First() as MemberBase)?.AssemblyName ?? "UnknownAssembly", typeMembers.Key, result); } } }
private void configureServices(IServiceRegistry services) { var configuration = new TemplateServiceConfiguration {BaseTemplateType = typeof (FubuRazorView)}; services.ReplaceService<ITemplateRegistry<IRazorTemplate>>(_templateRegistry); services.ReplaceService<IFubuTemplateService>(new FubuTemplateService(_templateRegistry, new TemplateService(configuration), new FileSystem())); services.ReplaceService<ITemplateServiceConfiguration>(configuration); services.ReplaceService<IParsingRegistrations<IRazorTemplate>>(_parsings); services.SetServiceIfNone<ITemplateDirectoryProvider<IRazorTemplate>, TemplateDirectoryProvider<IRazorTemplate>>(); services.SetServiceIfNone<ISharedPathBuilder>(new SharedPathBuilder()); var graph = new SharingGraph(); services.SetServiceIfNone(graph); services.SetServiceIfNone<ISharingGraph>(graph); services.FillType<IActivator, RazorActivator>(); services.FillType<ISharedTemplateLocator<IRazorTemplate>, SharedTemplateLocator<IRazorTemplate>>(); services.FillType<ISharingAttacher<IRazorTemplate>, MasterAttacher<IRazorTemplate>>(); services.FillType<ITemplateSelector<IRazorTemplate>, RazorTemplateSelector>(); services.FillType<IActivator, SharingAttacherActivator<IRazorTemplate>>(); services.FillType<IRenderStrategy, AjaxRenderStrategy>(); services.FillType<IRenderStrategy, DefaultRenderStrategy>(); services.SetServiceIfNone<IViewModifierService<IFubuRazorView>, ViewModifierService<IFubuRazorView>>(); services.FillType<IViewModifier<IFubuRazorView>, LayoutActivation>(); services.FillType<IViewModifier<IFubuRazorView>, PartialRendering>(); services.FillType<IViewModifier<IFubuRazorView>, FubuPartialRendering>(); }
private void button1_Click(object sender, EventArgs e) { button1.Enabled = false; IEnumerable<dynamic> rows = null; // Connect to the database using (SqlConnection cnn = new SqlConnection(@"Data Source=KANG\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True")) { cnn.Open(); using (SqlCommand cmd = cnn.CreateCommand()) { // Send our query and get the data back cmd.CommandText = queryTextBox.Text; // Convert it to a list of dynamic objects rows = cmd.ExecuteReader().ToDynamicList(); // Run the template over the data var config = new TemplateServiceConfiguration() { BaseTemplateType = typeof(ReportTemplate) }; Razor.SetTemplateService(new TemplateService(config)); var render = Razor.Parse(templateTextBox.Text, rows); // Stuff the content in the web browser control previewBrowser.DocumentText = render; button1.Enabled = true; } } }
public SampleService(bool throwOnStart, bool throwOnStop, bool throwUnhandled, Uri address) { _throwOnStart = throwOnStart; _throwOnStop = throwOnStop; _throwUnhandled = throwUnhandled; if (!EventLog.SourceExists(EventSource)) { EventLog.CreateEventSource(EventSource, "Application"); } EventLog.WriteEntry(EventSource, String.Format("Creating server at {0}", address.ToString())); _config = new HttpSelfHostConfiguration(address); _config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional } ); _config.Routes.MapHttpRoute( "Default", "{controller}/{action}", new { controller = "Home", action = "Index", date = RouteParameter.Optional}); const string viewPathTemplate = "SampleTopshelfService.Views.{0}"; var templateConfig = new TemplateServiceConfiguration(); templateConfig.Resolver = new DelegateTemplateResolver(name => { string resourcePath = string.Format(viewPathTemplate, name); var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourcePath); using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } }); Razor.SetTemplateService(new TemplateService(templateConfig)); _server = new HttpSelfHostServer(_config); }
public RazorViewParser(ITemplateResolver resolver) { if (resolver == null) throw new ArgumentNullException("resolver"); var config = new TemplateServiceConfiguration { Resolver = resolver }; _templateService = new TemplateService(config); }
public void SetupTemplateResolver() { var mock = new Mock<ITemplateResolver>(); mock.Setup(x => x.Resolve(It.IsAny<string>())).Returns("Mocked View Content."); var razorConfig = new TemplateServiceConfiguration { Resolver = mock.Object}; Razor.SetTemplateService(new TemplateService(razorConfig)); }
/// <summary> /// Creates a new <see cref="FileSystemRazorViewEngine"/> that finds views within the given path. /// </summary> /// <param name="viewPathRoot">The root directory that contains views.</param> public FileSystemRazorViewEngine(string viewPathRoot) { this.viewPathRoot = viewPathRoot; var razorConfig = new TemplateServiceConfiguration(); razorConfig.Resolver = new DelegateTemplateResolver(ResolveTemplate); razorService = new TemplateService(razorConfig); }
private void InitializeRazor() { TemplateServiceConfiguration templateConfig = new TemplateServiceConfiguration(); templateConfig.DisableTempFileLocking = true; templateConfig.EncodedStringFactory = new RawStringFactory(); templateConfig.CachingProvider = new DefaultCachingProvider(x => { }); var service = RazorEngineService.Create(templateConfig); Engine.Razor = service; }
protected override string RenderTemplate(string content, PageContext pageData) { var includesPath = Path.Combine(pageData.Site.SourceFolder, "_includes"); var serviceConfig = new TemplateServiceConfiguration { Resolver = new IncludesResolver(FileSystem, includesPath) }; RazorEngine.Razor.SetTemplateService(new TemplateService(serviceConfig)); content = Regex.Replace(content, "<p>(@model .*?)</p>", "$1"); return RazorEngine.Razor.Parse(content, pageData); }
internal IEmailTemplateService InstanceEmailTemplateService(IKernel kernel) { TemplateServiceConfiguration configuration = new TemplateServiceConfiguration { Activator = new WindsorTemplateActivator(kernel), BaseTemplateType = typeof(ExtendedTemplate<>), Resolver = new EmbeddedTemplateResolver(typeof(EmailTemplate)) }; IEmailTemplateService service = new EmailTemplateService(configuration); return service; }
public async Task Invoke(HttpContext context) { var requestPath = context.Request.Path.Value; if (!String.IsNullOrWhiteSpace(requestPath) && requestPath.Equals("/", StringComparison.CurrentCultureIgnoreCase)) { requestPath = "/Default.cshtml"; } var fileInfo = _env.WebRootFileProvider.GetFileInfo(requestPath); if (fileInfo.Exists && CanHandle(fileInfo)) { context.Response.StatusCode = 200; context.Response.ContentType = "text/html"; var dynamicViewBag = new DynamicViewBag(); dynamicViewBag.AddValue("IsHttps", context.Request.IsHttps); var config = new TemplateServiceConfiguration(); // .. configure your instance config.TemplateManager = new ResolvePathTemplateManager(new[] { _env.MapPath("/Shared") }); var service = RazorEngineService.Create(config); service.WithContext(new RazorPageContext { HttpContext = context }); Engine.Razor = service; string result; if (Engine.Razor.IsTemplateCached(fileInfo.PhysicalPath, null)) { result = Engine.Razor.Run(fileInfo.PhysicalPath, null, null, dynamicViewBag); } else { using (var stream = fileInfo.CreateReadStream()) { using (var reader = new StreamReader(stream)) { var razor = await reader.ReadToEndAsync(); result = Engine.Razor.RunCompile(razor, fileInfo.PhysicalPath, null, null, dynamicViewBag); } } } await context.Response.WriteAsync(result); return; } await _next(context); }
/// <summary> /// Gets an instance of the Razor Engine Service /// </summary> /// <returns>RazorEngine Service</returns> public static IRazorEngineService getInstance() { if (service == null) { TemplateServiceConfiguration config = new TemplateServiceConfiguration(); config.Language = RazorEngine.Language.CSharp; service = RazorEngineService.Create(config); } return service; }
static Render() { var config = new TemplateServiceConfiguration { BaseTemplateType = typeof(HtmlTemplateBase<>) }; var service = new TemplateService(config); Razor.SetTemplateService(service); Razor.Compile(Resources.FormattedSingleFile(), "singleFile"); Razor.Compile(Resources.Directory(), "directory"); }
/// <summary> /// 删除提示信息: /// RazorEngine: We can't cleanup temp files if you use RazorEngine on the default Appdomain. /// </summary> public static void Init() { //参考地址 //https://github.com/Antaris/RazorEngine/issues/244 // var config = new TemplateServiceConfiguration(); config.DisableTempFileLocking = true; // loads the files in-memory (gives the templates full-trust permissions) config.CachingProvider = new DefaultCachingProvider(t => { }); //disables the warnings // Use the config Engine.Razor = RazorEngineService.Create(config); // new API Razor.SetTemplateService(new TemplateService(config)); // legacy API }
public static void GenerateProxyJs(List<Type> svTypes, List<Type> itTypes ) { if (svTypes == null || svTypes.Count == 0) return; var config = new TemplateServiceConfiguration {EncodedStringFactory = new RawStringFactory()}; var service = RazorEngineService.Create(config); Engine.Razor = service; var template = ReadTemplate("ServicesTemplate.cshtml"); var model = Build(svTypes, itTypes); var result = Engine.Razor.RunCompile(template, "Services", typeof(List<ServiceWithMethod>), model); var savePath = AppPath.GetRelativeDir("Content\\Lib\\miniAbp\\auto\\"); File.WriteAllText(savePath + "mabpProxy.js", result, Encoding.UTF8); }
public void TemplateRunner_CanRunTemplateString() { const string template = "Hello @Model.Forename, welcome to RazorEngine!"; var configuration = new TemplateServiceConfiguration { Debug = true }; using (var service = RazorEngineService.Create(configuration)) { var runner = service.CompileRunner<Person>(template); var output = runner.Run(new Person { Forename = "Max" }); Assert.AreEqual("Hello Max, welcome to RazorEngine!", output); } }
public string Parse(string rootView, object model) { var config = new TemplateServiceConfiguration(); config.DisableTempFileLocking = true; config.CachingProvider = new DefaultCachingProvider(s => { }); using (engine = RazorEngineService.Create(config)) { LoadTemplates(); var result = engine.Run(rootView, null, model); return result; } }
public static void UseRazor(this HttpConfiguration config) { TemplateServiceConfiguration templateConfig = new TemplateServiceConfiguration(); templateConfig.Debug = true; Engine.Razor = RazorEngineService.Create(templateConfig); TryGetRootPath(config); var rootPath = config.RootPath(); var cshtmls = Directory.GetFiles(rootPath, "*.cshtml", SearchOption.AllDirectories); foreach (var item in cshtmls) { var name = item.Replace(rootPath, "~").Replace("\\","/"); Engine.Razor.AddTemplate(name, File.ReadAllText(item)); } }
static void Main(string[] args) { var config = new TemplateServiceConfiguration(); var xml = new XmlTemplateServiceConfiguration("myapp"); foreach (var ns in xml.Namespaces) { config.Namespaces.Add(ns); } Engine.Razor = RazorEngineService.Create(config); if (!Engine.Razor.IsTemplateCached("test", null)) { } }
public static void Main(string[] args) { Console.WriteLine ("Initialization"); Init (args); var viewModel = new ViewModel { Model = model, Declarations = declarations }; Console.WriteLine ("Setuping template engine"); string viewPathTemplate = "../../Views/{0}"; var templateConfig = new TemplateServiceConfiguration(); templateConfig.Resolver = new DelegateTemplateResolver(name => { string resourcePath = string.Format(viewPathTemplate, name); return File.ReadAllText (resourcePath); }); Razor.SetTemplateService(new TemplateService(templateConfig)); // string template = File.ReadAllText ("./Templates/GoalModel.cshtml"); // string result = Razor.Parse(template, new { }); Console.WriteLine ("Copying common files"); if (Directory.Exists ("./Report")) { Directory.Delete ("./Report", true); } Directory.CreateDirectory ("Report"); DirectoryCopy ("../../Content", "./Report/Content", true); Console.WriteLine ("Building goal page"); string result = Razor.Resolve ("GoalModel.cshtml", viewModel).Run(new ExecuteContext()); File.WriteAllText ("./Report/goals.html", result); Console.WriteLine ("Building agent page"); result = Razor.Resolve("AgentModel.cshtml", viewModel).Run(new ExecuteContext()); File.WriteAllText ("./Report/agents.html", result); Console.WriteLine ("Building obstacle page"); result = Razor.Resolve("ObstacleModel.cshtml", viewModel).Run(new ExecuteContext()); File.WriteAllText ("./Report/obstacles.html", result); Console.WriteLine ("Building domain property page"); result = Razor.Resolve("DomPropModel.cshtml", viewModel).Run(new ExecuteContext()); File.WriteAllText ("./Report/domprops.html", result); Console.WriteLine ("Building domain hypothesis page"); result = Razor.Resolve("DomHypModel.cshtml", viewModel).Run(new ExecuteContext()); File.WriteAllText ("./Report/domhyps.html", result); }
static RazorPageParser() { Singleton = new Lazy<IPageParser>( () => new RazorPageParser(), true); var rconf = new TemplateServiceConfiguration(); rconf.BaseTemplateType = typeof(TemplateBase<>); rconf.Namespaces.Add("WiGi"); rconf.Namespaces.Add("WiGi.Account"); rconf.Namespaces.Add("WiGi.Wiki"); Razor.SetTemplateService(new TemplateService(rconf)); }
public FactoryWorkerRazor() { Templates = new Dictionary<string, string>(); var config = new TemplateServiceConfiguration { EncodedStringFactory = new RawStringFactory(), BaseTemplateType = typeof(FactoryWorkerTemplateBase), ReferenceResolver = new FactoryWorkerReferenceResolver(), TemplateManager = new DelegateTemplateManager(_ => Templates[_]), Debug = true }; var service = RazorEngineService.Create(config); Engine.Razor = service; }
public static string Parse(string template, GlobalVariable par, TableDef tab,string cacheName) { string result = ""; //DynamicViewBag vb = new DynamicViewBag(); //vb.GetDynamicMemberNames() TemplateServiceConfiguration config = new TemplateServiceConfiguration(); config.BaseTemplateType = typeof(HtmlTemplateBase<>); TemplateService svc = new TemplateService(config); Razor.SetTemplateService(svc); result = Razor.Parse(template, new { GlobalVariable = par, Table = tab },cacheName); return result; }
/// <summary> /// Initialises a new instance of <see cref="FluentConfigurationBuilder"/>. /// </summary> /// <param name="config">The default configuration that we build a new configuration from.</param> public FluentConfigurationBuilder(TemplateServiceConfiguration config) { //Contract.Requires(config != null); _config = config; }