public SMSVerificationCodeProvider(ITwilioConfiguration configuration,
                                    IVerificationCode verificationCode = null, ITemplateParser parser = null)
 {
     _configuration    = configuration;
     _verificationCode = verificationCode ?? new GeneralVerificationCode();
     _parser           = parser;
 }
Example #2
0
        //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);
        }
Example #3
0
 public FeignInterceptor(ClientDescriptor clientDescriptor, IHttpClientFactory httpClientFactory, IParameterExpanderLocator parameterExpanderLocator)
 {
     _templateParser           = new TemplateParser();
     _clientDescriptor         = clientDescriptor;
     _parameterExpanderLocator = parameterExpanderLocator;
     _httpClient = httpClientFactory.CreateClient(clientDescriptor.Name);
 }
Example #4
0
        /// <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);
        }
Example #5
0
        private Template(string templateFile, string destinationPath, bool onlyBody)
        {
            _destinationPath = destinationPath;
            _fileName        = templateFile;

            _templateParser = WebAppConfig.ViewEngines.Find(templateFile).Parser;

            string contents = TemplateUtil.ReadTemplateContents(_fileName, _destinationPath);

            Match matchTitle = Regex.Match(contents, @"<title\s*>(?<title>.*?)</title>");
            Match matchHead  = Regex.Match(contents, @"<!--\s*#STARTCOPY#\s*-->(?<text>.*?)<!--\s*#ENDCOPY#\s*-->", RegexOptions.IgnoreCase | RegexOptions.Singleline);

            if (matchTitle.Success)
            {
                _pageTitle = CompileTemplate(matchTitle.Groups["title"].Value);
            }

            if (matchHead.Success)
            {
                if (_headSections == null)
                {
                    _headSections = new List <ICompiledTemplate>();
                }

                _headSections.Add(CompileTemplate(matchHead.Groups["text"].Value));
            }

            if (onlyBody)
            {
                contents = TemplateUtil.ExtractBody(contents);
            }

            _parsedTemplate          = CompileTemplate(contents);
            _parsedTemplate.FileName = templateFile;
        }
Example #6
0
 public EmailTemplate(IEnumerable <ITemplateProvider> templateProviderses,
                      ITemplateParser templateParser,
                      IFileReader fileReader)
 {
     _templateProviders = templateProviderses;
     _templateParser    = templateParser;
     _fileReader        = fileReader;
 }
Example #7
0
 public LocalGenerator(IDatabase db, IParserConfig parseConfig)
 {
     _parseConfig = parseConfig;
     debugger     = new DefaultDebuger(db);
     parser       = DbLoader.CreateTemplateEngine(parseConfig);// new RazorTemplatePaser(parseConfig);
     // parser = new LiquidTemplatePaser(parseConfig);
     LogReport += (msg) => debugger.WriteLine(msg);
 }
Example #8
0
        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);
        }
Example #9
0
        /// <summary>Creates a new <see cref="SmtpMessagingService" />, using the given view engines.</summary>
        /// <param name="viewEngines">The view engines to use when creating Template views.</param>
        /// <param name="createSmtpClient">
        ///     A function that creates a <see cref="SmtpClient" />. If null, a default creation
        ///     function is used.
        /// </param>
        public SmtpMessagingService(ViewEngineCollection viewEngines, Func<SmtpClient> createSmtpClient = null)
        {
            if (viewEngines == null) throw new ArgumentNullException(nameof(viewEngines));

            _renderer = new TemplateViewRenderer(viewEngines);
            _templateParser = new MailMessageTemplateParser(_renderer);
            _smtpClientFunc = createSmtpClient ?? (() => new SmtpClient());
        }
Example #10
0
 public DefaultMethodInvoker(RequestContext requestContext, MethodInvokerEntry entry)
     : base(requestContext, entry.Interceptors)
 {
     _entry  = entry;
     _client = entry.Client;
     _codec  = entry.Codec;
     _keyValueFormatterFactory = entry.KeyValueFormatterFactory;
     _templateParser           = entry.TemplateParser;
 }
Example #11
0
		public bool CanHandleElement(ITemplateParser parser, XmlReader reader)
		{
			if (reader.NodeType == XmlNodeType.Element && !reader.IsEmptyElement)
			{
				return reader.GetAttribute("mr:unless") != null;
			}

			return false;
		}
 public override void Load(
     ITemplateParser parser,
     Func <PathString, bool> predicate = null,
     Func <PathString, string> mapPath = null,
     bool includeSubPaths = true)
 {
     throw new NotImplementedException(
               "Enumerating templates from a URI is not implemented yet. " +
               "Please use the LoadUri() method instead.");
 }
Example #13
0
        /// <summary>
        ///     Creates a new <see cref="SmtpMessagingService" />.
        /// </summary>
        public SmtpMessagingService(ITemplateViewRenderer renderer, ITemplateParser<MailMessage> templateParser, Func<SmtpClient> smtpClientFunc)
        {
            if (renderer == null) throw new ArgumentNullException(nameof(renderer));
            if (templateParser == null) throw new ArgumentNullException(nameof(templateParser));
            if (smtpClientFunc == null) throw new ArgumentNullException(nameof(smtpClientFunc));

            _renderer = renderer;
            _templateParser = templateParser;
            _smtpClientFunc = smtpClientFunc;
        }
Example #14
0
 public MethodInvokerCache(
     IGoClient goClient = null,
     IKeyValueFormatterFactory keyValueFormatterFactory = null,
     ITemplateParser templateParser = null,
     IServiceProvider services      = null)
 {
     _goClient = goClient ?? DefaultGoClient;
     _keyValueFormatterFactory = keyValueFormatterFactory ?? DefaultKeyValueFormatterFactory;
     _templateParser           = templateParser ?? DefaultTemplateParser;
     _services = services;
 }
Example #15
0
        /// <summary>Creates a new <see cref="SmtpMessagingService" />, using the given view engines.</summary>
        /// <param name="viewEngines">The view engines to use when creating Template views.</param>
        /// <param name="createSmtpClient">
        ///     A function that creates a <see cref="SmtpClient" />. If null, a default creation
        ///     function is used.
        /// </param>
        public SmtpMessagingService(ViewEngineCollection viewEngines, Func <SmtpClient> createSmtpClient = null)
        {
            if (viewEngines == null)
            {
                throw new ArgumentNullException(nameof(viewEngines));
            }

            _renderer       = new TemplateViewRenderer(viewEngines);
            _templateParser = new MailMessageTemplateParser(_renderer);
            _smtpClientFunc = createSmtpClient ?? (() => new SmtpClient());
        }
Example #16
0
        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));
        }
Example #17
0
 public TemplateInvoker(IFileManager fileManager,
                        ITemplateParser templateParser,
                        IFileAndDirectoryTokenParser fileAndDirectoryTokenParser,
                        ICraneContext context,
                        ITokenDictionaryFactory tokenDictionaryFactory)
 {
     _fileManager    = fileManager;
     _templateParser = templateParser;
     _fileAndDirectoryTokenParser = fileAndDirectoryTokenParser;
     _context = context;
     _tokenDictionaryFactory = tokenDictionaryFactory;
 }
Example #18
0
    public static ConditionBase ParseCondition(string expr, string variable, ITemplateParser parser)
    {
        expr = expr.Trim();

        var left = expr.TryBefore("||");

        if (left != null)
        {
            return(new ConditionOr(
                       ParseCondition(left, variable, parser),
                       ParseCondition(expr.After("||"), variable, parser)));
        }

        left = expr.TryBefore(" OR ");
        if (left != null)
        {
            return(new ConditionOr(
                       ParseCondition(left, variable, parser),
                       ParseCondition(expr.After(" OR "), variable, parser)));
        }

        left = expr.TryBefore("&&");
        if (left != null)
        {
            return(new ConditionAnd(
                       ParseCondition(left, variable, parser),
                       ParseCondition(expr.After("&&"), variable, parser)));
        }

        left = expr.TryBefore(" AND ");
        if (left != null)
        {
            return(new ConditionAnd(
                       ParseCondition(left, variable, parser),
                       ParseCondition(expr.After(" AND "), variable, parser)));
        }

        var filter = TemplateUtils.TokenOperationValueRegex.Match(expr);

        if (!filter.Success)
        {
            return(new ConditionCompare(ValueProviderBase.TryParse(expr, variable, parser) !));
        }
        else
        {
            var vpb       = ValueProviderBase.TryParse(filter.Groups["token"].Value, variable, parser);
            var operation = filter.Groups["operation"].Value;
            var value     = filter.Groups["value"].Value;
            return(new ConditionCompare(vpb, operation, value, parser.AddError));
        }
    }
Example #19
0
 public void SetUp()
 {
     _server = Configuration.Configure()
               .WithRandomPort()
               .Build();
     _emailConfiguration = new EmailConfiguration()
     {
         From           = "*****@*****.**",
         Port           = _server.Configuration.Port,
         SmtpServer     = "localhost",
         DefaultSubject = "Message from arpa"
     };
     _templateParser = Substitute.For <ITemplateParser>();
 }
Example #20
0
        protected MultiEventHandler(IServiceProvider serviceProvider)
            : base(serviceProvider)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            _emailService = serviceProvider.GetRequiredService <IEmailSender>();
            _razorEngine  = serviceProvider.GetRequiredService <ITemplateParser>();
            _logger       = serviceProvider.GetRequiredService <ILogger <MultiEventHandler <TEvent> > >();

            DbContextOptions = serviceProvider
                               .GetRequiredService <DbContextOptions <AppDbContext> >();
        }
Example #21
0
        public ImpressionEngine(ITemplateParser templateParser, IReflector reflector, ITemplateCache templateCache)
        {
            if (templateParser == null)
            {
                throw new ArgumentNullException("templateParser");
            }
            if (reflector == null)
            {
                throw new ArgumentNullException("reflector");
            }

            // save a local pointer
            this.templateParser = templateParser;
            this.reflector      = reflector;
            this.templateCache  = templateCache;
        }
Example #22
0
        public DotLiquidView(ControllerContext controllerContext, IViewLocator locator, ITemplateParser parser, ViewLocationResult viewResult, ViewLocationResult masterViewResult)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            if (viewResult == null)
            {
                throw new ArgumentNullException("viewPath");
            }

            _locator = locator;
            _parser = parser;
            this.ViewResult = viewResult;
            this.MasterViewResult = masterViewResult;
        }
Example #23
0
		public void ProcessElement(ITemplateParser parser, ITemplateContext context)
		{
			String unlessExpression = context.Reader.GetAttribute("mr:unless");

			context.AppendLineIndented("if not " + unlessExpression + ":");
			context.IncreaseIndentation();

			// Output element
			parser.OutputCurrentElementAsContent(context, delegate(String attributeName)
				{
					return attributeName != "mr:unless";
				});

			parser.ProcessReader(context, context.CurrentElementDepth - 1);

			context.DecreaseIndentation();
		}
Example #24
0
        public DotLiquidView(ControllerContext controllerContext, IViewLocator locator, ITemplateParser parser, ViewLocationResult viewResult, ViewLocationResult masterViewResult)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            if (viewResult == null)
            {
                throw new ArgumentNullException("viewPath");
            }

            _locator              = locator;
            _parser               = parser;
            this.ViewResult       = viewResult;
            this.MasterViewResult = masterViewResult;
        }
Example #25
0
        public StateController(
            IStateFileSerializer stateFileSerializer,
            ProductJsonConverter productJsonConverter,
            ITemplateParser templateParser,
            ProductHandler productHandler)
        {
            _stateFileSerializer  = stateFileSerializer;
            _productJsonConverter = productJsonConverter;
            _productHandler       = productHandler;
            _templateParser       = templateParser;

            _statesFolderPath = HostingEnvironment.MapPath(_statesFolder);

            if (!Directory.Exists(_statesFolderPath))
            {
                Directory.CreateDirectory(_statesFolderPath);
            }
        }
        public DotLiquidViewEngine(IFileSystemFactory fileSystem, IViewLocator viewLocator, ITemplateParser parser, IEnumerable <Type> filters)
        {
            DotLiquid.Liquid.UseRubyDateFormat = true;
            _viewLocator     = viewLocator;
            _parser          = parser;
            this._fileSystem = fileSystem;
            // Register custom tags (Only need to do this once)
            Template.RegisterFilter(typeof(CommonFilters));
            Template.RegisterFilter(typeof(CommerceFilters));

            foreach (var filter in filters)
            {
                Template.RegisterFilter(filter);
            }

            Template.RegisterTag <Paginate>("paginate");
            Template.RegisterTag <CurrentPage>("current_page");
            Template.RegisterTag <Layout>("layout");
        }
        public DotLiquidViewEngine(IFileSystemFactory fileSystem, IViewLocator viewLocator, ITemplateParser parser, IEnumerable<Type> filters)
        {
            DotLiquid.Liquid.UseRubyDateFormat = true;
            _viewLocator = viewLocator;
            _parser = parser;
            this._fileSystem = fileSystem;
            // Register custom tags (Only need to do this once)
            Template.RegisterFilter(typeof(CommonFilters));
            Template.RegisterFilter(typeof(CommerceFilters));

            foreach (var filter in filters)
            {
                Template.RegisterFilter(filter);
            }

            Template.RegisterTag<Paginate>("paginate");
            Template.RegisterTag<CurrentPage>("current_page");
            Template.RegisterTag<Layout>("layout");
        }
Example #28
0
        /// <summary>
        ///     Creates a new <see cref="SmtpMessagingService" />.
        /// </summary>
        public SmtpMessagingService(ITemplateViewRenderer renderer, ITemplateParser <MailMessage> templateParser, Func <SmtpClient> smtpClientFunc)
        {
            if (renderer == null)
            {
                throw new ArgumentNullException(nameof(renderer));
            }
            if (templateParser == null)
            {
                throw new ArgumentNullException(nameof(templateParser));
            }
            if (smtpClientFunc == null)
            {
                throw new ArgumentNullException(nameof(smtpClientFunc));
            }

            _renderer       = renderer;
            _templateParser = templateParser;
            _smtpClientFunc = smtpClientFunc;
        }
Example #29
0
        /// <summary>
        /// Constructs the compiler with required dependencies
        /// </summary>
        /// <param name="parser">The template parser</param>
        /// <param name="renderer">The template renderer</param>
        /// <param name="validator">The template validator</param>
        /// <param name="functionRepository">The function repository</param>
        /// <param name="templateRepository">The template repository</param>
        internal NettleCompiler
        (
            ITemplateParser parser,
            ITemplateRenderer renderer,
            ITemplateValidator validator,
            IFunctionRepository functionRepository,
            IRegisteredTemplateRepository templateRepository
        )
        {
            Validate.IsNotNull(parser);
            Validate.IsNotNull(renderer);
            Validate.IsNotNull(validator);
            Validate.IsNotNull(functionRepository);
            Validate.IsNotNull(templateRepository);

            _parser             = parser;
            _renderer           = renderer;
            _validator          = validator;
            _functionRepository = functionRepository;
            _templateRepository = templateRepository;
        }
        /// <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);
        }
Example #31
0
        /// <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);
        }
Example #32
0
		public void ProcessElement(ITemplateParser parser, ITemplateContext context)
		{
			String view = context.Reader.GetAttribute("src") + IronPythonViewEngine.TemplateExtension;
			
			IViewSourceLoader loader = 
				(IViewSourceLoader) context.ServiceProvider.GetService(typeof(IViewSourceLoader));

			IViewSource source = loader.GetViewSource(view);
			
			if (source == null)
			{
				throw new RailsException("RenderPartial: could not find view [" + view + "]");
			}

			String functionName;
			context.Engine.CompilePartialTemplate(source, view, out functionName);

			context.Script.AppendLine();
			context.AppendIndented(functionName);
			context.Script.Append('(');
			context.Script.Append("controller, context, request, response, session, output, flash, siteroot");
			context.Script.Append(')');
			context.Script.AppendLine();
		}
Example #33
0
		public void ProcessPI(ITemplateParser parser, ITemplateContext context)
		{
			String content = context.Reader.Value.Trim();

			if (content == "end")
			{
				context.DecreaseIndentation();
			}
			else if (content.EndsWith("else:"))
			{
				context.DecreaseIndentation();
				context.AppendLineIndented(content);
				context.IncreaseIndentation();
			}
			else
			{
				context.AppendLineIndented(content);

				if (content.EndsWith(":"))
				{
					context.IncreaseIndentation();
				}
			}
		}
Example #34
0
 public RazorJSCompiler()
 {
     this._templateParser     = new CSharpRazorTemplateParser();
     this._templateBuilder    = new RazorJSTemplateBuilder();
     this._documentTranslator = new DocumentTranslator();
 }
Example #35
0
 public abstract void Load(
     ITemplateParser parser,
     Func <PathString, bool> predicate = null,
     Func <PathString, string> mapPath = null,
     bool includeSubPaths = true);
Example #36
0
        private Template(string templateFile, string destinationPath, bool onlyBody)
        {
            _destinationPath = destinationPath;
            _fileName = templateFile;

            _templateParser = WebAppConfig.ViewEngines.Find(templateFile).Parser;

            string contents = TemplateUtil.ReadTemplateContents(_fileName, _destinationPath);

            Match matchTitle = Regex.Match(contents, @"<title\s*>(?<title>.*?)</title>");
            Match matchHead = Regex.Match(contents, @"<!--\s*#STARTCOPY#\s*-->(?<text>.*?)<!--\s*#ENDCOPY#\s*-->", RegexOptions.IgnoreCase | RegexOptions.Singleline);

            if (matchTitle.Success)
                _pageTitle = CompileTemplate(matchTitle.Groups["title"].Value);

            if (matchHead.Success)
            {
                if (_headSections == null)
                    _headSections = new List<ICompiledTemplate>();

                _headSections.Add(CompileTemplate(matchHead.Groups["text"].Value));
            }

            if (onlyBody)
                contents = TemplateUtil.ExtractBody(contents);

            _parsedTemplate = CompileTemplate(contents);
            _parsedTemplate.FileName = templateFile;
        }
Example #37
0
		public void ProcessElement(ITemplateParser parser, ITemplateContext context)
		{
			parser.ProcessReader(context, context.CurrentElementDepth);
		}
Example #38
0
		public bool CanHandleElement(ITemplateParser parser, XmlReader reader)
		{
			return (reader.NodeType == XmlNodeType.Element && reader.LocalName == "mr:content");
		}
Example #39
0
        public ImpressionEngine(ITemplateParser templateParser, IReflector reflector, ITemplateCache templateCache)
        {
            if (templateParser == null)
                throw new ArgumentNullException("templateParser");
            if (reflector == null)
                throw new ArgumentNullException("reflector");

            // save a local pointer
            this.templateParser = templateParser;
            this.reflector = reflector;
            this.templateCache = templateCache;
        }
Example #40
0
 /// <summary>
 ///     Creates a new <see cref="TemplateViewResult" />.
 /// </summary>
 public TemplateViewResult(Template template, ITemplateViewRenderer renderer, ITemplateParser<MailMessage> parser)
 {
     Template = template;
     Renderer = renderer ?? new TemplateViewRenderer(ViewEngineCollection);
     TemplateParser = parser ?? new MailMessageTemplateParser(Renderer);
 }
Example #41
0
 public EmailMessageFormatter(ITemplateProvider templateProvider, ITemplateParser templateParser)
 {
     _templateProvider = templateProvider;
     _templateParser   = templateParser;
 }
Example #42
0
		public void ProcessPI(ITemplateParser parser, ITemplateContext context)
		{
			throw new NotImplementedException();
		}
Example #43
0
 public RazorJSCompiler(ITemplateParser templateParser, ITemplateBuilder templateBuilder, IDocumentTranslator documentTranslator)
 {
     this._templateParser     = templateParser;
     this._templateBuilder    = templateBuilder;
     this._documentTranslator = documentTranslator;
 }
 public TemplateEngine(ITemplateProvider templateProvider, ITemplateParser templateParser)
 {
     this.templateProvider = templateProvider;
     this.templateParser = templateParser;
 }
Example #45
0
 public DotLiquidView(ControllerContext controllerContext, IViewLocator locator, ITemplateParser parser, ViewLocationResult partialPath)
     : this(controllerContext, locator, parser, partialPath, null)
 {
 }
 public EmailTemplateManager(string templateFolder)
 {
     _templateFolder = Util.DevirtualizePath(templateFolder);
     _templateParser = new TemplateParser();
 }
        public override TemplateParserPluginResult Parse(ITemplateParser templateParser, string template)
        {
            Contract.Requires<ArgumentNullException>(templateParser != null);
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(template));
            Contract.Ensures(Contract.Result<TemplateParserPluginResult>() != null);

            List<TemplateToken> templateTokens = new List<TemplateToken>();
            List<NetworkEdgeType> unresolvedContext = new List<NetworkEdgeType>();
            string resolvedText = null;
            Match match = _wordRegex.Match(template);

            if (match.Success)
            {
                string templateItemType = match.Groups[2].Value.ToLower();
                string wordSample = null;

                switch (templateItemType)
                {
                    case "agent":
                        var agentNodes = templateParser.NetworkContext[NetworkEdgeType.Agent];

                        if (!agentNodes.Any())
                        {
                            unresolvedContext.Add(NetworkEdgeType.Agent);
                            break;
                        }

                        wordSample = GetContextNodeByIndex(match, 3, agentNodes).Name;
                        break;

                    case "recipient":
                        var recipientNodes = templateParser.NetworkContext[NetworkEdgeType.Recipient];

                        if (!recipientNodes.Any())
                        {
                            unresolvedContext.Add(NetworkEdgeType.Recipient);
                            break;
                        }

                        wordSample = GetContextNodeByIndex(match, 3, recipientNodes).Name;
                        break;

                    case "action":
                        var actionNodes = templateParser.NetworkContext[NetworkEdgeType.Action];

                        if (!actionNodes.Any())
                        {
                            unresolvedContext.Add(NetworkEdgeType.Action);
                            break;
                        }

                        wordSample = GetContextNodeByIndex(match, 3, actionNodes).Name;
                        break;

                    default:
                        throw new NotSupportedException();
                }

                if (!string.IsNullOrEmpty(wordSample))
                {
                    resolvedText = templateParser.ReconcileWord(match.Groups[1].Value.Trim('~', ':'), wordSample);

                    templateTokens.Add(new TemplateToken(resolvedText, Lemmatize(templateParser.TextAnalyzer, wordSample), match.ToString()));
                }
            }

            return new TemplateParserPluginResult(resolvedText, templateTokens, unresolvedContext);
        }
 public AbstractCodeGenerator(ITemplateParser parser)
 {
     this.parser = parser;
 }
Example #49
0
		public bool CanHandleElement(ITemplateParser parser, XmlReader reader)
		{
			return false;
		}
 public MailMessageWrapper(ITemplateParser templateParser)
 {
     ContainedMailMessage = new MailMessage();
     TemplateParser = templateParser;
 }
Example #51
0
		public void ProcessPI(ITemplateParser parser, ITemplateContext context)
		{
			context.AppendLineIndented("output.Write(" + context.Reader.Value + ")");
		}
 public abstract TemplateParserPluginResult Parse(ITemplateParser parser, string template);
 public MergedEmailFactory(ITemplateParser templateParser)
 {
     Message = new MailMessageWrapper(templateParser);
 }
Example #54
0
        public Action <RenderingContext, object> CompileNonGeneric(string templateId, ITemplateParser parser, TextReader templateContents, Type modelType)
        {
            var    typedCompileMethod = GenericCompileMethod.MakeGenericMethod(modelType);
            object compiledTemplate;

            try
            {
                compiledTemplate = typedCompileMethod.Invoke(this,
                                                             new object[] { templateId, parser, templateContents });
            }
            catch (TargetInvocationException ex)
            {
                throw ex.InnerException;
            }

            var writer    = Expression.Parameter(typeof(RenderingContext));
            var model     = Expression.Parameter(typeof(object));
            var castModel = Expression.Variable(modelType);
            var template  = Expression.Constant(compiledTemplate);
            var lambda    = Expression.Lambda <Action <RenderingContext, object> >(
                Expression.Block(
                    new[] { castModel },
                    Expression.Assign(castModel, Expression.TypeAs(model, modelType)),
                    Expression.Call(template, compiledTemplate.GetType().GetMethod("Invoke"), writer, castModel)
                    ),
                writer,
                model
                );

            return(lambda.Compile());
        }
        public override TemplateParserPluginResult Parse(ITemplateParser templateParser, string template)
        {
            Contract.Requires<ArgumentNullException>(templateParser != null);
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(template));
            Contract.Ensures(Contract.Result<TemplateParserPluginResult>() != null);

            _templateParser = templateParser;

            string resolvedText = null;
            List<TemplateToken> templateTokens = new List<TemplateToken>();
            List<NetworkEdgeType> unresolvedContext = new List<NetworkEdgeType>();

            for (; ; )
            {
                Match match = _agentsRegex.Match(template);
                if (match.Success)
                {
                    ParserResult parserResult = ParseActorsTemplate(template, match, unresolvedContext, NetworkEdgeType.Agent);

                    resolvedText = parserResult.Text;
                    templateTokens.AddRange(parserResult.TemplateTokens);
                    break;
                }

                match = _agentRegex.Match(template);
                if (match.Success)
                {
                    TemplateToken actorToken = ParseActorTemplate(template, match, unresolvedContext, NetworkEdgeType.Agent);

                    resolvedText = actorToken.Text;
                    templateTokens.Add(actorToken);
                    break;
                }

                match = _recipientsRegex.Match(template);
                if (match.Success)
                {
                    ParserResult parserResult = ParseActorsTemplate(template, match, unresolvedContext, NetworkEdgeType.Recipient);

                    resolvedText = parserResult.Text;
                    templateTokens.AddRange(parserResult.TemplateTokens);
                    break;
                }

                match = _recipientRegex.Match(template);
                if (match.Success)
                {
                    TemplateToken recipientToken = ParseActorTemplate(template, match, unresolvedContext, NetworkEdgeType.Recipient);

                    resolvedText = recipientToken.Text;
                    templateTokens.Add(recipientToken);
                    break;
                }

                match = _actionRegex.Match(template);
                if (match.Success)
                {
                    TemplateToken actionToken = ParseActionTemplate(template, match, unresolvedContext);

                    resolvedText = actionToken.Text;
                    templateTokens.Add(actionToken);
                    break;
                }

                match = _locativeRegex.Match(template);
                if (match.Success)
                {
                    throw new NotImplementedException();
                }

                break;
            }

            _templateParser = null;

            return new TemplateParserPluginResult(resolvedText, templateTokens, unresolvedContext);
        }