コード例 #1
0
        public System.Web.WebPages.HelperResult FieldStartMarkerDiv(string fieldExpression)
        {
#line default
#line hidden
            return(new System.Web.WebPages.HelperResult(__razor_helper_writer => {
#line 25 "..\..\Views\Shared\MainHelpers.cshtml"

                var fn = new BuiltInFunctions(TridionHelper.Engine, TridionHelper.Package);
                string tagString = fn.FieldStartMarker(fieldExpression);
                tagString = tagString.TrimEnd('>');
                tagString += " tag=\"div\">";



#line default
#line hidden

#line 31 "..\..\Views\Shared\MainHelpers.cshtml"
                WriteTo(__razor_helper_writer, tagString);


#line default
#line hidden

#line 31 "..\..\Views\Shared\MainHelpers.cshtml"



#line default
#line hidden
            }));

#line 32 "..\..\Views\Shared\MainHelpers.cshtml"
        }
コード例 #2
0
        public string RenderComponentFieldAsBBCode(string fieldExpression, int fieldIndex, bool outputImages)
        {
            BuiltInFunctions functions = new BuiltInFunctions(_engine, _package);
            string output = functions.RenderComponentField(fieldExpression, fieldIndex);

            StringReader sr = new StringReader(output);
            NameTable nt = new NameTable();
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
            nsmgr.AddNamespace("tcdl", Tridion.ContentManager.Templating.TcdlTags.TcdlNamespace);
            XmlParserContext parserContext = new XmlParserContext(null, nsmgr, null, XmlSpace.None);

            XmlReader xmlReader = XmlReader.Create(sr, new XmlReaderSettings(), parserContext);

            XslCompiledTransform transform = new XslCompiledTransform(true);

            using (Stream xsltStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Tridion.ContentManager.Templating.Expression.NetbiscuitsFunctions.XhtmlToBBCode.xslt"))
            {
                using (XmlReader xsltReader = XmlReader.Create(xsltStream))
                {
                    transform.Load(xsltReader);
                }
            }

            StringWriter resultWriter = new StringWriter();
            XsltArgumentList argumentList = new XsltArgumentList();
            argumentList.AddParam("IncludeImages", String.Empty, outputImages);

            transform.Transform(xmlReader, argumentList, resultWriter);

            return resultWriter.ToString();   
        }
コード例 #3
0
        public (object value, string error) GetValue(string path)
        {
            if (memory == null)
            {
                return(null, null);
            }

            var parts = path.Split(".[]".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                        .Select(x => x.Trim('\'', '"'))
                        .ToArray();
            object value    = null;
            var    curScope = memory;

            foreach (string part in parts)
            {
                string error = null;
                if (int.TryParse(part, out var idx) && BuiltInFunctions.TryParseList(curScope, out var li))
                {
                    (value, error) = BuiltInFunctions.AccessIndex(li, idx);
                }
                else
                {
                    (value, error) = BuiltInFunctions.AccessProperty(curScope, part);
                }

                if (error != null)
                {
                    return(null, error);
                }

                curScope = value;
            }

            return(value, null);
        }
コード例 #4
0
        public string RenderComponentFieldAsBBCode(string fieldExpression, int fieldIndex, bool outputImages)
        {
            BuiltInFunctions functions = new BuiltInFunctions(_engine, _package);
            string           output    = functions.RenderComponentField(fieldExpression, fieldIndex);

            StringReader        sr    = new StringReader(output);
            NameTable           nt    = new NameTable();
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);

            nsmgr.AddNamespace("tcdl", Tridion.ContentManager.Templating.TcdlTags.TcdlNamespace);
            XmlParserContext parserContext = new XmlParserContext(null, nsmgr, null, XmlSpace.None);

            XmlReader xmlReader = XmlReader.Create(sr, new XmlReaderSettings(), parserContext);

            XslCompiledTransform transform = new XslCompiledTransform(true);

            using (Stream xsltStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Tridion.ContentManager.Templating.Expression.NetbiscuitsFunctions.XhtmlToBBCode.xslt"))
            {
                using (XmlReader xsltReader = XmlReader.Create(xsltStream))
                {
                    transform.Load(xsltReader);
                }
            }

            StringWriter     resultWriter = new StringWriter();
            XsltArgumentList argumentList = new XsltArgumentList();

            argumentList.AddParam("IncludeImages", String.Empty, outputImages);

            transform.Transform(xmlReader, argumentList, resultWriter);

            return(resultWriter.ToString());
        }
コード例 #5
0
        public void ASC_WithA_Returns65()
        {
            var       actual = BuiltInFunctions.ASC("A");
            const int wellKnownAsciiCodeOfLetterA = 65;

            Assert.AreEqual(wellKnownAsciiCodeOfLetterA, actual);
        }
コード例 #6
0
        public System.Web.WebPages.HelperResult FieldStartMarker(string fieldExpression)
        {
#line default
#line hidden
            return(new System.Web.WebPages.HelperResult(__razor_helper_writer => {
#line 19 "..\..\Views\Shared\MainHelpers.cshtml"

                var fn = new BuiltInFunctions(TridionHelper.Engine, TridionHelper.Package);


#line default
#line hidden

#line 21 "..\..\Views\Shared\MainHelpers.cshtml"
                WriteTo(__razor_helper_writer, fn.FieldStartMarker(fieldExpression));


#line default
#line hidden

#line 21 "..\..\Views\Shared\MainHelpers.cshtml"



#line default
#line hidden
            }));

#line 22 "..\..\Views\Shared\MainHelpers.cshtml"
        }
コード例 #7
0
        public System.Web.WebPages.HelperResult GetFieldValue(string fieldExpression = null, int index = 0)
        {
#line default
#line hidden
            return(new System.Web.WebPages.HelperResult(__razor_helper_writer => {
#line 6 "..\..\Views\Shared\MainHelpers.cshtml"

                var fn = new BuiltInFunctions(TridionHelper.Engine, TridionHelper.Package);
                try
                {
#line default
#line hidden

#line 10 "..\..\Views\Shared\MainHelpers.cshtml"
                    WriteTo(__razor_helper_writer, fn.GetFieldValue(fieldExpression, index));


#line default
#line hidden

#line 10 "..\..\Views\Shared\MainHelpers.cshtml"
                }
                catch
                {
                    Log.Debug("Unable to resolve: " + fieldExpression + " with index: " + index);
                }


#line default
#line hidden
            }));

#line 16 "..\..\Views\Shared\MainHelpers.cshtml"
        }
コード例 #8
0
        public void ASC_WithABC_Returns65()
        {
            var       actual = BuiltInFunctions.ASC("ABC");
            const int wellKnownAsciiCodeOfLetterA = 65;

            // B and C shold be ignored.
            Assert.AreEqual(wellKnownAsciiCodeOfLetterA, actual);
        }
コード例 #9
0
 /// <summary>
 /// Initializes the TridionRazorTemplate.
 /// </summary>
 /// <param name="engine"></param>
 /// <param name="package"></param>
 public void Initialize(Engine engine, Package package, Template template, List <string> assemblyReferences)
 {
     _engine           = engine;
     _package          = package;
     _tridionHelper    = new TridionUtilities(engine, package);
     _razorTBB         = template;
     _builtInFunctions = new BuiltInFunctions(engine, package);
     _references       = assemblyReferences;
 }
コード例 #10
0
        protected override Delegate GetFunc()
        {
            Func <string, string, bool> call = (arg1, arg2) =>
            {
                return(BuiltInFunctions.RegexMatch(arg1, arg2));
            };

            return(call);
        }
コード例 #11
0
        /// <summary>
        /// Finds all signatures for the given function name.
        /// </summary>
        /// <param name="functionName">The function to get the signatures for.</param>
        /// <returns>The signatures which match the supplied function name.</returns>
        internal static FunctionSignatureWithReturnType[] GetBuiltInFunctionSignatures(string functionName)
        {
            // Try to find the function in our built-in functions
            FunctionSignatureWithReturnType[] signatures;
            if (!BuiltInFunctions.TryGetBuiltInFunction(functionName, out signatures))
            {
                throw new ODataException(ODataErrorStrings.MetadataBinder_UnknownFunction(functionName));
            }

            return(signatures);
        }
コード例 #12
0
        // Generate a new lookup function based on one lookup function
        private EvaluatorLookup CustomizedEvaluatorLookup(EvaluatorLookup baseLookup)
        => (string name) =>
        {
            var prebuiltPrefix = "prebuilt.";

            if (name.StartsWith(prebuiltPrefix))
            {
                return(baseLookup(name.Substring(prebuiltPrefix.Length)));
            }

            var templateName = ParseTemplateName(name).pureTemplateName;

            if (this.TemplateMap.ContainsKey(templateName))
            {
                return(new ExpressionEvaluator(templateName, BuiltInFunctions.Apply(this.TemplateEvaluator(name)), ReturnType.Object, this.ValidTemplateReference));
            }

            const string template = "template";

            if (name.Equals(template))
            {
                return(new ExpressionEvaluator(template, BuiltInFunctions.Apply(this.TemplateFunction()), ReturnType.Object, this.ValidateTemplateFunction));
            }

            const string fromFile = "fromFile";

            if (name.Equals(fromFile))
            {
                return(new ExpressionEvaluator(fromFile, BuiltInFunctions.Apply(this.FromFile()), ReturnType.String, BuiltInFunctions.ValidateUnaryString));
            }

            const string activityAttachment = "ActivityAttachment";

            if (name.Equals(activityAttachment))
            {
                return(new ExpressionEvaluator(
                           activityAttachment,
                           BuiltInFunctions.Apply(this.ActivityAttachment()),
                           ReturnType.Object,
                           (expr) => BuiltInFunctions.ValidateOrder(expr, null, ReturnType.Object, ReturnType.String)));
            }

            const string isTemplate = "isTemplate";

            if (name.Equals(isTemplate))
            {
                return(new ExpressionEvaluator(isTemplate, BuiltInFunctions.Apply(this.IsTemplate()), ReturnType.Boolean, BuiltInFunctions.ValidateUnaryString));
            }

            return(baseLookup(name));
        };
コード例 #13
0
        private void SetGFunctions(Interpreter interpreter)
        {
            if (_model.Model.ContainsKey(PermConstants.Section.RoleSection) is false)
            {
                return;
            }

            foreach (KeyValuePair <string, Assertion> assertionKeyValue in _model.Model[PermConstants.Section.RoleSection])
            {
                string    key       = assertionKeyValue.Key;
                Assertion assertion = assertionKeyValue.Value;
                interpreter.SetFunction(key, BuiltInFunctions.GenerateGFunction(key, assertion.RoleManager));
            }
        }
コード例 #14
0
        private ExpressionEvaluator Lookup(string type)
        {
            ExpressionEvaluator eval;

            if (type == "ignore")
            {
                eval          = new ExpressionEvaluator("ignore", null);
                eval.Negation = eval;
            }
            else
            {
                eval = BuiltInFunctions.Lookup(type);
            }

            return(eval);
        }
コード例 #15
0
        public static ExpressionEvaluator LookupFunction(string type)
        {
            ExpressionEvaluator eval;

            if (type == Optional || type == Ignore)
            {
                eval          = new ExpressionEvaluator(type, null, ReturnType.Boolean, BuiltInFunctions.ValidateUnaryBoolean);
                eval.Negation = eval;
            }
            else
            {
                eval = BuiltInFunctions.Lookup(type);
            }

            return(eval);
        }
コード例 #16
0
        public override eeObject VisitFn_call([NotNull] EelooParser.Fn_callContext ctx)
        {
            // add this to scope
            Interpreter.currentScope.scopeCtx = ctx;

            // Get function's name
            string iden = ctx.IDENTIFIER().GetText();

            // If function is built-in
            var func = BuiltInFunctions.ResolveFunc(iden);

            if (func != null)
            {
                // Evaluate function's arguments
                ICollection <eeObject> arguments = ctx.exps() != null?Visit(ctx.exps()).AsEXPRLIST() : new List <eeObject>();

                var scope  = new Scope(Interpreter.currentScope, ctx);
                var result = (eeObject)func.DynamicInvoke(arguments);
                Scope.unScope(scope);

                return(result);
            }

            // Check if function is user-defined
            var fn = Interpreter.currentScope.resolveVar(iden);

            if (fn != null && fn.type == eeObjectType.FUNCTION)
            {
                ICollection <eeObject> args = ctx.exps() != null?Visit(ctx.exps()).AsEXPRLIST() : null;

                var funcObj = fn.AsFunction();

                var scope = new Scope(Interpreter.currentScope, ctx);
                Interpreter.globalStack.AddCall(ctx, funcObj);

                var result = funcObj.invoke(args);

                Interpreter.globalStack.RemoveCall(funcObj);
                Scope.unScope(scope);

                return(result);
            }
            else
            {
                throw new NoFunctionError(iden);
            }
        }
コード例 #17
0
        public ExpressionEvaluator GetMethodX(string name)
        {
            // user can always choose to use builtin.xxx to disambiguate with template xxx
            var builtInPrefix = "builtin.";

            if (name.StartsWith(builtInPrefix))
            {
                return(BuiltInFunctions.Lookup(name.Substring(builtInPrefix.Length)));
            }

            if (_evaluator.TemplateMap.ContainsKey(name))
            {
                return(new ExpressionEvaluator(name, BuiltInFunctions.Apply(this.TemplateEvaluator(name)), ReturnType.String, this.ValidTemplateReference));
            }

            return(BuiltInFunctions.Lookup(name));
        }
コード例 #18
0
        // Validator for template(...)
        private void ValidateTemplateFunction(Expression expression)
        {
            BuiltInFunctions.ValidateAtLeastOne(expression);

            var children0 = expression.Children[0];

            if (children0.ReturnType != ReturnType.Object && children0.ReturnType != ReturnType.String)
            {
                throw new Exception(LGErrors.ErrorTemplateNameformat(children0.ToString()));
            }

            // Validate more if the name is string constant
            if (children0.Type == ExpressionType.Constant)
            {
                var templateName = (children0 as Constant).Value.ToString();
                CheckTemplateReference(templateName, expression.Children.Skip(1));
            }
        }
コード例 #19
0
        /// <summary>
        /// Construct a run time. You can have multiple run times per script.
        /// </summary>
        /// <param name="script">Contains the script source file.</param>
        /// <param name="text_writer">Allows print() output to be redirected.</param>
        public RunTime(Script script, TextWriter text_writer = null)
        {
            statements = script.statements;
            user_def_function_locations = script.user_def_function_locations;
            built_in_functions          = new BuiltInFunctions(symbol_table, text_writer);

            // initialize "statement_handlers[]"
            statement_handlers = new StatementHandler[Enum.GetNames(typeof(StatementType)).Length];
            statement_handlers[(int)StatementType.Assign]              = run_assign_statement;
            statement_handlers[(int)StatementType.Conditional]         = run_conditional_statement;
            statement_handlers[(int)StatementType.Function_Arg_Assign] = run_function_arg_assign_statement;
            statement_handlers[(int)StatementType.Function_Call]       = run_function_call_statement;
            statement_handlers[(int)StatementType.Global]              = run_global_statement;
            statement_handlers[(int)StatementType.Keyword]             = run_keyword_statement;
            statement_handlers[(int)StatementType.Jump]        = run_jump_statement;
            statement_handlers[(int)StatementType.Return]      = run_return_statement;
            statement_handlers[(int)StatementType.SliceAssign] = run_slice_assign_statement;
        }
コード例 #20
0
ファイル: Minify.cs プロジェクト: modulexcite/More
        private static ColorValue MinifyColor(ColorValue value)
        {
            // There's no lossless conversion for RGBA values
            if (value is RGBAColorValue)
            {
                return(value);
            }

            // The smallest form of a color will *always* be the hex version or the named color version
            //   So lets build the sextuple hex version
            var red   = (byte)((NumberValue)BuiltInFunctions.Red(new[] { value }, Position.NoSite)).Value;
            var green = (byte)((NumberValue)BuiltInFunctions.Green(new[] { value }, Position.NoSite)).Value;
            var blue  = (byte)((NumberValue)BuiltInFunctions.Blue(new[] { value }, Position.NoSite)).Value;

            string hex;

            using (var buffer = new StringWriter())
            {
                (new HexSextupleColorValue(red, green, blue)).Write(buffer);
                hex = buffer.ToString().Substring(1);
            }

            var    asNum   = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);
            string asNamed = null;

            if (Enum.IsDefined(typeof(NamedColor), asNum))
            {
                asNamed = Enum.GetName(typeof(NamedColor), (NamedColor)asNum);
            }

            if (asNamed.HasValue() && asNamed.Length < 7)
            {
                return(new NamedColorValue((NamedColor)asNum));
            }

            if (red.ToString("x").Distinct().Count() == 1 &&
                green.ToString("x").Distinct().Count() == 1 &&
                blue.ToString("x").Distinct().Count() == 1)
            {
                return(new HexTripleColorValue(red, green, blue));
            }

            return(new HexSextupleColorValue(red, green, blue));
        }
コード例 #21
0
ファイル: DataContext.cs プロジェクト: dallmair/nquery-vnext
        private static DataContext CreateDefault()
        {
            var functions          = BuiltInFunctions.GetFunctions().ToImmutableList();
            var aggregates         = BuiltInAggregates.GetAggregates().ToImmutableList();
            var reflectionProvider = new ReflectionProvider();
            var propertyProviders  = ImmutableDictionary.Create <Type, IPropertyProvider>()
                                     .Add(typeof(object), reflectionProvider);
            var methodProviders = ImmutableDictionary.Create <Type, IMethodProvider>()
                                  .Add(typeof(object), reflectionProvider);
            var comparers = ImmutableDictionary.Create <Type, IComparer>();

            return(new DataContext(ImmutableList.Create <TableSymbol>(),
                                   ImmutableList.Create <TableRelation>(),
                                   functions,
                                   aggregates,
                                   ImmutableList.Create <VariableSymbol>(),
                                   propertyProviders,
                                   methodProviders,
                                   comparers));
        }
コード例 #22
0
        /// <summary>
        /// Finds the signature that best matches the arguments
        /// </summary>
        /// <param name="functionName">The name of the function</param>
        /// <param name="argumentNodes">The nodes of the arguments, can be new {null,null}.</param>
        /// <param name="signatures">The signatures to match against</param>
        /// <returns>Returns the matching signature or throws</returns>
        internal static FunctionSignatureWithReturnType MatchSignatureToBuiltInFunction(string functionName, SingleValueNode[] argumentNodes, FunctionSignatureWithReturnType[] signatures)
        {
            FunctionSignatureWithReturnType signature;

            IEdmTypeReference[] argumentTypes = argumentNodes.Select(s => s.TypeReference).ToArray();

            // Handle the cases where we don't have type information (null literal, open properties) for ANY of the arguments
            int argumentCount = argumentTypes.Length;

            if (argumentTypes.All(a => a == null) && argumentCount > 0)
            {
                // we specifically want to find just the first function that matches the number of arguments, we don't care about
                // ambiguity here because we're already in an ambiguous case where we don't know what kind of types
                // those arguments are.
                signature = signatures.FirstOrDefault(candidateFunction => candidateFunction.ArgumentTypes.Count() == argumentCount);
                if (signature == null)
                {
                    throw new ODataException(ODataErrorStrings.FunctionCallBinder_CannotFindASuitableOverload(functionName, argumentTypes.Count()));
                }
                else
                {
                    // in this case we can't assert the return type, we can only assert that a function exists... so
                    // we need to set the return type to null.
                    signature = new FunctionSignatureWithReturnType(null, signature.ArgumentTypes);
                }
            }
            else
            {
                signature = TypePromotionUtils.FindBestFunctionSignature(signatures, argumentNodes);
                if (signature == null)
                {
                    throw new ODataException(ODataErrorStrings.MetadataBinder_NoApplicableFunctionFound(
                                                 functionName,
                                                 BuiltInFunctions.BuildFunctionSignatureListDescription(functionName, signatures)));
                }
            }

            return(signature);
        }
コード例 #23
0
public System.Web.WebPages.HelperResult GetFieldValue(string fieldExpression = null, int index = 0)
{
#line default
#line hidden
return new System.Web.WebPages.HelperResult(__razor_helper_writer => {

#line 6 "..\..\Views\Shared\MainHelpers.cshtml"
 
    var fn = new BuiltInFunctions(TridionHelper.Engine, TridionHelper.Package);
    try
    {
        

#line default
#line hidden

#line 10 "..\..\Views\Shared\MainHelpers.cshtml"
WriteTo(__razor_helper_writer, fn.GetFieldValue(fieldExpression, index));


#line default
#line hidden

#line 10 "..\..\Views\Shared\MainHelpers.cshtml"
                                                 
    }
    catch
    {
        Log.Debug("Unable to resolve: " + fieldExpression + " with index: " + index);
    }


#line default
#line hidden
});

#line 16 "..\..\Views\Shared\MainHelpers.cshtml"
}
コード例 #24
0
        public bool TryGetValue(string path, out object value)
        {
            value = null;
            if (memory == null || path.Length == 0 || (path[0] != '[' && !char.IsLetter(path[0])))
            {
                return(false);
            }

            var parts = path.Split(".[]".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                        .Select(x => x.Trim('\'', '"'))
                        .ToArray();

            var curScope = memory;

            foreach (var part in parts)
            {
                string error = null;
                if (int.TryParse(part, out var idx) && BuiltInFunctions.TryParseList(curScope, out var li))
                {
                    (value, error) = BuiltInFunctions.AccessIndex(li, idx);
                    if (error != null)
                    {
                        return(false);
                    }
                }
                else
                {
                    if (!BuiltInFunctions.TryAccessProperty(curScope, part, out value))
                    {
                        return(false);
                    }
                }

                curScope = value;
            }

            return(true);
        }
コード例 #25
0
        // Genearte a new lookup function based on one lookup function
        private EvaluatorLookup CustomizedEvaluatorLookup(EvaluatorLookup baseLookup)
        => (string name) =>
        {
            var prebuiltPrefix = "prebuilt.";

            if (name.StartsWith(prebuiltPrefix))
            {
                return(baseLookup(name.Substring(prebuiltPrefix.Length)));
            }

            if (this.TemplateMap.ContainsKey(name))
            {
                return(new ExpressionEvaluator(name, BuiltInFunctions.Apply(this.TemplateEvaluator(name)), ReturnType.Object, this.ValidTemplateReference));
            }

            const string template = "template";

            if (name.Equals(template))
            {
                return(new ExpressionEvaluator(template, BuiltInFunctions.Apply(this.TemplateFunction()), ReturnType.Object, this.ValidateTemplateFunction));
            }

            const string fromFile = "fromFile";

            if (name.Equals(fromFile))
            {
                return(new ExpressionEvaluator(fromFile, BuiltInFunctions.Apply(this.FromFile()), ReturnType.String, this.ValidateFromFile));
            }

            const string activityAttachment = "ActivityAttachment";

            if (name.Equals(activityAttachment))
            {
                return(new ExpressionEvaluator(activityAttachment, BuiltInFunctions.Apply(this.ActivityAttachment()), ReturnType.Object, this.ValidateActivityAttachment));
            }

            return(baseLookup(name));
        };
コード例 #26
0
        // Genearte a new lookup function based on one lookup function
        private EvaluatorLookup CustomizedEvaluatorLookup(EvaluatorLookup baseLookup)
        => (string name) =>
        {
            var prebuiltPrefix = "prebuilt.";

            if (name.StartsWith(prebuiltPrefix))
            {
                return(baseLookup(name.Substring(prebuiltPrefix.Length)));
            }

            if (this.TemplateMap.ContainsKey(name))
            {
                return(new ExpressionEvaluator(name, BuiltInFunctions.Apply(this.TemplateEvaluator(name)), ReturnType.Object, this.ValidTemplateReference));
            }

            const string lgTemplate = "lgTemplate";

            if (name.Equals(lgTemplate))
            {
                return(new ExpressionEvaluator(lgTemplate, BuiltInFunctions.Apply(this.LgTemplate()), ReturnType.Object, this.ValidateLgTemplate));
            }

            return(baseLookup(name));
        };
コード例 #27
0
        private CSharpSyntaxNode CreateListInvocation(IList <IParseTree> children)
        {
            // macro invocation
            var head = this.Visit(children[0]);
            var tail = children.Skip(1).ToList();

            if (Macros.TryRunMacro(this, head.GetText().ToString(), tail, out CSharpSyntaxNode transformed))
            {
                return(transformed);
            }

            // built-in function invocation
            var builtIn = BuiltInFunctions.Run(this, children);

            if (builtIn != null)
            {
                return(builtIn);
            }

            // user function invocation
            var arguments = tail
                            .Select(child => this.Visit(child) as ExpressionSyntax)
                            .ToArray();

            switch (head)
            {
            case MemberAccessExpressionSyntax member: return(BuildInvocation(member, arguments));

            case InvocationExpressionSyntax invocation: return(BuildInvocation(invocation, arguments));

            case ExpressionSyntax expression: return(BuildInvocation(expression, arguments));

            default:
                throw new InvalidOperationException($"Unexpected first element in list: {head.GetType().FullName}");
            }
        }
コード例 #28
0
        // Genearte a new lookup function based on one lookup function
        private EvaluatorLookup CustomizedEvaluatorLookup(EvaluatorLookup baseLookup, bool isExpander)
        => (string name) =>
        {
            var prebuiltPrefix = "prebuilt.";

            if (name.StartsWith(prebuiltPrefix))
            {
                return(baseLookup(name.Substring(prebuiltPrefix.Length)));
            }

            if (this.TemplateMap.ContainsKey(name))
            {
                if (isExpander)
                {
                    return(new ExpressionEvaluator(name, BuiltInFunctions.Apply(this.TemplateExpander(name)), ReturnType.String, this.ValidTemplateReference));
                }
                else
                {
                    return(new ExpressionEvaluator(name, BuiltInFunctions.Apply(this.TemplateEvaluator(name)), ReturnType.String, this.ValidTemplateReference));
                }
            }

            return(baseLookup(name));
        };
コード例 #29
0
        public void TestAccumulatePath()
        {
            var memory = new SimpleObjectMemory(new
            {
                f = "foo",
                b = "bar",
                z = new
                {
                    z = "zar"
                },
                n = 2
            });

            var parser = new ExpressionEngine();

            // normal case, note, we doesn't append a " yet
            var exp = parser.Parse("a[f].b[n].z");

            var(path, left, err) = BuiltInFunctions.TryAccumulatePath(exp, memory);
            Assert.AreEqual(path, "a['foo'].b[2].z");

            // normal case
            exp = parser.Parse("a[z.z][z.z].y");
            (path, left, err) = BuiltInFunctions.TryAccumulatePath(exp, memory);
            Assert.AreEqual(path, "a['zar']['zar'].y");

            // normal case
            exp = parser.Parse("a.b[z.z]");
            (path, left, err) = BuiltInFunctions.TryAccumulatePath(exp, memory);
            Assert.AreEqual(path, "a.b['zar']");

            // stop evaluate at middle
            exp = parser.Parse("json(x).b");
            (path, left, err) = BuiltInFunctions.TryAccumulatePath(exp, memory);
            Assert.AreEqual(path, "b");
        }
コード例 #30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Expression"/> class.
 /// Built-in expression constructor.
 /// </summary>
 /// <param name="type">Type of built-in expression from <see cref="ExpressionType"/>.</param>
 /// <param name="children">Child expressions.</param>
 public Expression(string type, params Expression[] children)
 {
     Evaluator = BuiltInFunctions.Lookup(type);
     Children  = children;
 }
コード例 #31
0
public System.Web.WebPages.HelperResult FieldStartMarkerDiv(string fieldExpression)
{
#line default
#line hidden
return new System.Web.WebPages.HelperResult(__razor_helper_writer => {

#line 25 "..\..\Views\Shared\MainHelpers.cshtml"
 
    var fn = new BuiltInFunctions(TridionHelper.Engine, TridionHelper.Package);
    string tagString = fn.FieldStartMarker(fieldExpression);
    tagString = tagString.TrimEnd('>');
    tagString += " tag=\"div\">";

    

#line default
#line hidden

#line 31 "..\..\Views\Shared\MainHelpers.cshtml"
WriteTo(__razor_helper_writer, tagString);


#line default
#line hidden

#line 31 "..\..\Views\Shared\MainHelpers.cshtml"
              


#line default
#line hidden
});

#line 32 "..\..\Views\Shared\MainHelpers.cshtml"
}
コード例 #32
0
 public void Test_IpMatch()
 {
     Assert.True(BuiltInFunctions.IPMatch("192.168.2.123", "192.168.2.0/24"));
     Assert.False(BuiltInFunctions.IPMatch("192.168.2.123", "192.168.2.0/25"));
     Assert.False(BuiltInFunctions.IPMatch("192.168.2.123", "192.168.2.0"));
 }
コード例 #33
0
        // In this simple object scope, we don't allow you to set a path in which some parts in middle don't exist
        // for example
        // if you set dialog.a.b = x, but dialog.a don't exist, this will result in an error
        // because we can't and shouldn't smart create structure in the middle
        // you can implement a customzied Scope that support such behavior
        public void SetValue(string path, object value)
        {
            if (memory == null)
            {
                return;
            }

            var parts = path.Split(".[]".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                        .Select(x => x.Trim('\'', '"'))
                        .ToArray();

            var    curScope = memory;
            var    curPath  = string.Empty; // valid path so far
            string error    = null;

            // find the 2nd last value, ie, the container
            for (var i = 0; i < parts.Length - 1; i++)
            {
                if (int.TryParse(parts[i], out var index) && BuiltInFunctions.TryParseList(curScope, out var li))
                {
                    curPath          += $"[{parts[i]}]";
                    (curScope, error) = BuiltInFunctions.AccessIndex(li, index);
                }
                else
                {
                    curPath          += $".{parts[i]}";
                    (curScope, error) = BuiltInFunctions.AccessProperty(curScope, parts[i]);
                }

                if (error != null)
                {
                    return;
                }

                if (curScope == null)
                {
                    curPath = curPath.TrimStart('.');
                    return;
                }
            }

            // set the last value
            if (int.TryParse(parts.Last(), out var idx))
            {
                if (BuiltInFunctions.TryParseList(curScope, out var li))
                {
                    if (li is JArray)
                    {
                        value = JToken.FromObject(value);
                    }

                    if (idx > li.Count)
                    {
                        error = $"{idx} index out of range";
                    }
                    else if (idx == li.Count)
                    {
                        // expand for one
                        li.Add(value);
                    }
                    else
                    {
                        li[idx] = value;
                    }
                }
                else
                {
                    error = $"set value for an index to a non-list object";
                }

                if (error != null)
                {
                    return;
                }
            }
            else
            {
                (_, error) = BuiltInFunctions.SetProperty(curScope, parts.Last(), value);
                if (error != null)
                {
                    return;
                }
            }

            // Update the version once memory has been updated
            version++;
        }
コード例 #34
0
 /// <summary>
 /// Initializes the TridionRazorTemplate.
 /// </summary>
 /// <param name="engine"></param>
 /// <param name="package"></param>
 public void Initialize(Engine engine, Package package, Template template, List<string> assemblyReferences)
 {
     _engine = engine;
     _package = package;
     _tridionHelper = new TridionUtilities(engine, package);
     _razorTBB = template;
     _builtInFunctions = new BuiltInFunctions(engine, package);
     _references = assemblyReferences;
 }
コード例 #35
0
public System.Web.WebPages.HelperResult FieldStartMarker(string fieldExpression)
{
#line default
#line hidden
return new System.Web.WebPages.HelperResult(__razor_helper_writer => {

#line 19 "..\..\Views\Shared\MainHelpers.cshtml"
 
    var fn = new BuiltInFunctions(TridionHelper.Engine, TridionHelper.Package);
    

#line default
#line hidden

#line 21 "..\..\Views\Shared\MainHelpers.cshtml"
WriteTo(__razor_helper_writer, fn.FieldStartMarker(fieldExpression));


#line default
#line hidden

#line 21 "..\..\Views\Shared\MainHelpers.cshtml"
                                         


#line default
#line hidden
});

#line 22 "..\..\Views\Shared\MainHelpers.cshtml"
}