Пример #1
0
        public override bool Play(MappedItem control, Log log)
        {
            string expectedText = expressionParam.GetValue();

            if (expectedText == null)
                expectedText = "";

            foreach (Variable v in this.TestItem.Test.Variables.OrderBy(v => v.Name.Length))
            {
                expectedText = expectedText.Replace(v.Name, "\"" + v.Value + "\"");
            }

            var expression = new CompiledExpression(expectedText);

            try
            {
                EvaluatedResult = (bool)expression.Eval();

            }
            catch (Exception ex)
            {
                //expression was not a boolean
            }

            if (EvaluatedResult)
            {
                foreach (TestItem testItem in this.TestItem.TestItems)
                {
                    testItem.Play(log);
                }
            }

            return true;
        }
Пример #2
0
		public object Eval(string expr, Func<string,object> getVarValue) {
			CompiledExpression compiledExpr;
			if (!UseCache || !CachedExpressions.TryGetValue(expr, out compiledExpr)) {
				var linqExpr = Parse(expr);
				compiledExpr = new CompiledExpression() {
					Parameters = GetExpressionParameters(linqExpr)
				};
				var lambdaExpr = Expression.Lambda(linqExpr, compiledExpr.Parameters);
				compiledExpr.Lambda = lambdaExpr.Compile();
				
				if (UseCache)
					lock (CachedExpressions) {
						CachedExpressions[expr] = compiledExpr;
					}
			}

			var valuesList = new List<object>();
			foreach (var paramExpr in compiledExpr.Parameters) {
				valuesList.Add( new LambdaParameterWrapper( getVarValue(paramExpr.Name)) );
			}

			var lambdaRes = compiledExpr.Lambda.DynamicInvoke(valuesList.ToArray());
			if (lambdaRes is LambdaParameterWrapper)
				lambdaRes = ((LambdaParameterWrapper)lambdaRes).Value;
			return lambdaRes;
		}
Пример #3
0
        public decimal Evaluate(decimal input, decimal paramY)
        {
            var registry = new TypeRegistry();
            registry.RegisterType("m", typeof (Math));
            registry.RegisterSymbol("x", input);
            registry.RegisterSymbol("y", paramY);

            var expression = new CompiledExpression<decimal>(Expression)
            {
                TypeRegistry = registry
            };
            return expression.Eval();
        }
Пример #4
0
		protected override void Compile (Compiler c)
		{
			if (c.Debugger != null)
				c.Debugger.DebugCompile (c.Input);

			c.CheckExtraAttributes ("if", "test");

			c.AssertAttribute ("test");
			test = c.CompileExpression (c.GetAttribute ("test"));

			if (!c.Input.MoveToFirstChild ()) return;
			children = c.CompileTemplateContent ();
			c.Input.MoveToParent ();
		}	
Пример #5
0
		public XslKey (Compiler c)
		{
			this.name = c.ParseQNameAttribute ("name");

			c.KeyCompilationMode = true;
			useExpr = c.CompileExpression (c.GetAttribute ("use"));
			if (useExpr == null)
				useExpr = c.CompileExpression (".");

			c.AssertAttribute ("match");
			string matchString = c.GetAttribute ("match");
			this.matchPattern = c.CompilePattern (matchString, c.Input);
			c.KeyCompilationMode = false;
		}
Пример #6
0
 internal static object HandleResult(SerializedEvaluation evaluation, Func<string, IRpcRoot> referenceResolver)
 {
     if (evaluation == null || string.IsNullOrEmpty(evaluation.Evaluation))
         return null;
     
     var reg = new TypeRegistry();
     for (int i = 0; i < evaluation.References.Length; i++)
     {
         reg.RegisterSymbol("r" + (i + 1), referenceResolver(evaluation.References[i]));
     }
     var p = new CompiledExpression(evaluation.Evaluation)
     {
         TypeRegistry = reg
     };
     return p.Eval();
 }
Пример #7
0
 /// <summary>
 /// Function to call when a server request is received
 /// </summary>
 /// <param name="evaluation">The incoming request</param>
 /// <param name="referenceResolver">Your reference loader: Resolves references to server-side objects</param>
 /// <returns></returns>
 public static SerializedEvaluation HandleIncomingRequest(SerializedEvaluation evaluation, Func<string, IRpcRoot> referenceResolver)
 {
     var reg = new TypeRegistry();
     for (int i = 0; i < evaluation.References.Length; i++)
     {
         reg.RegisterSymbol("r" + (i + 1), referenceResolver(evaluation.References[i]));
     }
     var p = new CompiledExpression(evaluation.Evaluation)
     {
         TypeRegistry = reg
     };
     var ret = p.Eval();
     if (ret == null)
         return null;
     return new RpcCallVisitor().Serialize(Expression.Constant(ret));
 }
Пример #8
0
        internal static async Task<object> HandleResultAsync(SerializedEvaluation evaluation, Func<string, Task<IRpcRoot>> referenceResolver)
        {
            if (evaluation == null || string.IsNullOrEmpty(evaluation.Evaluation))
                return null;
            
            var reg = new TypeRegistry();

            for (int i = 0; i < evaluation.References.Length; i++)
            {
                reg.RegisterSymbol("r" + (i + 1), await referenceResolver(evaluation.References[i]).ConfigureAwait(false));
            }
            var p = new CompiledExpression(evaluation.Evaluation)
            {
                TypeRegistry = reg
            };
            return p.Eval();
        }
        public void TryGetValue_DefaultsToAnyEntryTest()
        {
            var target = new CompiledExpressionMap();

            CompiledExpression expectedExpression = new CompiledExpression<string, string>((string s) => s.ToUpperInvariant());

            target.Add("AnyKey", expectedExpression);

            bool expected = true;

            bool actual;
            CompiledExpression outExpression;

            actual = target.TryGetValue(out outExpression);

            Assert.Equal(expected, actual);
            Assert.Equal(expectedExpression, outExpression);
        }
        public void TryGetValueTest()
        {
            var target = new CompiledExpressionMap();

            CompiledExpression otherExpression1 = new CompiledExpression<string, string>((string s) => s.ToUpperInvariant());
            CompiledExpression otherExpression2 = new CompiledExpression<string, string>((string s) => s.Trim());
            CompiledExpression expectedExpression = new CompiledExpression<string, string>((string s) => s.ToLowerInvariant());

            target.Add(CompiledExpressionMap.DefaultLanguageKey, otherExpression1);
            target.Add("anyKey", otherExpression2);
            target.Add(ContextUiCulture, expectedExpression);

            bool expected = true;

            bool actual;
            CompiledExpression outExpression;

            actual = target.TryGetValue(out outExpression);

            Assert.Equal(expected, actual);
            Assert.Equal(expectedExpression, outExpression);
        }
        public bool Evaluate(State state)
        {
            if (_expression == null || _expression.Equals(string.Empty))
            {
                return true;
            }

            var expression = new CompiledExpression(this._expression);
            expression.RegisterType("h", typeof(ExpressionHelper));
            if (state != null)
            {
                foreach (var fluent in state.Fluents)
                {
                    expression.RegisterType(fluent.Name, fluent.Value);
                }
            }
            return (bool)expression.Eval();
        }
        /// <summary>
        /// Compile the expression
        /// </summary>
        public Expression Compile <TData>(Dictionary <String, Delegate> variableFunc)
        {
            ParameterExpression expressionParm = Expression.Parameter(typeof(TData), "_scope");
            Expression          body           = null;

            // Iterate and perform binary operations
            foreach (var itm in this.Clause)
            {
                Expression clauseExpr = null;
                if (itm is ProtocolWhenClauseCollection)
                {
                    clauseExpr = Expression.Invoke((itm as ProtocolWhenClauseCollection).Compile <TData>(variableFunc), expressionParm);
                }
                else if (itm is WhenClauseImsiExpression)
                {
                    var imsiExpr = itm as WhenClauseImsiExpression;
                    clauseExpr = Expression.Invoke(QueryExpressionParser.BuildLinqExpression <TData>(NameValueCollection.ParseQueryString(imsiExpr.Expression), variableFunc), expressionParm);
                    if (imsiExpr.NegationIndicator)
                    {
                        clauseExpr = Expression.Not(clauseExpr);
                    }
                    this.m_tracer.TraceVerbose("Converted WHEN {0} > {1}", imsiExpr.Expression, clauseExpr);
                }
                else if (itm is XmlLambdaExpression)
                {
                    var xmlLambda = itm as XmlLambdaExpression;
                    (itm as XmlLambdaExpression).InitializeContext(null);
                    // replace parameter
                    clauseExpr = Expression.Invoke(((itm as XmlLambdaExpression).ToExpression() as LambdaExpression), expressionParm);
                }
                else
                {
                    CompiledExpression <bool> exp = new CompiledExpression <bool>(itm as String);
                    exp.TypeRegistry = new TypeRegistry();
                    exp.TypeRegistry.RegisterDefaultTypes();
                    exp.TypeRegistry.RegisterType <TData>();
                    exp.TypeRegistry.RegisterType <Guid>();
                    exp.TypeRegistry.RegisterType <TimeSpan>();
                    exp.TypeRegistry.RegisterParameter("now", () => DateTime.Now); // because MONO is scumbag
                    foreach (var fn in variableFunc)
                    {
                        exp.TypeRegistry.RegisterParameter(fn.Key, fn.Value);
                    }
                    //exp.TypeRegistry.RegisterSymbol("data", expressionParm);
                    exp.ScopeCompile <TData>();
                    //Func<TData, bool> d = exp.ScopeCompile<TData>();
                    var linqAction = exp.GenerateLambda <Func <TData, bool>, TData>(true, false);
                    clauseExpr = Expression.Invoke(linqAction, expressionParm);
                    //clauseExpr = Expression.Invoke(d, expressionParm);
                }

                // Append to master expression
                if (body == null)
                {
                    body = clauseExpr;
                }
                else
                {
                    body = Expression.MakeBinary((ExpressionType)Enum.Parse(typeof(ExpressionType), this.Operator.ToString()), body, clauseExpr);
                }
            }

            // Wrap and compile
            var objParm       = Expression.Parameter(typeof(Object));
            var bodyCondition = Expression.Lambda <Func <TData, bool> >(body, expressionParm);
            var invoke        = Expression.Invoke(
                bodyCondition,
                Expression.Convert(objParm, typeof(TData))
                );
            var uncompiledExpression = Expression.Lambda <Func <Object, bool> >(invoke, objParm);

            this.m_compiledExpression = uncompiledExpression.Compile();
            return(uncompiledExpression);
        }
Пример #13
0
		internal CompiledExpression CompileExpression (string expression, bool isKey)
		{
			if (expression == null || expression == "") return null;

			Expression expr = xpathParser.Compile (expression);
			if (isKey)
				expr = new ExprKeyContainer (expr);
			CompiledExpression e = new CompiledExpression (expression, expr);

			return e;
		}
Пример #14
0
        private void ButtonGo_Click(object sender, RoutedEventArgs e)
        {
            var inputNav = GetResourceNavigator();

            if (inputNav == null)
            {
                return;
            }

            // Don't need to cache this, it is cached in the fhir-client
            CompiledExpression xps = null;

            try
            {
                xps = _compiler.Compile(textboxExpression.Text);
            }
            catch (Exception ex)
            {
                SetResults("Expression compilation error:\r\n" + ex.Message, true);
                return;
            }

            IEnumerable <IElementNavigator> prepopulatedValues = null;

            if (xps != null)
            {
                try
                {
                    if (inputNav is stu3.Hl7.Fhir.ElementModel.PocoNavigator)
                    {
                        prepopulatedValues = xps(inputNav, new fp3.FhirEvaluationContext(inputNav));
                    }
                    else
                    {
                        prepopulatedValues = xps(inputNav, new fp2.FhirEvaluationContext(inputNav));
                    }
                }
                catch (Exception ex)
                {
                    SetResults("Expression evaluation error:\r\n" + ex.Message);
                    AppendParseTree();
                    return;
                }

                ResetResults();
                try
                {
                    if (prepopulatedValues.Count() > 0)
                    {
                        string tooltip = null;
                        if (inputNav is stu3.Hl7.Fhir.ElementModel.PocoNavigator)
                        {
                            foreach (var t2 in fp3.ElementNavFhirExtensions.ToFhirValues(prepopulatedValues))
                            {
                                if (t2 != null)
                                {
                                    // output the content as XML fragments
                                    var fragment = s3.FhirSerializer.SerializeToXml(t2, root: t2.TypeName);
                                    AppendResults(fragment.Replace(" xmlns=\"http://hl7.org/fhir\"", ""));
                                }
                                // System.Diagnostics.Trace.WriteLine(string.Format("{0}: {1}", xpath.Value, t2.AsStringRepresentation()));
                            }
                        }
                        else if (inputNav is dstu2.Hl7.Fhir.ElementModel.PocoNavigator)
                        {
                            foreach (var t2 in fp2.ElementNavFhirExtensions.ToFhirValues(prepopulatedValues))
                            {
                                if (t2 != null)
                                {
                                    // output the content as XML fragments
                                    var fragment = s2.FhirSerializer.SerializeToXml(t2, root: t2.TypeName);
                                    AppendResults(fragment.Replace(" xmlns=\"http://hl7.org/fhir\"", ""), false, tooltip);
                                }
                                // System.Diagnostics.Trace.WriteLine(string.Format("{0}: {1}", xpath.Value, t2.AsStringRepresentation()));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    SetResults("Processing results error:\r\n" + ex.Message);
                    return;
                }
            }

            AppendParseTree();
        }
Пример #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="character"></param>
        /// <returns></returns>
        public bool Check(string conditions, CharacterEntity character)
        {
            if (string.IsNullOrWhiteSpace(conditions))
            {
                return(true);
            }

            Func <ConditionScope, bool> method;

            lock (m_compiledExpressions)
            {
                if (m_compiledExpressions.ContainsKey(conditions))
                {
                    method = m_compiledExpressions[conditions];
                }
                else
                {
                    if (conditions.Contains("BI")) // inutilisable
                    {
                        method = scope => false;
                    }
                    else
                    {
                        var hasTemplateRegex    = new Regex(@"PO==(?<HasTemplate>[0-9]*)", RegexOptions.Compiled);
                        var notHasTemplateRegex = new Regex(@"PO!=(?<NotHasTemplate>[0-9]*)", RegexOptions.Compiled);

                        var subCond = hasTemplateRegex.Replace(conditions, @"character.Inventory.HasTemplate(${HasTemplate})");
                        subCond = notHasTemplateRegex.Replace(subCond, @"character.Inventory.NotHasTemplate(${NotHasTemplate})");

                        // Nouvelle
                        var realConditions = new StringBuilder(subCond);

                        // Stats tot
                        realConditions.Replace("CI", "character.Statistics.GetTotal(EffectEnum.AddIntelligence)");
                        realConditions.Replace("CV", "character.Statistics.GetTotal(EffectEnum.AddVitality)");
                        realConditions.Replace("CA", "character.Statistics.GetTotal(EffectEnum.AddAgility)");
                        realConditions.Replace("CW", "character.Statistics.GetTotal(EffectEnum.AddWisdom)");
                        realConditions.Replace("CC", "character.Statistics.GetTotal(EffectEnum.AddChance)");
                        realConditions.Replace("CS", "character.Statistics.GetTotal(EffectEnum.AddStrength)");

                        // Stats base
                        realConditions.Replace("Ci", "character.DatabaseRecord.Intelligence");
                        realConditions.Replace("Cs", "character.DatabaseRecord.Strength");
                        realConditions.Replace("Cv", "character.DatabaseRecord.Vitality");
                        realConditions.Replace("Ca", "character.DatabaseRecord.Agility");
                        realConditions.Replace("Cw", "character.DatabaseRecord.Wisdom");
                        realConditions.Replace("Cc", "character.DatabaseRecord.Chance");

                        // Perso
                        realConditions.Replace("Ps", "character.AlignmentId");
                        realConditions.Replace("Pa", "character.AlignmentPromotion");
                        realConditions.Replace("PP", "character.AlignmentLevel");
                        realConditions.Replace("PL", "character.Level");
                        realConditions.Replace("PK", "character.Inventory.Kamas");
                        realConditions.Replace("PG", "character.BreedId");
                        realConditions.Replace("PS", "character.Sex");
                        realConditions.Replace("PZ", "1");                       // Abonné
                        realConditions.Replace("PN", "character.Name");
                        realConditions.Replace("PJ", "0");                       // HasJob
                        realConditions.Replace("MK", "0");                       // HasJob
                        realConditions.Replace("Pg", "0");                       // Don
                        realConditions.Replace("PR", "0");                       // Married
                        realConditions.Replace("PX", "character.Account.Power"); // Admin level
                        realConditions.Replace("PW", "10000");                   // MaxWeight
                        realConditions.Replace("PB", "character.Map.SubAreaId");
                        realConditions.Replace("SI", "character.MapId");
                        realConditions.Replace("MiS", "character.Id");

                        var registry = new TypeRegistry();
                        registry.RegisterType("EffectEnum", typeof(EffectEnum));

                        method = new CompiledExpression <bool>(realConditions.ToString())
                        {
                            TypeRegistry = registry
                        }.ScopeCompile <ConditionScope>();
                    }
                    m_compiledExpressions.Add(conditions, method);
                }
            }
            return(method(new ConditionScope(character)));
        }
Пример #16
0
        /// <summary>
        /// Binds the compiled expression.
        /// </summary>
        /// <returns></returns>
        public IBinaryDataListEntry BindCompiledExpression()
        {
            // very short circuit if no items ;)
            if (_internalKeyMap.Keys.Count == 0)
            {
                CompiledExpression = null;
                return(null);
            }

            // short circuit the long eval for mix mode data ;)
            if (_internalMap.Keys.Count <= 1 && FetchEvaluationIterationCount(Expression) == 1 && CompiledExpression.Length == 3)
            {
                return(_internalKeyMap.Values.FirstOrDefault());
            }

            var replaceValue = string.Empty;

            // Right now we assume there are not ;)
            foreach (var idx in _internalMap.Keys)
            {
                var token    = BuildSubToken(idx);
                var otherKey = _internalMap[idx];
                IBinaryDataListEntry value;
                if (_internalKeyMap.TryGetValue(otherKey, out value))
                {
                    if (value != null)
                    {
                        if (!value.IsRecordset)
                        {
                            var scalar = value.FetchScalar();
                            if (scalar != null)
                            {
                                if (_result == null)
                                {
                                    try
                                    {
                                        var toReplace = scalar.TheValue;
                                        CompiledExpression = CompiledExpression.Replace(token, toReplace);
                                    }
                                    catch (NullValueInVariableException)
                                    {
                                        CompiledExpression = CompiledExpression.Replace(token, null);
                                    }
                                }
                                else
                                {
                                    var    itr = _result.FetchRecordsetIndexes();
                                    string replaceVal;
                                    try
                                    {
                                        replaceVal = scalar.TheValue;
                                    }
                                    catch (NullValueInVariableException)
                                    {
                                        replaceVal = null;
                                    }

                                    while (itr.HasMore())
                                    {
                                        var val = itr.FetchNextIndex();

                                        // Fetch the next value from result ;)
                                        try
                                        {
                                            string error;
                                            string template = _result.TryFetchRecordsetColumnAtIndex(GlobalConstants.EvaluationRsField, val, out error).TheValue;
                                            Errors.AddError(error);

                                            template = template.Replace(token, replaceVal);
                                            _result.TryPutRecordItemAtIndex(new BinaryDataListItem(template, _ns, GlobalConstants.EvaluationRsField, val), val, out error);
                                            Errors.AddError(error);
                                        }
                                        catch (NullValueInVariableException)
                                        {
                                            //Do nothing got null
                                        }
                                    }

                                    CompiledExpression = CompiledExpression.Replace(token, replaceVal);
                                }
                            }
                        }
                        else
                        {
                            string error;
                            // build up the complex expression result - this means debug will be out of sync of complex expressions ;)
                            if (_result == null)
                            {
                                IList <Dev2Column> cols = new List <Dev2Column> {
                                    new Dev2Column(GlobalConstants.EvaluationRsField, enDev2ColumnArgumentDirection.Both)
                                };
                                _result = Dev2BinaryDataListFactory.CreateEntry(_ns, string.Empty, cols, BinaryDataList.UID);

                                var max = _internalKeyMap.Values.OrderByDescending(c => c.ItemCollectionSize()).FirstOrDefault();

                                if (max != null)
                                {
                                    var itrToVal = max.ItemCollectionSize();
                                    if (itrToVal == 0)
                                    {
                                        itrToVal = 1;
                                    }

                                    for (int i = 0; i < itrToVal; i++)
                                    {
                                        int idxT = (i + 1);
                                        _result.TryPutRecordItemAtIndex(new BinaryDataListItem(CompiledExpression, _ns, GlobalConstants.EvaluationRsField, idxT), idxT, out error);
                                        Errors.AddError(error);
                                    }
                                }

                                if (IsDebug)
                                {
                                    // attach audit object for debug ;)
                                    _result.ComplexExpressionAuditor = new ComplexExpressionAuditor();
                                }
                            }

                            var idxItr = value.FetchRecordsetIndexes();
                            int expIdx = 1;

                            // we need to treat this as a scalar ;)
                            if (idxItr.Count == 1)
                            {
                                int curVal = idxItr.FetchNextIndex();
                                int amt    = _result.ItemCollectionSize();
                                // ensure we always iterate once ;)
                                if (amt == 0)
                                {
                                    amt = 1;
                                }

                                idxItr = new LoopedIndexIterator(curVal, amt);
                            }

                            // else iterate across the recordset cuz it had a star ;)
                            while (idxItr.HasMore())
                            {
                                try
                                {
                                    var val = idxItr.FetchNextIndex();

                                    // Fetch the next value from result ;)
                                    var template = _result.TryFetchRecordsetColumnAtIndex(GlobalConstants.EvaluationRsField,
                                                                                          expIdx, out error).TheValue;
                                    Errors.AddError(error);

                                    var binaryValue = value.TryFetchIndexedRecordsetUpsertPayload(val, out error);
                                    Errors.AddError(error);

                                    // now bind this result row with the correct data list data ;)
                                    if (binaryValue != null)
                                    {
                                        var preTemplate = template;
                                        var toReplace   = binaryValue.TheValue;
                                        template = template.Replace(token, toReplace);

                                        // In cases when [[[{0}]] is the result, we need to inject the template value
                                        // In cases when [[rec({0}).a]] we need to replace the template pattern ;)
                                        var tmp = CompiledExpression.Replace("[", "").Replace("]", "").Replace(token, string.Empty);
                                        // ReSharper disable ConvertIfStatementToConditionalTernaryExpression
                                        if (tmp.Length > 0)
                                        // ReSharper restore ConvertIfStatementToConditionalTernaryExpression
                                        {
                                            // we have a [[rec({0}.a]] case ;)
                                            replaceValue = toReplace;
                                        }
                                        else
                                        {
                                            replaceValue = template;
                                        }

                                        _result.TryPutRecordItemAtIndex(new BinaryDataListItem(template, _ns, GlobalConstants.EvaluationRsField, expIdx), expIdx, out error);
                                        Errors.AddError(error);

                                        if (IsDebug)
                                        {
                                            var displayValue = DataListUtil.AddBracketsToValueIfNotExist(binaryValue.DisplayValue);
                                            _result.ComplexExpressionAuditor.AddAuditStep(preTemplate, displayValue, token, idx, template, Expression);
                                            _result.ComplexExpressionAuditor.SetMaxIndex(expIdx);
                                        }
                                    }

                                    expIdx++; // inc result index ;)
                                }
                                catch (NullValueInVariableException)
                                {
                                    //Do Nothing got null value
                                }
                            }

                            replaceValue       = DataListUtil.RemoveLanguageBrackets(replaceValue);
                            CompiledExpression = CompiledExpression.Replace(token, replaceValue);
                        }
                    }
                    else
                    {
                        CompiledExpression = CompiledExpression.Replace(token, string.Empty);
                    }
                }
            }

            return(_result);
        }
Пример #17
0
 public static bool Predicate(this CompiledExpression evaluator, IElementNavigator input, IElementNavigator container)
 {
     return(Predicate(evaluator, input, new EvaluationContext(container)));
 }
Пример #18
0
        public double Calculate(CompiledExpression compiledExpression, List <VariableValue> variableValues)
        {
            if (compiledExpression == null)
            {
                throw new ArgumentNullException("compiledExpression");
            }
            if (variableValues == null)
            {
                throw new ArgumentNullException("variableValues");
            }
            //
            List <double> calculationsStack = new List <double>();

            //
            for (int i = 0; i < compiledExpression.CompiledExpressionItems.Count; i++)
            {
                CompiledExpressionItem item = compiledExpression.CompiledExpressionItems[i];
                //
                switch (item.Kind)
                {
                case CompiledExpressionItemKind.Constant: {
                    calculationsStack.Add(item.Constant);
                    break;
                }

                case CompiledExpressionItemKind.Variable: {
                    // TODO: Add dictionary optimizations.
                    bool variableValueFound = false;
                    foreach (VariableValue variableValue in variableValues)
                    {
                        if (item.VariableName == variableValue.VariableName)
                        {
                            variableValueFound = true;
                            calculationsStack.Add(variableValue.Value);
                            break;
                        }
                    }
                    if (!variableValueFound)
                    {
                        throw new MathProcessorException(String.Format("Variable {0} is not initialized.", item.VariableName));
                    }
                    break;
                }

                case CompiledExpressionItemKind.Operation: {
                    Operation operation       = operationsRegistry.GetOperationByName(item.OperationName);
                    double[]  parametersArray = new double[operation.OperandsCount];
                    //
                    if (calculationsStack.Count - operation.OperandsCount < 0)
                    {
                        throw new MathProcessorException("Stack is empty.");
                    }
                    for (int j = 0; j < operation.OperandsCount; j++)
                    {
                        int index = calculationsStack.Count - operation.OperandsCount + j;
                        parametersArray[j] = calculationsStack[index];
                    }
                    //
                    calculationsStack.RemoveRange(calculationsStack.Count - operation.OperandsCount, operation.OperandsCount);
                    calculationsStack.Add(operation.Calculator.Calculate(parametersArray));
                    break;
                }

                default: {
                    throw new InvalidOperationException("Unknown item kind.");
                }
                }
            }
            //
            if (calculationsStack.Count != 1)
            {
                throw new MathProcessorException("Stack disbalance. Expression has invalid syntax.");
            }
            return(calculationsStack[0]);
        }
Пример #19
0
 public void ParseInvalidNumericThrowsException()
 {
     var str = "2.55X";
     var c   = new CompiledExpression(str);
     var ret = c.Eval();
 }
		internal static XPathExpression Compile (string xpath,
			NSResolver nsmgr, IStaticXsltContext ctx)
		{
			XPathParser parser = new XPathParser (ctx);
			CompiledExpression x = new CompiledExpression (xpath, parser.Compile (xpath));
			x.SetContext (nsmgr);
			return x;
		}
Пример #21
0
 public static object Scalar(this CompiledExpression evaluator, IElementNavigator input, EvaluationContext ctx)
 {
     return(evaluator.Scalar(input.ToTypedElement(), ctx));
 }
Пример #22
0
 public static bool IsBoolean(this CompiledExpression evaluator, bool value, IElementNavigator input, EvaluationContext ctx)
 {
     return(evaluator.IsBoolean(value, input.ToTypedElement(), ctx));
 }
Пример #23
0
 public static object Scalar(this CompiledExpression evaluator, IElementNavigator input, IElementNavigator container)
 {
     return(Scalar(evaluator, input, new EvaluationContext(container)));
 }
Пример #24
0
        /// <summary>
        /// Returns a compiled expression for specified source string.
        /// </summary>
        public CompiledExpression Compile(PreparedExpression preparedExpression)
        {
            if (preparedExpression == null)
            {
                throw new ArgumentNullException("preparedExpression");
            }

            OperationsStack operationsStack = new OperationsStack(operationsRegistry);

            for (int itemIndex = 0; itemIndex < preparedExpression.PreparedExpressionItems.Count; itemIndex++)
            {
                PreparedExpressionItem item = preparedExpression.PreparedExpressionItems[itemIndex];
                // If constant or variable - add to result
                if (item.Kind == PreparedExpressionItemKind.Constant)
                {
                    operationsStack.PushConstant(item.Constant);
                }
                if (item.Kind == PreparedExpressionItemKind.Variable)
                {
                    operationsStack.PushVariable(item.VariableName);
                }
                // If delimiter
                if (item.Kind == PreparedExpressionItemKind.Delimiter)
                {
                    operationsStack.PushDelimiter(item.DelimiterKind);
                }
                // Signature (operator signature / part of signature / function)
                if (item.Kind == PreparedExpressionItemKind.Signature)
                {
                    List <Operation> operations = new List <Operation>(operationsRegistry.GetOperationsUsingSignature(item.Signature));
                    operations.Sort(new Comparison <Operation>(compareOperationsByOperandsCount));

                    for (int i = 0; i < operations.Count; i++)
                    {
                        Operation operation = operations[i];
                        // Operator
                        if (operation.Kind == OperationKind.Operator)
                        {
                            // Unary operator
                            if (operation.OperandsCount == 1)
                            {
                                // If operator placed at the start of subexpression
                                if ((itemIndex == 0) ||
                                    ((itemIndex > 0) && (preparedExpression.PreparedExpressionItems[itemIndex - 1].Kind == PreparedExpressionItemKind.Delimiter) && (preparedExpression.PreparedExpressionItems[itemIndex - 1].DelimiterKind == DelimiterKind.OpeningBrace)))
                                {
                                    operationsStack.PushUnaryOperator(operation);
                                    break;
                                }
                            }
                            // Binary operator
                            if (operation.OperandsCount == 2)
                            {
                                operationsStack.PushBinaryOperator(operation);
                                break;
                            }
                            // Ternary and more
                            if (operation.OperandsCount > 2)
                            {
                                int partNumber = 0;
                                for (int k = 0; k < operation.Signature.Length; k++)
                                {
                                    if (operation.Signature[k] == item.Signature)
                                    {
                                        partNumber = k + 1;
                                        break;
                                    }
                                }
                                // If it is start part in signature
                                if (partNumber == 1)
                                {
                                    operationsStack.PushComplexOperatorFirstSignature(operation);
                                    break;
                                }

                                operationsStack.PushComplexOperatorNonFirstSignature(operation, partNumber);
                                break;
                            }
                        }
                        // Function
                        if (operation.Kind == OperationKind.Function)
                        {
                            operationsStack.PushFunction(operation);
                            break;
                        }
                    }
                }
            }

            operationsStack.DoFinalFlush();

            CompiledExpression res = operationsStack.GetResult();

            if (!isCompiledExpressionStackBalanced(res))
            {
                throw new CompilerSyntaxException("Operands disbalance detected.");
            }
            return(res);
        }
Пример #25
0
 public static bool IsBoolean(this CompiledExpression evaluator, bool value, IElementNavigator input, IElementNavigator container)
 {
     return(IsBoolean(evaluator, value, input, new EvaluationContext(container)));
 }
Пример #26
0
        static void Main(string[] args)
        {
            var cc = new CompiledExpression() { StringToParse = "Convert.ToBoolean(obj.result)==true" };
            object obj = new objHolder() { result = true };
            cc.RegisterType("obj", obj);
            cc.RegisterDefaultTypes();
            var result = cc.Eval();

            var x = new List<String>() { "Hello", "There", "World" };
            dynamic scope = new ExpandoObject();
            scope.x = x;
            var data = new MyClass { Value = () => false };
            var item = new MyClass { Value = () => true };
            scope.data = data;
            scope.item = item;
            scope.i = 1;
            var a = scope.data.Value() && scope.item.Value();
            //var b = !scope.data.Value() || scope.item.Value();

            System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
            var pi = Convert.ToString(3.141592654);
            var xs = 2d;
            var pipi = 3.141592654.ToString();
            var c0 = new CompiledExpression() { StringToParse = "3.141592654.ToString()" };
            var pi2 = c0.Eval();

            var p = scope.x[0];

            // (data.Value && !item.Value) ? 'yes' : 'no'
            var c = new CompiledExpression() { StringToParse = "data.Foo(30 + data.Bar(10))" };
            c.RegisterType("data", data);
            Console.WriteLine(data.X);
            c.Eval();
            //c.Call();
            Console.WriteLine(data.X);

            var c8= new CompiledExpression() { StringToParse = "data.X  + '%'" };
            c8.RegisterType("data", data);
            Console.WriteLine(data.X);
            var cr = c8.Eval();
            Console.WriteLine(data.X);

            var c1 = new CompiledExpression() { StringToParse = "Foo()" };
            var f1 = c1.ScopeCompileCall<MyClass>();
            Console.WriteLine(data.X);
            f1(data);
            Console.WriteLine(data.X);
            System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
            var fr = new CultureInfo("fr-FR");

            var qq = (25.82).ToString("0.00", fr) + "px";
            var test = "(25.82).ToString('0.00') + 'px'";
            var cx = new CompiledExpression() { StringToParse = "int.Parse('25.82', fr)" };
            cx.RegisterType("fr", fr);

            var c2 = new CompiledExpression() { StringToParse = "data.Foo()" };
            var y = 12 + "px";
            var f2 = c2.ScopeCompileCall();
            Console.WriteLine(scope.data.X);
            f2(scope);
            Console.WriteLine(scope.data.X);

            scope.c = new c();

            var c3 = new CompiledExpression() { StringToParse = "c.sum(1,2,3,4,5,6,7,8)" };
            var f3 = c3.ScopeCompile();
            var x3 = f3(scope);

            var c4 = new CompiledExpression() { StringToParse = "c.sum(1,2)" };
            var f4 = c4.ScopeCompile();
            var x4 = f4(scope);

            var c5 = new CompiledExpression() { StringToParse = "c.sum(1.0d,2.0d)" };
            var f5 = c5.ScopeCompile();
            var x5 = f5(scope);

            var c6 = new CompiledExpression() { StringToParse = "c.sum(1,2.0d)" };
            var f6 = c6.ScopeCompile();
            var x6 = f6(scope);

            Console.ReadLine();
        }
Пример #27
0
        public CommandReturn ExecuteCommand(string command, string target, string value, string condition, int?timeout, ref Dictionary <string, string> persistantVariables, out string stepValue)
        {
            stepValue = "";
            CommandReturn ret;

            bool playStep = true;

            // Option : Conditional execution (Selenium condition comment <-- condition=${variable1} == 5 --> )
            if (!String.IsNullOrEmpty(condition))
            {
                // internal variables
                foreach (var variable in persistantVariables)
                {
                    condition = condition.Replace("${" + variable.Key + "}", variable.Value);
                }

                // eval condition
                try
                {
                    var expression2 = condition.Replace("\"", "'").ToLower();
                    var expression  = new CompiledExpression()
                    {
                        StringToParse = expression2
                    };
                    var  result     = expression.Eval();
                    bool?boolResult = result as bool?;
                    playStep = (boolResult ?? true) != false;
                }
                catch (Exception ex)
                {
                    var commandReturn = new CommandReturn();
                    commandReturn.resultValue = ResultValue.ERROR;
                    commandReturn.isOk        = false;
                    commandReturn.message     = "Expression evaluator error: " + ex.Message;
                    return(commandReturn);
                }
            }

            if (!playStep)
            {
                var commandReturn = new CommandReturn();
                commandReturn.resultValue = ResultValue.COMMAND_OK;
                commandReturn.isOk        = true;
                commandReturn.message     = "Step not played by condition";
                return(commandReturn);
            }

            try
            {
                stepValue = "";
                string sPattern = @"\${\w*?}";

                if (System.Text.RegularExpressions.Regex.IsMatch(target, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {
                    if (persistantVariables != null)
                    {
                        var rgx = new System.Text.RegularExpressions.Regex(sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                        foreach (System.Text.RegularExpressions.Match m in rgx.Matches(target))
                        {
                            if (!string.IsNullOrWhiteSpace(m.Value))
                            {
                                string varFound = persistantVariables[m.Value.Replace("${", "").Replace("}", "")];
                                target = target.Replace(m.Value, varFound);
                            }
                        }
                    }
                }

                if (System.Text.RegularExpressions.Regex.IsMatch(value, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {
                    if (persistantVariables != null)
                    {
                        var rgx = new System.Text.RegularExpressions.Regex(sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                        foreach (System.Text.RegularExpressions.Match m in rgx.Matches(value))
                        {
                            if (!string.IsNullOrWhiteSpace(m.Value))
                            {
                                string varFound = persistantVariables[m.Value.Replace("${", "").Replace("}", "")];
                                value = value.Replace(m.Value, varFound);
                            }
                        }
                    }
                }

                if (_appiumMetaPilot == null)
                {
                    var commandReturn = new CommandReturn();
                    commandReturn.resultValue = ResultValue.ERROR;
                    commandReturn.isOk        = false;
                    commandReturn.message     = "appiumPilot is null";

                    return(commandReturn);
                }

                if (_appiumMetaPilot.AppiumDriver == null)
                {
                    var commandReturn = new CommandReturn();
                    commandReturn.resultValue = ResultValue.ERROR;
                    commandReturn.message     = "iosDriver & androidDriver are null";
                    return(commandReturn);
                }


                switch (command)
                {
                case "backGroundApp":
                    ret = _appiumMetaPilot.BackGroundApp(target, value);
                    break;

                case "click":
                case "clickAndWait":
                    ret = _appiumMetaPilot.Click(target);
                    break;

                case "sendkeys":
                case "sendKeys":
                case "type":
                    ret = _appiumMetaPilot.SendKeys(target, value);
                    break;

                case "verifyText":
                    ret = _appiumMetaPilot.VerifyText(target, value);
                    break;

                case "tap":
                    ret = _appiumMetaPilot.Tap(target, value);
                    break;

                case "waitForElementPresent":
                case "waitforvisible":
                    ret = _appiumMetaPilot.WaitForVisible(target, value, timeout ?? 30);
                    break;

                case "deviceOrientation":
                    ret = _appiumMetaPilot.DeviceOrientation(target);
                    break;

                case "echo":
                    ret = _appiumMetaPilot.Echo(target, value, out stepValue);
                    break;

                case "storeVisible":
                    ret = _appiumMetaPilot.StoreVisible(target, value, ref persistantVariables);
                    break;

                case "swipe":
                    ret = _appiumMetaPilot.Swipe(target);
                    break;

                case "selectAndWait":
                    ret = _appiumMetaPilot.SelectAndWait(target, value, timeout ?? 30);
                    break;

                case "assertElementPresent":
                case "verifyElementPresent":
                    ret = _appiumMetaPilot.VerifyElementPresent(target, value);
                    break;

                case "pause":
                case "Pause":
                    var returnValue = new CommandReturn();
                    if (!int.TryParse(target, out var secs))
                    {
                        secs = 0;
                    }
                    Thread.Sleep(secs);
                    returnValue.resultValue = ResultValue.COMMAND_OK;
                    ret = returnValue;
                    break;

                default:
                    ret             = new CommandReturn();
                    ret.resultValue = ResultValue.INVALID_COMMAND;
                    break;
                }
                if (ret.resultValue == ResultValue.COMMAND_OK || ret.resultValue == ResultValue.VERIFICATION_OK)
                {
                    ret.isOk = true;
                }
                else
                {
                    ret.isOk = false;
                }
            }
            catch (Exception ex)
            {
                ret             = new CommandReturn();
                ret.resultValue = ResultValue.ERROR;
                ret.message     = "Error in ExecuteCommand()";
                ret.isOk        = false;
            }
            return(ret);
        }
Пример #28
0
 public MathParser(string expression)
 {
     Initialize();
     mathExpression = BuildMathExpression(expression);
 }
Пример #29
0
 public ComputedPropertyEnricher(string propertyName, CompiledExpression computeValue)
 {
     _propertyName = propertyName ?? throw new ArgumentNullException(nameof(propertyName));
     _computeValue = computeValue ?? throw new ArgumentNullException(nameof(computeValue));
 }
        private void ButtonGo_Click(object sender, RoutedEventArgs e)
        {
            var inputNav = GetResourceNavigator();

            if (inputNav == null)
            {
                return;
            }

            // Don't need to cache this, it is cached in the fhir-client
            CompiledExpression xps = null;

            try
            {
                xps = _compiler.Compile(textboxExpression.Text);
            }
            catch (Exception ex)
            {
                textboxResult.Text = "Expression compilation error:\r\n" + ex.Message;
                return;
            }

            IEnumerable <IValueProvider> prepopulatedValues = null;

            if (xps != null)
            {
                try
                {
                    prepopulatedValues = xps(inputNav, inputNav);
                }
                catch (Exception ex)
                {
                    textboxResult.Text = "Expression evaluation error:\r\n" + ex.Message;
                    AppendParseTree();
                    return;
                }

                textboxResult.Text = null;
                try
                {
                    if (prepopulatedValues.Count() > 0)
                    {
                        foreach (var t2 in prepopulatedValues.ToFhirValues())
                        {
                            if (t2 != null)
                            {
                                // output the content as XML fragments
                                var fragment = dstu2.Hl7.Fhir.Serialization.FhirSerializer.SerializeToXml(t2);
                                textboxResult.Text += fragment.Replace(" xmlns=\"http://hl7.org/fhir\"", "") + "\r\n";
                            }
                            // System.Diagnostics.Trace.WriteLine(string.Format("{0}: {1}", xpath.Value, t2.AsStringRepresentation()));
                        }
                    }
                }
                catch (Exception ex)
                {
                    textboxResult.Text = "Processing results error:\r\n" + ex.Message;
                    return;
                }
            }

            AppendParseTree();
        }
Пример #31
0
        static void Main(string[] args)
        {
            var cc = new CompiledExpression()
            {
                StringToParse = "Convert.ToBoolean(obj.result)==true"
            };
            object obj = new objHolder()
            {
                result = true
            };

            cc.RegisterType("obj", obj);
            cc.RegisterDefaultTypes();
            var result = cc.Eval();

            var x = new List <String>()
            {
                "Hello", "There", "World"
            };
            dynamic scope = new ExpandoObject();

            scope.x = x;
            var data = new MyClass {
                Value = () => false
            };
            var item = new MyClass {
                Value = () => true
            };

            scope.data = data;
            scope.item = item;
            scope.i    = 1;
            var a = scope.data.Value() && scope.item.Value();

            //var b = !scope.data.Value() || scope.item.Value();

            System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
            var pi   = Convert.ToString(3.141592654);
            var xs   = 2d;
            var pipi = 3.141592654.ToString();
            var c0   = new CompiledExpression()
            {
                StringToParse = "3.141592654.ToString()"
            };
            var pi2 = c0.Eval();

            var p = scope.x[0];

            // (data.Value && !item.Value) ? 'yes' : 'no'
            var c = new CompiledExpression()
            {
                StringToParse = "data.Foo(30 + data.Bar(10))"
            };

            c.RegisterType("data", data);
            Console.WriteLine(data.X);
            c.Eval();
            //c.Call();
            Console.WriteLine(data.X);

            var c8 = new CompiledExpression()
            {
                StringToParse = "data.X  + '%'"
            };

            c8.RegisterType("data", data);
            Console.WriteLine(data.X);
            var cr = c8.Eval();

            Console.WriteLine(data.X);


            var c1 = new CompiledExpression()
            {
                StringToParse = "Foo()"
            };
            var f1 = c1.ScopeCompileCall <MyClass>();

            Console.WriteLine(data.X);
            f1(data);
            Console.WriteLine(data.X);
            System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
            var fr = new CultureInfo("fr-FR");

            var qq   = (25.82).ToString("0.00", fr) + "px";
            var test = "(25.82).ToString('0.00') + 'px'";
            var cx   = new CompiledExpression()
            {
                StringToParse = "int.Parse('25.82', fr)"
            };

            cx.RegisterType("fr", fr);


            var c2 = new CompiledExpression()
            {
                StringToParse = "data.Foo()"
            };
            var y  = 12 + "px";
            var f2 = c2.ScopeCompileCall();

            Console.WriteLine(scope.data.X);
            f2(scope);
            Console.WriteLine(scope.data.X);

            scope.c = new c();

            var c3 = new CompiledExpression()
            {
                StringToParse = "c.sum(1,2,3,4,5,6,7,8)"
            };
            var f3 = c3.ScopeCompile();
            var x3 = f3(scope);

            var c4 = new CompiledExpression()
            {
                StringToParse = "c.sum(1,2)"
            };
            var f4 = c4.ScopeCompile();
            var x4 = f4(scope);

            var c5 = new CompiledExpression()
            {
                StringToParse = "c.sum(1.0d,2.0d)"
            };
            var f5 = c5.ScopeCompile();
            var x5 = f5(scope);

            var c6 = new CompiledExpression()
            {
                StringToParse = "c.sum(1,2.0d)"
            };
            var f6 = c6.ScopeCompile();
            var x6 = f6(scope);

            Console.ReadLine();
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var questionnaire = (QuestionnaireWithResultsViewModel)value;

            if (questionnaire.MustAcceptTerms && !questionnaire.HasAcceptedTerms)
            {
                return(new ValidationResult(T("Please, accept our terms and conditions!").Text));
            }
            else
            {
                // valido le risposte in base alle condizioni dato che solo in questo oggetto ho la visione di insieme
                var singleChoice = questionnaire.QuestionsWithResults.Where(w => w.SingleChoiceAnswer > 0).Select(s => s.SingleChoiceAnswer);
                var multiChoice  = questionnaire.QuestionsWithResults
                                   .SelectMany(s => s.AnswersWithResult)
                                   .Where(w => w.Answered)
                                   .Select(s2 => s2.Id);
                _answerIds = singleChoice.Union(multiChoice);
                var validationErrors  = new List <string>();
                var requiredQuestions = questionnaire.QuestionsWithResults.Where(w => String.IsNullOrWhiteSpace(w.Condition) && w.IsRequired);
                foreach (var q in requiredQuestions)
                {
                    switch (q.QuestionType)
                    {
                    case QuestionType.OpenAnswer:
                        if (string.IsNullOrWhiteSpace(q.OpenAnswerAnswerText))
                        {
                            validationErrors.Add(String.Format(T("You have to answer to {0}").Text, q.Question));
                        }
                        break;

                    case QuestionType.MultiChoice:
                        if (q.AnswersWithResult.Count(w => w.Answered) == 0)
                        {
                            validationErrors.Add(String.Format(T("You have to answer to {0}").Text, q.Question));
                        }
                        break;

                    case QuestionType.SingleChoice:
                        if (q.SingleChoiceAnswer <= 0)
                        {
                            validationErrors.Add(String.Format(T("You have to answer to {0}").Text, q.Question));
                        }
                        break;
                    }
                }

                var conditionalQuestions = questionnaire.QuestionsWithResults.Where(w => !String.IsNullOrWhiteSpace(w.Condition) && w.IsRequired);

                foreach (var q in conditionalQuestions)
                {
                    // verifico per ogni question condizionale se tra tutte le risposte date la condizione è soddisfatta
                    var condition = Regex.Replace(q.Condition, "[0-9]+", new MatchEvaluator(HasThisAnswer));
                    condition = condition.Replace("and", "&&").Replace("or", "||");
                    var expression      = new CompiledExpression(condition);
                    var conditionResult = expression.Eval();
                    if (((bool)conditionResult && q.ConditionType == ConditionType.Show) || ((!(bool)conditionResult) && q.ConditionType == ConditionType.Hide))
                    {
                        // Se la condizione è vera allora ho la condizione soddisfatta
                        if (q.IsRequired)
                        {
                            // quindi la domanda è visibile a video e se è required deve avere una risposta pertinente
                            if (q.QuestionType == QuestionType.OpenAnswer)
                            {
                                if (String.IsNullOrWhiteSpace(q.OpenAnswerAnswerText))
                                {
                                    validationErrors.Add(String.Format(T("You have to answer to {0}").Text, q.Question));
                                }
                                else
                                {
                                    var textValidationError = String.Format(T(ValidateCommons.ValidateAnswerText(q.OpenAnswerAnswerText, q.AnswerType)).Text, q.Question);
                                    if (!String.IsNullOrWhiteSpace(textValidationError))
                                    {
                                        validationErrors.Add(textValidationError);
                                    }
                                }
                            }
                            else if (q.QuestionType == QuestionType.SingleChoice && q.SingleChoiceAnswer <= 0)
                            {
                                validationErrors.Add(String.Format(T("You have to answer to {0}").Text, q.Question));
                            }
                            else if (q.QuestionType == QuestionType.MultiChoice && q.AnswersWithResult.Count(w => w.Answered) == 0)
                            {
                                validationErrors.Add(String.Format(T("You have to answer to {0}").Text, q.Question));
                            }
                        }
                        else
                        {
                            if (q.QuestionType == QuestionType.OpenAnswer && !String.IsNullOrWhiteSpace(q.OpenAnswerAnswerText))
                            {
                                var textValidationError = String.Format(T(ValidateCommons.ValidateAnswerText(q.OpenAnswerAnswerText, q.AnswerType)).Text, q.Question);
                                if (!String.IsNullOrWhiteSpace(textValidationError))
                                {
                                    validationErrors.Add(textValidationError);
                                }
                            }
                        }
                    }
                    else if (((bool)conditionResult && q.ConditionType == ConditionType.Hide) || ((!(bool)conditionResult) && q.ConditionType == ConditionType.Show))
                    {
                        // Se la condizione è vera e deve nascondere oppure la condizione è falsa
                        q.OpenAnswerAnswerText = "";
                        q.SingleChoiceAnswer   = 0;
                        for (var i = 0; i < q.AnswersWithResult.Count(); i++)
                        {
                            q.AnswersWithResult[i].Answered = false;
                        }
                    }
                }
                if (validationErrors.Count() > 0)
                {
                    return(new ValidationResult(String.Join("\r\n", validationErrors)));
                }
            }
            return(ValidationResult.Success);
        }
Пример #33
0
		private CompiledExpression (CompiledExpression other)
		{
			_nsm = other._nsm;
			_expr = other._expr;
			rawExpression = other.rawExpression;
		}
Пример #34
0
 public static CompiledExpression <T> Compile <T>([NotNull] this IExpression <T> expression)
 => CompiledExpression <T> .Compile(expression);
        public bool Evaluate(IEnumerable<Tuple<string, bool>> values)
        {
            if (_expression == null || _expression.Equals(string.Empty))
            {
                return true;
            }

            var expression = new CompiledExpression(this._expression);
            expression.RegisterType("h", typeof(ExpressionHelper));
            if (values != null)
            {
                foreach (var value in values)
                {
                    expression.RegisterType(value.Item1, value.Item2);
                }
            }
            return (bool)expression.Eval();
        }
Пример #36
0
        public CompiledExpression Optimize(CompiledExpression compiledExpression)
        {
            if (compiledExpression == null)
            {
                throw new ArgumentNullException("compiledExpression");
            }

            List <CompiledExpressionItem> optimizedExpression = new List <CompiledExpressionItem>();

            for (int i = 0; i < compiledExpression.CompiledExpressionItems.Count; i++)
            {
                CompiledExpressionItem item = compiledExpression.CompiledExpressionItems[i];

                switch (item.Kind)
                {
                case CompiledExpressionItemKind.Constant:
                {
                    optimizedExpression.Add(item);
                    break;
                }

                case CompiledExpressionItemKind.Variable:
                {
                    optimizedExpression.Add(item);
                    break;
                }

                case CompiledExpressionItemKind.Operation:
                {
                    Operation operation = operationsRegistry.GetOperationByName(item.OperationName);
                    // If all arguments are constants, we can optimize this. Otherwise, we can't
                    bool noVariablesInArguments = true;
                    for (int j = 0; (j < operation.OperandsCount) && noVariablesInArguments; j++)
                    {
                        int index = optimizedExpression.Count - operation.OperandsCount + j;
                        if (index < 0)
                        {
                            throw new MathProcessorException("Stack is empty.");
                        }

                        if (optimizedExpression[index].Kind != CompiledExpressionItemKind.Constant)
                        {
                            noVariablesInArguments = false;
                        }
                    }
                    if (noVariablesInArguments)
                    {
                        double[] arguments = new double[operation.OperandsCount];
                        for (int j = optimizedExpression.Count - operation.OperandsCount, k = 0; j < optimizedExpression.Count; j++, k++)
                        {
                            arguments[k] = optimizedExpression[j].Constant;
                        }

                        optimizedExpression.RemoveRange(optimizedExpression.Count - operation.OperandsCount, operation.OperandsCount);
                        optimizedExpression.Add(new CompiledExpressionItem(CompiledExpressionItemKind.Constant,
                                                                           operation.Calculator.Calculate(arguments)));
                    }
                    else
                    {
                        optimizedExpression.Add(item);
                    }
                    break;
                }

                default:
                {
                    throw new InvalidOperationException("Unknown item kind.");
                }
                }
            }
            return(new CompiledExpression(optimizedExpression));
        }
Пример #37
0
        // Parses expressions of the form "eval{expression}". Expressions cannot be nested.
        // Returns list of complete expressions (used as base replacement text) and evaluation results
        private List<ParsedEvaluation> ParseEvaluations(string fieldReplacedTemplatedExpression)
        {
            List<ParsedEvaluation> parsedEvaluations = new List<ParsedEvaluation>();

            #if DNF46

            Match match = m_evaluationParser.Match(fieldReplacedTemplatedExpression);

            if (match.Success)
            {
                foreach (Capture capture in match.Captures)
                {
                    CompiledExpression expression = new CompiledExpression(capture.Value);
                    string source = string.Format("eval{0}{1}{2}", m_startTokenDelimiter, capture.Value, m_endTokenDelimiter);
                    string result = expression.Eval().ToString();
                    parsedEvaluations.Add(new ParsedEvaluation(source, result));
                }
            }

            #endif

            return parsedEvaluations;
        }
Пример #38
0
 public static bool Predicate(this CompiledExpression evaluator, IElementNavigator input, EvaluationContext ctx)
 {
     return(evaluator.Predicate(input.ToTypedElement(), ctx));
 }
Пример #39
0
        public Function(String expression)
        {
            PreparedExpression preparedExpression = ToolsHelper.Parser.Parse(expression);

            compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);
        }
Пример #40
0
        public PreparedExpression Decompile(CompiledExpression compiledExpression)
        {
            if (compiledExpression == null)
            {
                throw new ArgumentNullException("compiledExpression");
            }

            List <DecompiledExpressionItem> decompilationStack = new List <DecompiledExpressionItem>();

            for (int i = 0; i < compiledExpression.CompiledExpressionItems.Count; i++)
            {
                CompiledExpressionItem item = compiledExpression.CompiledExpressionItems[i];

                switch (item.Kind)
                {
                case CompiledExpressionItemKind.Constant:
                {
                    List <PreparedExpressionItem> items = new List <PreparedExpressionItem>();
                    items.Add(new PreparedExpressionItem(PreparedExpressionItemKind.Constant, item.Constant));
                    decompilationStack.Add(new DecompiledExpressionItem(false, new PreparedExpression(items)));
                    break;
                }

                case CompiledExpressionItemKind.Variable:
                {
                    List <PreparedExpressionItem> items = new List <PreparedExpressionItem>();
                    items.Add(new PreparedExpressionItem(PreparedExpressionItemKind.Variable, item.VariableName));
                    decompilationStack.Add(new DecompiledExpressionItem(false, new PreparedExpression(items)));
                    break;
                }

                case CompiledExpressionItemKind.Operation:
                {
                    Operation operation = operationsRegistry.GetOperationByName(item.OperationName);
                    List <PreparedExpressionItem> resultExpression = new List <PreparedExpressionItem>();
                    // Begining to construct a new expression string
                    if (operation.Kind == OperationKind.Function)
                    {
                        resultExpression.Add(new PreparedExpressionItem(PreparedExpressionItemKind.Signature, operation.Signature[0]));
                        resultExpression.Add(new PreparedExpressionItem(PreparedExpressionItemKind.Delimiter, DelimiterKind.OpeningBrace));
                    }
                    else if (operation.OperandsCount == 1)
                    {
                        // Unary operator
                        resultExpression.Add(new PreparedExpressionItem(PreparedExpressionItemKind.Signature, operation.Signature[0]));
                    }
                    // For each argument we have to determine, need there are braces or not
                    for (int j = 0; j < operation.OperandsCount; j++)
                    {
                        int index = decompilationStack.Count - operation.OperandsCount + j;
                        if (index < 0)
                        {
                            throw new MathProcessorException("Stack is empty.");
                        }

                        DecompiledExpressionItem decompiledItem = decompilationStack[index];
                        bool applyBraces = false;
                        if (operation.Kind != OperationKind.Function)
                        {
                            // First argument
                            if (j == 0)
                            {
                                if (decompiledItem.IsComplex)
                                {
                                    if (decompiledItem.LastOperation.Kind != OperationKind.Function)
                                    {
                                        if (decompiledItem.LastOperation.OperandsCount == 1)
                                        {
                                            applyBraces = true;
                                        }
                                        else
                                        {
                                            if (operation.Priority < decompiledItem.LastOperation.Priority)
                                            {
                                                applyBraces = true;
                                            }
                                            else if (operation.Priority == decompiledItem.LastOperation.Priority)
                                            {
                                                if (operationsRegistry.GetAssociationByPriority(operation.Priority) == PriorityAssociation.RightAssociated)
                                                {
                                                    applyBraces = true;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            // Last argument
                            if (j == operation.OperandsCount - 1)
                            {
                                if (decompiledItem.IsComplex)
                                {
                                    if (decompiledItem.LastOperation.Kind != OperationKind.Function)
                                    {
                                        if (decompiledItem.LastOperation.OperandsCount == 1)
                                        {
                                            applyBraces = true;
                                        }
                                        else
                                        {
                                            if (operation.Priority < decompiledItem.LastOperation.Priority)
                                            {
                                                applyBraces = true;
                                            }
                                            else if (operation.Priority == decompiledItem.LastOperation.Priority)
                                            {
                                                if (operationsRegistry.GetAssociationByPriority(operation.Priority) == PriorityAssociation.LeftAssociated)
                                                {
                                                    applyBraces = true;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (applyBraces)
                        {
                            resultExpression.Add(new PreparedExpressionItem(PreparedExpressionItemKind.Delimiter, DelimiterKind.OpeningBrace));
                        }
                        resultExpression.AddRange(decompiledItem.Expression.PreparedExpressionItems);
                        if (applyBraces)
                        {
                            resultExpression.Add(new PreparedExpressionItem(PreparedExpressionItemKind.Delimiter, DelimiterKind.ClosingBrace));
                        }


                        // Appending delimiters between arguments
                        if (j < operation.OperandsCount - 1)
                        {
                            if (operation.Kind == OperationKind.Function)
                            {
                                resultExpression.Add(new PreparedExpressionItem(PreparedExpressionItemKind.Delimiter, DelimiterKind.Comma));
                            }
                            else
                            {
                                resultExpression.Add(new PreparedExpressionItem(PreparedExpressionItemKind.Signature, operation.Signature[j]));
                            }
                        }
                    }
                    decompilationStack.RemoveRange(decompilationStack.Count - operation.OperandsCount, operation.OperandsCount);

                    if (operation.Kind == OperationKind.Function)
                    {
                        resultExpression.Add(new PreparedExpressionItem(PreparedExpressionItemKind.Delimiter, DelimiterKind.ClosingBrace));
                    }

                    decompilationStack.Add(new DecompiledExpressionItem(true, new PreparedExpression(resultExpression), operation));
                    break;
                }

                default:
                {
                    throw new InvalidOperationException("Unknown item kind.");
                }
                }
            }

            if (decompilationStack.Count != 1)
            {
                throw new MathProcessorException("Stack disbalance. Expression has invalid syntax.");
            }
            return(decompilationStack[0].Expression);
        }
Пример #41
0
 protected CompiledExpression SetPropertyExpression(string key, LambdaExpression expression)
 {
     var compiledExpression = new CompiledExpression(expression);
     PropertyExpressions[key] = compiledExpression;
     return compiledExpression;
 }
 public CompiledFormattedExpression(CompiledExpression expression, string?format, Alignment?alignment)
 {
     _expression = expression ?? throw new ArgumentNullException(nameof(expression));
     _format     = format;
     _alignment  = alignment;
 }