本文整理汇总了C#中TemplateService类的典型用法代码示例。如果您正苦于以下问题:C# TemplateService类的具体用法?C# TemplateService怎么用?C# TemplateService使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
TemplateService类属于命名空间,在下文中一共展示了TemplateService类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateTemplateService
/// <summary>
/// Creates an instance of a <see cref="TemplateService"/>.
/// </summary>
/// <param name="configuration">The <see cref="TemplateServiceConfigurationElement"/> that represents the configuration.</param>
/// <param name="defaultNamespaces">The enumerable of namespaces to add as default.</param>
/// <returns>A new instance of <see cref="TemplateService"/>.</returns>
public static TemplateService CreateTemplateService(TemplateServiceConfigurationElement configuration, IEnumerable<string> defaultNamespaces = null)
{
if (configuration == null)
throw new ArgumentNullException("configuration");
ILanguageProvider provider = null;
MarkupParser parser = null;
Type templateBaseType = null;
if (!string.IsNullOrEmpty(configuration.LanguageProvider))
provider = (ILanguageProvider)GetInstance(configuration.LanguageProvider);
if (!string.IsNullOrEmpty(configuration.MarkupParser))
parser = (MarkupParser)GetInstance(configuration.MarkupParser);
if (!string.IsNullOrEmpty(configuration.TemplateBase))
templateBaseType = GetType(configuration.TemplateBase);
var namespaces = configuration.Namespaces
.Cast<NamespaceConfigurationElement>()
.Select(n => n.Namespace);
if (defaultNamespaces != null)
{
namespaces = defaultNamespaces
.Concat(namespaces)
.Distinct();
}
var service = new TemplateService(provider, templateBaseType, parser);
foreach (string ns in namespaces)
service.Namespaces.Add(ns);
return service;
}
示例2: Main
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 ="[email protected]", 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();
}
示例3: ConnectionList
/// <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;
}
示例4: StronglyTypedModel
static void StronglyTypedModel()
{
var welcomeEmailTemplatePath = Path.Combine(TemplateFolderPath, "WelcomeEmailStronglyTyped.cshtml");
// Generate the email body from our email template
var stronglyTypedModel = new UserModel() { Name = "Sarah", Email = "[email protected]", IsPremiumUser = false };
var templateService = new TemplateService();
var emailHtmlBody = templateService.Parse(File.ReadAllText(welcomeEmailTemplatePath), stronglyTypedModel, null, null);
// Send the email
var email = new MailMessage()
{
Body = emailHtmlBody,
IsBodyHtml = true,
Subject = "Welcome (generated from strongly-typed model)"
};
email.To.Add(new MailAddress(stronglyTypedModel.Email, stronglyTypedModel.Name));
// The From field will be populated from the app.config value by default
var smtpClient = new SmtpClient();
smtpClient.Send(email);
// In the real world, you'll probably want to use async version instead:
// await smtpClient.SendMailAsync(email);
}
示例5: TemplateService_CanSupportCustomActivator_WithUnity
public void TemplateService_CanSupportCustomActivator_WithUnity()
{
#if RAZOR4
Assert.Ignore("We need to add roslyn to generate custom constructors!");
#endif
var container = new UnityContainer();
container.RegisterType(typeof(ITextFormatter), typeof(ReverseTextFormatter));
var config = new TemplateServiceConfiguration
{
Activator = new UnityTemplateActivator(container),
BaseTemplateType = typeof(CustomTemplateBase<>)
};
#pragma warning disable 0618 // Fine because we still want to test if
using (var service = new TemplateService(config))
#pragma warning restore 0618 // Fine because we still want to test if
{
const string template = "<h1>Hello @Format(Model.Forename)</h1>";
const string expected = "<h1>Hello ttaM</h1>";
var model = new Person { Forename = "Matt" };
string result = service.Parse(template, model, null, null);
Assert.That(result == expected, "Result does not match expected: " + result);
}
}
示例6: DynamicModel
static void DynamicModel()
{
var welcomeEmailTemplatePath = Path.Combine(TemplateFolderPath, "WelcomeEmailDynamic.cshtml");
// Generate the email body from our email template
// Note: the RazorEngine library supports using an anonymous type as a model without having to transform it to an Expando object first.
var anonymousModel = new { Name = "Sarah", Email = "[email protected]", IsPremiumUser = false };
var templateService = new TemplateService();
var emailHtmlBody = templateService.Parse(File.ReadAllText(welcomeEmailTemplatePath), anonymousModel, null, null);
// Send the email
var email = new MailMessage()
{
Body = emailHtmlBody,
IsBodyHtml = true,
Subject = "Welcome (generated from dynamic model)"
};
email.To.Add(new MailAddress(anonymousModel.Email, anonymousModel.Name));
// The From field will be populated from the app.config value by default
var smtpClient = new SmtpClient();
smtpClient.Send(email);
}
示例7: Render
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;
}
}
示例8: Main
public static void Main(string[] args)
{
if (args.Length >= 2)
{
var fileEncoding = Encoding.UTF8;
var config = new FluentTemplateServiceConfiguration(c => c.WithEncoding(RazorEngine.Encoding.Raw));
using (var myConfiguredTemplateService = new TemplateService(config))
{
RazorEngine.Razor.SetTemplateService(myConfiguredTemplateService);
if (args.Length > 3 && args[2] == "-r")
{
Assembly.LoadFrom(args[3]);
}
string razorContent = File.ReadAllText(args[0], fileEncoding);
string outputContent = RazorEngine.Razor.Parse(razorContent);
File.WriteAllText(args[1], outputContent, fileEncoding);
}
}
else
{
Console.WriteLine("Usage: RazorParser fileName.cshtml output.[js|ts|css|less] -r Referenced.dll");
}
Console.WriteLine("Done");
}
示例9: IntegrationTest
//[Test]
public void IntegrationTest()
{
const string templatePath = @"..\..\Test Templates\Modeled Basic Template.odt";
const string reportPath = @"..\..\Generated Reports\Very Basic Report.odt";
const string expectedReportPath = @"..\..\Expected Report Outputs\Very Basic Report.odt";
var templateFactory = new TemplateFactory();
var zipFactory = new ZipFactory();
var readerFactory = new StreamReaderWrapperFactory();
var zipHandlerService = new ZipHandlerService( readerFactory );
var buildOdfMetadataService = new BuildOdfMetadataService();
var xmlNamespaceService = new XmlNamespaceService();
var xDocumentParserService = new XDocumentParserService();
var odfHandlerService = new OdfHandlerService( zipFactory, zipHandlerService, buildOdfMetadataService,
xmlNamespaceService, xDocumentParserService );
var templateService = new TemplateBuilderService( templateFactory, odfHandlerService,
xmlNamespaceService, xDocumentParserService );
var document = File.ReadAllBytes( templatePath );
var template = templateService.BuildTemplate( document );
var razorTemplateService = new TemplateService();
var compileService = new CompileService( razorTemplateService );
compileService.Compile( template, "Template 1" );
var reportService = new ReportGeneratorService( new ZipFactory(), razorTemplateService );
using( var report = new FileStream( reportPath, FileMode.Create ) )
{
reportService.BuildReport( template, new BasicModel {Name = "Fancypants McSnooterson"}, report );
}
var diffs = GetDifferences( expectedReportPath, reportPath );
var thereAreDifferences = diffs.HasDifferences();
Assert.That( !thereAreDifferences );
}
示例10: GetEmailBody
private static string GetEmailBody(string template, object data)
{
string path = HttpContext.Current.Server
.MapPath("~/") + template;
TemplateService templateService = new TemplateService();
var emailHtmlBody = templateService.Parse(File.ReadAllText(path), data, null, null);
return PreMailer.Net.PreMailer.MoveCssInline(emailHtmlBody, true).Html;
}
示例11: ProcessSubContent
private void ProcessSubContent(TemplateService service, Match match, dynamic model)
{
var subName = match.Groups[1].Value; // got an include/layout match?
var subContent = GetContent(subName); // go get that template then
ProcessContent(subContent, service, model); // recursively process it
service.GetTemplate(subContent, model, subName); // then add it to the service
}
示例12: Issue11_TemplateServiceShouldCompileModellessTemplate
public void Issue11_TemplateServiceShouldCompileModellessTemplate()
{
using (var service = new TemplateService())
{
const string template = "<h1>Hello World</h1>";
service.Compile(template, null, "issue11");
}
}
示例13: TestEnginePreparation
public void TestEnginePreparation()
{
TemplateService templateService = new TemplateService();
templateService.PrepareEngine += new System.Action<Jint.Engine>(templateService_PrepareEngine);
Assert.AreEqual("pwet", templateService.Process("<% write('pwet'); %>"));
templateService = new TemplateService(TemplateMode.HtmlEscaped);
templateService.PrepareEngine += new System.Action<Jint.Engine>(templateService_PrepareEngine);
Assert.AreEqual("pwet", templateService.Process("<% write2('pwet'); %>"));
}
示例14: OnExecute
protected override async Task OnExecute()
{
var dc = GetDatacenter(required: true);
var service = dc.GetService(Service);
if (service == null)
{
await Console.WriteErrorLine(Strings.Config_GenerateCommand_NoSuchService, Service, dc.FullName);
return;
}
// Get the config template for this service
if (dc.Environment.ConfigTemplates == null)
{
await Console.WriteErrorLine(Strings.Config_GenerateCommand_NoTemplateSource, dc.Environment.FullName);
}
else
{
if (!String.Equals(dc.Environment.ConfigTemplates.Type, FileSystemConfigTemplateSource.AbsoluteAppModelType, StringComparison.OrdinalIgnoreCase))
{
await Console.WriteErrorLine(Strings.Config_GenerateCommand_UnknownConfigTemplateSourceType, dc.Environment.ConfigTemplates.Type);
}
var configSource = new FileSystemConfigTemplateSource(dc.Environment.ConfigTemplates.Value);
var configTemplate = configSource.ReadConfigTemplate(service);
if (String.IsNullOrEmpty(configTemplate))
{
await Console.WriteErrorLine(Strings.Config_GenerateCommand_NoTemplate, service.FullName);
}
else
{
var secrets = await GetEnvironmentSecretStore(Session.CurrentEnvironment);
// Render the template
var engine = new TemplateService(new TemplateServiceConfiguration()
{
BaseTemplateType = typeof(ConfigTemplateBase),
Language = Language.CSharp
});
await Console.WriteInfoLine(Strings.Config_GenerateCommand_CompilingConfigTemplate, service.FullName);
engine.Compile(configTemplate, typeof(object), "configTemplate");
await Console.WriteInfoLine(Strings.Config_GenerateCommand_ExecutingTemplate, service.FullName);
string result = engine.Run("configTemplate", new ConfigTemplateModel(secrets, service), null);
// Write the template
if (String.IsNullOrEmpty(OutputFile))
{
await Console.WriteDataLine(result);
}
else
{
File.WriteAllText(OutputFile, result);
await Console.WriteInfoLine(Strings.Config_GenerateCommand_GeneratedConfig, OutputFile);
}
}
}
}
示例15: Parse
public string Parse()
{
TemplateService templateService = new TemplateService();
string templateName = "TestTemplate";
string body = "@model dynamic" + Environment.NewLine + "<html>Hello, @Model.CustomerName!</html>";
dynamic model = new { CustomerName = "Girish" };
var result = templateService.Parse(body, model, null, templateName);
return result;
}