public void Send(string to) { try { if (string.IsNullOrEmpty(From)) { throw new Exception("'From' cannot be empty"); } if (string.IsNullOrEmpty(to)) { throw new ArgumentException(nameof(to)); } var code = _verificationCode.Generate(out var result); var text = _parser.Parse(code); TwilioClient.Init(_configuration.AccountSid, _configuration.AuthToken); var message = MessageResource.Create( from: new PhoneNumber(From), to: new PhoneNumber(to), body: text ); MessageSentHandler?.Invoke(result, message); } catch (Exception ex) { VerificationCodoeExceptionHandler?.Invoke(ex); } }
private void SetRequestLine(HttpRequestMessage request, MethodDescriptor methodDescriptor, IDictionary <string, string> templateArguments) { var requestLineTemplate = methodDescriptor.RequestLine; var requestLine = requestLineTemplate.NeedParse ? _templateParser.Parse(requestLineTemplate.Template, templateArguments) : requestLineTemplate.Template; request.RequestUri = new Uri(requestLine, UriKind.RelativeOrAbsolute); }
/// <summary> /// Parses and validates the template content /// </summary> /// <param name="templateContent">The template content</param> /// <returns>The parsed template</returns> private Template ParseTemplate ( string templateContent ) { var parsedTemplate = _parser.Parse ( templateContent ); var validationResults = _validator.ValidateTemplate ( parsedTemplate ); if (false == validationResults.IsValid) { throw new NettleValidationException ( validationResults.Errors ); } return(parsedTemplate); }
//public static LoveTemplate Build<T>(ITemplateRenderer renderer, IViewViewModelPair<T> pair) //{ // return renderer.RenderTemplate(pair); //} public static LoveTemplate Build <T>(ITemplateParser parser, IMarkupExpressionEvaluator evaluator, IViewViewModelPair <T> pair) { var syntaxTree = parser.Parse(pair.ViewSource); syntaxTree.DecorateTree(); var expressions = new List <LoveNode>(); foreach (var n in syntaxTree.Flatten()) { if (n is LoveMarkupExpression) { expressions.Add(n); } } foreach (var n in expressions) { var expression = n as LoveMarkupExpression; var evaluated = evaluator.Evaluate(expression, pair.Model); n.Parent.Replace(expression, evaluated); } var t = new LoveTemplate(syntaxTree); // Redecorate tree t._syntaxTree.DecorateTree(); var tText = t.ToString(); return(t); }
/// <summary> /// Loads a single file and returns the template /// </summary> /// <param name="fileName">The file to load</param> /// <param name="parser">The parser to use to parse the template file</param> /// <param name="templatePath">Optional template path registers the template /// with the Name Manager. Also causes the template to be periodically /// reloaded</param> /// <returns>The template that was loaded</returns> public ITemplate LoadFile(string fileName, ITemplateParser parser, string templatePath = null) { Encoding encoding; var buffer = LoadFileContents(fileName, out encoding); var template = parser.Parse(new[] { new TemplateResource { Content = buffer, Encoding = encoding } }, Package); if (!string.IsNullOrEmpty(templatePath)) { _nameManager.Register(template, templatePath); Reload(new TemplateInfo { FileNames = new[] { fileName }, Parser = parser, TemplatePath = templatePath, Checksum = new[] { CalculateChecksum(buffer) } }); } template.IsStatic = !ReloadInterval.HasValue; return(template); }
public void Send(string to) { try { if (string.IsNullOrEmpty(From)) { throw new Exception("'From' cannot be empty"); } if (string.IsNullOrEmpty(to)) { throw new ArgumentException(nameof(to)); } var code = _verificationCode.Generate(out var result); var text = _parser.Parse(code); var message = new MimeMessage(); message.From.Add(new MailboxAddress(From)); message.To.Add(new MailboxAddress(to)); message.Body = new TextPart { Text = text }; using (var emailClient = new SmtpClient()) { emailClient.Connect(_configuration.SmtpServer, _configuration.SmtpPort, _configuration.UseSsl); if (AuthenticateHandlerDelegate != null) { AuthenticateHandlerDelegate.Invoke(emailClient); } else { if (_configuration.RemoveXOauth2) { emailClient.AuthenticationMechanisms.Remove("XOAUTH2"); } emailClient.Authenticate(_configuration.SmtpUsername, _configuration.SmtpPassword); } emailClient.Send(message); MessageSentHandler?.Invoke(result, message); emailClient.Disconnect(true); } } catch (Exception ex) { VerificationCodoeExceptionHandler?.Invoke(ex); } }
public static string Parse(this ITemplateParser parser, string contengt, IDictionary <string, string> arguments) { var context = new ParseContext(new TemplateString(contengt, TemplateUtilities.GetVariables(contengt)), arguments); parser.Parse(context); return(context.Result); }
private void ParseTemplate(ITemplate template, ITokenDictionary tokenDictionary) { foreach (var file in GetInstalledFiles(template).Where(f => f.IsTextFile())) { var parsed = _templateParser.Parse(tokenDictionary, _fileManager.ReadAllText(file.FullName)); _fileManager.WriteAllText(file.FullName, parsed); } }
public Action <RenderingContext, T> Compile <T>(string templateId, ITemplateParser parser, TextReader templateContents) { if (templateContents == null) { throw new ArgumentNullException("templateContents"); } var syntaxTree = parser.Parse(templateId, templateContents, typeof(T), _memberLocator, _helperHandlers); return(CompileFromTree <T>(syntaxTree)); }
private ICompiledTemplate CompileTemplate(string text) { try { return(_templateParser.Parse(text)); } catch (TemplateParserException ex) { throw new ViciMvcException("Error parsing template " + Path.GetFileName(_fileName), ex); } }
public async Task Should_Send_Templated_Email_Async() { // Arrange _server.ClearReceivedEmail(); EmailSender emailSender = CreateEmailSender(); var confirmEmailTemplate = new ConfirmEmailTemplate(); var expectedRecipient = "*****@*****.**"; var expectedSubject = "Expected subject"; var expectedBody = $"<title>{expectedSubject}</title>"; _templateParser.Parse(Arg.Any <ITemplate>()).Returns(expectedBody); // Act await emailSender.SendTemplatedEmailAsync(confirmEmailTemplate, expectedRecipient); // Assert _server.ReceivedEmailCount.Should().Be(1); SmtpMessage receivedMail = _server.ReceivedEmail.First(); receivedMail.MessageParts[0].BodyData.Should().Be(expectedBody); receivedMail.ToAddresses.First().Address.Should().Be(expectedRecipient); receivedMail.Headers.Get("Subject").Should().Be(expectedSubject); }
public async Task SendTemplatedEmailAsync(ITemplate templateData, string receipientMail, IList <EmailAttachment> attachments = null) { var templatedBody = _templateParser.Parse(templateData); var subject = _emailConfig.DefaultSubject; if (templatedBody.Contains("<title>") && templatedBody.Contains("</title>")) { subject = templatedBody.Split("<title>")[1].Split("</title>")[0]; } var mailMessage = new EmailMessage(new string[] { receipientMail }, subject, templatedBody, attachments); await SendEmailAsync(mailMessage); }
public void Send(string to) { if (string.IsNullOrEmpty(From)) { throw new Exception("'From' cannot be empty"); } if (string.IsNullOrEmpty(to)) { throw new ArgumentException(nameof(to)); } var code = _verificationCode.Generate(out var result); var text = _parser.Parse(code); TwilioClient.Init(_configuration.AccountSid, _configuration.AuthToken); var message = CallResource.Create( from: new PhoneNumber(From), to: new PhoneNumber(to), url: new Uri( $"{Url ?? "http://twimlets.com/message?" + WebUtility.UrlEncode("Message[0]=")}{text}" ) ); MessageSentHandler?.Invoke(result, message); }
public async Task <string> Generate(object data, EmailTemplateOptions options) { var provider = _templateProviders.FirstOrDefault(templateProvider => templateProvider.CanHandle(options)); if (provider == null) { return(string.Empty); } var templateContent = await provider.GetContents(options); var parsedContent = await _templateParser.Parse(templateContent, data); return(parsedContent); }
public BinaryTemplate Compile(string template, bool optimizationHtmlCode = false) { var compiler = new CSharpCodeProvider(); var parms = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true }; parms.ReferencedAssemblies.Add("System.dll"); parms.ReferencedAssemblies.Add("System.Core.dll"); var templateContent = _templateParser.Parse(template, optimizationHtmlCode); var cs = CSharp().Replace("{0}", templateContent.Content); var result = compiler.CompileAssemblyFromSource(parms, cs); var builderType = result.CompiledAssembly.GetType("BinaryTemplates.BinaryBuilder"); var instance = Activator.CreateInstance(builderType); var addHanlder = (Action <object, MethodInfo, string>)Delegate.CreateDelegate(typeof(Action <object, MethodInfo, string>), instance, "AddHandler"); var clearHandler = (Action)Delegate.CreateDelegate(typeof(Action), instance, "ClearHandlers"); var renderHandler = (Func <Dictionary <string, object>, string>)Delegate.CreateDelegate(typeof(Func <Dictionary <string, object>, string>), instance, "Render"); return(new BinaryTemplate(new BinaryBuilderMembers(addHanlder, clearHandler, renderHandler, templateContent.FunctionsContainer))); }
/// <summary> /// Loads a set of files that comprise the parts of a single template /// </summary> /// <param name="fileNames">The files to load</param> /// <param name="parser">The parser to use to parse the template files</param> /// <param name="templatePath">Optional template path registers the template /// with the Name Manager. Also causes the template to be periodically /// reloaded</param> /// <returns>The template that was loaded</returns> public ITemplate LoadFileSet(string[] fileNames, ITemplateParser parser, string templatePath = null) { var resources = new TemplateResource[fileNames.Length]; for (var i = 0; i < fileNames.Length; i++) { resources[i] = new TemplateResource { Content = LoadFileContents(fileNames[i], out Encoding encoding) }; resources[i].Encoding = encoding; resources[i].ContentType = ContentTypeFromExt(Path.GetExtension(fileNames[i])); } var template = parser.Parse(resources, Package); if (!string.IsNullOrEmpty(templatePath)) { _nameManager.Register(template, templatePath); var templateInfo = new TemplateInfo { FileNames = fileNames, Parser = parser, TemplatePath = templatePath, Checksum = new byte[fileNames.Length][] }; for (var i = 0; i < fileNames.Length; i++) { templateInfo.Checksum[i] = CalculateChecksum(resources[i].Content); } Reload(templateInfo); } template.IsStatic = !ReloadInterval.HasValue; return(template); }
/// <summary> /// Loads a template from a URI /// </summary> /// <param name="uri">The URI to load from</param> /// <param name="parser">The parser to use to parse the template</param> /// <param name="templatePath">Optional path to register the template at /// with the name manager</param> /// <returns>The template that was loaded</returns> public ITemplate LoadUri(Uri uri, ITemplateParser parser, string templatePath) { if (uri == null) { throw new ArgumentNullException("uri"); } if (parser == null) { throw new ArgumentNullException("parser"); } if (!uri.IsAbsoluteUri) { throw new ArgumentException("The Uri must be absolute", "uri"); } Encoding encoding; var buffer = LoadUriContents(uri, out encoding); var template = parser.Parse(new[] { new TemplateResource { Content = buffer, Encoding = encoding } }, Package); if (!string.IsNullOrEmpty(templatePath)) { _nameManager.Register(template, templatePath); Reload(new TemplateInfo { Uri = uri, Parser = parser, TemplatePath = templatePath, Checksum = CalculateChecksum(buffer) }); } template.IsStatic = !ReloadInterval.HasValue; return(template); }
protected override async Task InitializeRequestAsync(GoRequest request, IReadOnlyList <object> arguments) { var methodDescriptor = RequestContext.MethodDescriptor; var formatResult = await FormatAsync(methodDescriptor.Parameters, _keyValueFormatterFactory, arguments); var urlTemplate = _entry.UrlTemplate; request.Method = methodDescriptor.Method; request.Scheme = urlTemplate.Scheme; request.Host = urlTemplate.Host; request.Port = urlTemplate.Port; var path = urlTemplate.Path; // render path if (path.Contains("{") && path.Contains("}")) { path = _templateParser.Parse(path, formatResult[ParameterTarget.Path].ToDictionary(i => i.Key, i => i.Value.ToString())); } request.Path = path; if (urlTemplate.HasQuery()) { var queryString = urlTemplate.QueryString; var query = QueryHelpers.ParseNullableQuery(queryString); if (query != null && query.Any()) { foreach (var item in query) { request.AddQuery(item.Key, item.Value); } } } await BuildBodyAsync(request, _codec.Encoder, methodDescriptor.Parameters, arguments); BuildQueryAndHeaders(request, formatResult); }
public async Task <string> FormatEmailMessage <TModel>(string templateName, TModel model) where TModel : class { var template = _templateProvider.GetTemplate(templateName); return(await _templateParser.Parse(template, model)); }
/// <summary> /// Renders the Template view and builds a <see cref="MailMessage" />. Does not send the Template. /// </summary> /// <param name="emailTemplate">The Template to render.</param> /// <returns>A <see cref="MailMessage" /> containing the rendered Template.</returns> private MailMessage ToMailMessage(EmailTemplate emailTemplate) { var content = _renderer.Render(emailTemplate); return(_templateParser.Parse(content, emailTemplate)); // template to mailmessage (+add attachments) }
private void ParseAndOutputByTables(IDatabase database, ProjectConfig config, List <string> filterTables = null, List <string> withoutTables = null) { try { config.Database = database; List <Table> tables = null; string msg = ""; tables = DbLoader.GetTableInfos(database, config, filterTables, withoutTables, out msg); OnLogReport(msg); OutputContext context = new OutputContext(); config.LastOutputContext = context; context.Tables = tables; // context.Mappers = mapperDict; context.ProjectConfig = config; context.ParserConfig = _parseConfig; var enabledTemplates = config.GeneraterConfigs.Where(p => p.Enabled == true); string templateContent = "", templateKey = "", modelName = "", outputFileName = "", stepmsg = "", outputContent = ""; //清空上一次的生成数据 string projectDir = DbLoader.GetProjectDirectory(config);// config.Database.Config.CodeGenBaseDirectory;// DbLoader.GetProjectDirectory(config); try { var files = Directory.GetFiles(projectDir, "", SearchOption.AllDirectories); foreach (var item in files) { if (item != "") { System.IO.File.Delete(item); } } var dirs = Directory.GetDirectories(projectDir); foreach (var dir in dirs) { Directory.Delete(dir); } } catch (Exception) { } OnLogReport("EnabledTemplates count:" + enabledTemplates.Count() + " -> (" + enabledTemplates.Select(p => p.Name).Join(", ") + ")"); foreach (var template in enabledTemplates) { //CheckCancellation(); try { templateContent = GetTemplate(template); if (string.IsNullOrEmpty(templateContent)) { database.LogHelper.Debug("TemplateContent is empty,skip at :" + template.TemplateFileName); continue; //throw new ArgumentException("模板内容不能为空!"); } context.GeneraterConfig = template; // result.FileName = template.TemplateFileName; templateKey = DbLoader.GetTemplateKey(template.Name, template.TemplateFileName); string reallyOutputFileName = ""; var outType = template.OutputType; OnLogReport("Starting generate template:" + template.Name + " , outputType:" + template.OutputType.ToString() + " , templateKey:" + templateKey); if (outType == OutputType.Table) { foreach (Table table in context.Tables) { try { modelName = table.ClassName; context.ModelName = modelName; context.OutputFileName = DbLoader.FormatFileName(config, template, modelName, modelName); table.CurrentOutputContext = context; var Model = table; outputContent = parser.Parse <Table>(templateContent, templateKey, Model); reallyOutputFileName = context.RealOutputFileName; parser.OutputResult(reallyOutputFileName, outputContent, template.Encoding, template.Append); //result.ParseResult.Add( parser.ParseAndOutput<Table>(outputFileName, templateContent, templateKey, table, template.Encoding, template.Append)); stepmsg = "template = " + template.Name + " , table = " + table.Name + string.Format(" , Generate in Template {0}, Table Model {1} is OK : {2}", template.Name, table.Name, reallyOutputFileName); OnLogReport(stepmsg); } catch (Exception ex11) { database.LogHelper.Error(ex11); stepmsg = "template = " + template.Name + " , table = " + table.Name + " , Error: " + ex11.Message; OnLogReport(stepmsg); } } } else if (outType == OutputType.OutputContext) { modelName = template.Name; //string.IsNullOrEmpty(context.Owner) ? context.ProjectConfig.Name : context.Owner; context.OutputFileName = DbLoader.FormatFileName(config, template, modelName, modelName); //outputFileName = context.RealOutputFileName;// DbLoader.GetOutputFileName(config, template, modelName); outputContent = parser.Parse <OutputContext>(templateContent, templateKey, context); parser.OutputResult(context.RealOutputFileName, outputContent, template.Encoding, template.Append); //result.ParseResult.Add(outputContent); //result.ParseResult.Add(parser.ParseAndOutput<OutputContext>(context.RealOutputFileName, templateContent, templateKey, context, template.Encoding, template.Append)); stepmsg = string.Format(" Template {0}, OutputContext Model {1} is OK", template.Name, modelName); //result.StepResult.Add(stepmsg); OnLogReport(stepmsg); } stepmsg = string.Format(" {0} End", template.Name); OnLogReport(stepmsg); } catch (Exception ex) { //result.ErrorMessages.Add(ex.ToFriendlyString()); //result.ErrorMessages.Add(ErrorDetail.CreateByContent(ex.Message)); database.LogHelper.Error(ex); stepmsg = "Error: " + ex.Message; OnLogReport(stepmsg); } } } catch (Exception ex) { throw new Exception("[ParseAndOutputByTables Error]:" + ex + ex.StackTrace + ex.Source, ex.InnerException); } }
public void Render(ViewContext viewContext, TextWriter writer) { if (viewContext == null) { throw new ArgumentNullException("viewContext"); } // Copy data from the view context over to DotLiquid var localVars = new Hash(); if (viewContext.ViewData.Model != null) { var model = viewContext.ViewData.Model; if (model is ILiquidizable) { model = ((ILiquidizable)model).ToLiquid(); } if (model is Hash) { localVars = model as Hash; } else if (model is IDictionary <string, object> ) { var modelDictionary = model as IDictionary <string, object>; foreach (var item in modelDictionary.Keys) { localVars.Add(item, modelDictionary[item]); } } } foreach (var item in viewContext.ViewData) { localVars.Add(Template.NamingConvention.GetMemberName(item.Key), item.Value); } foreach (var item in viewContext.TempData) { localVars.Add(Template.NamingConvention.GetMemberName(item.Key), item.Value); } var renderParams = new RenderParameters { LocalVariables = Hash.FromDictionary(localVars) }; var template = _parser.Parse(this.ViewResult); if (this.MasterViewResult == null) { template.RenderWithTracing(writer, renderParams); } else // add master { var renderedContents = template.RenderWithTracing(renderParams); // read layout from context var layout = template.Registers["layout"].ToNullOrString(); var layoutPath = layout == null ? this.MasterViewResult : _locator.LocateView(layout); // render master with contents var masterTemplate = _parser.Parse(layoutPath); var headerTemplate = _parser.Parse(_locator.LocatePartialView("content_header")); var renderedHeaderContents = headerTemplate.RenderWithTracing(renderParams); renderParams.LocalVariables.Add("content_for_layout", renderedContents); renderParams.LocalVariables.Add("content_for_header", renderedHeaderContents); masterTemplate.RenderWithTracing(writer, renderParams); } }