Exemplo n.º 1
0
        public void PassNullParameter()
        {
            var eval = new FormulaEvaluator();

            eval.Evaluate("{{\"Hello \"+a}}", new Parameter("a", null)).Should().Be("Hello ");
            eval.Evaluate("{{1+a}}", new Parameter("a", null)).Should().Be(null);
            //TODO: eval.Evaluate("{{\"City: \"+Iif(a==null, string.Empty, a.City}}", new Parameter("a", null)).Should().Be("City: ");
        }
Exemplo n.º 2
0
        public void MultipleExpressionsWithNullResult()
        {
            var eval = new FormulaEvaluator();

            eval.AddVariable("a", null);
            eval.AddVariable("b", 1);
            eval.Evaluate("{{a}}{{b}}").Should().Be(1);
            eval.Evaluate("{{b}}{{a}}").Should().Be("1");
        }
Exemplo n.º 3
0
        public void FormulaEvaluatorTests1()
        {
            var eval = new FormulaEvaluator();

            eval.AddVariable("a", 2);
            eval.AddVariable("b", 3);
            eval.Evaluate("{{\"test\"}}").Should().Be("test");
            eval.Evaluate("{{a+b}}").Should().Be(5);
            eval.Evaluate("{{c}}+{{d}}={{c+d}}", new Parameter("c", 3), new Parameter("d", 6)).Should().Be("3+6=9");
            eval.Evaluate("{{c}}+{{d}}={{c+d}}", new Parameter("c", 7), new Parameter("d", 8)).Should().Be("7+8=15");
        }
Exemplo n.º 4
0
        public void EvalDictionaryParams()
        {
            Parameter CreateDicParameter(string name) => new Parameter("item", new Dictionary <string, object>
            {
                { "Name", new Dictionary <string, object> {
                      { "FirstName", name }
                  } }
            });

            var eval = new FormulaEvaluator();

            eval.Evaluate("{{item.Name.FirstName}}", CreateDicParameter("Julio")).Should().Be("Julio");
            eval.Evaluate("{{item.Name.FirstName}}", CreateDicParameter("John")).Should().Be("John");
        }
Exemplo n.º 5
0
        public FormulaCalculateResponse Calculate(CalculateFormulaRequest calculateFormulaRequest)
        {
            try
            {
                var formula = StringHelper.Base64ToString(calculateFormulaRequest.Formula);

                var formulaDataWrapper = new FormulaDataWrapper
                {
                    Data = calculateFormulaRequest.Data
                };

                var json = TradeCubeJsonSerializer.Serialize(formulaDataWrapper);
                var formulaEvaluatorRequest = new FormulaEvaluatorRequest(json, formula, "main")
                {
                    TimeoutInterval = calculateFormulaRequest.TimeoutSeconds
                };

                return(FormulaEvaluator.Evaluate(formulaEvaluatorRequest));
            }
            catch (Exception ex)
            {
                return(new FormulaCalculateResponse
                {
                    IsSuccess = false,
                    Message = ex.Message
                });
            }
        }
Exemplo n.º 6
0
        public void UsingDynamicLinqTypeTest()
        {
            var eval = new FormulaEvaluator();

            eval.AddVariable("a", "1");
            eval.Evaluate("{{EvaluateUtils.ParseAsInt(a).IncrementMe()}}").Should().Be(2);
        }
Exemplo n.º 7
0
        public void ParseExceptionMessageShouldBeUnknownIdentifier()
        {
            var eval = new FormulaEvaluator();

            Assert.Throws <ParseException>(() => eval.Evaluate("{{item.id}}"))
            .Message.Should().Be("Unknown identifier 'item'");
        }
Exemplo n.º 8
0
        public void EvalExpressionVariableWithAt()
        {
            var eval = new FormulaEvaluator();

            eval.AddVariable("@a", 1);
            eval.Evaluate("{{@a+@a}}").Should().Be(2);
        }
Exemplo n.º 9
0
        private void SendEvaluation(LocalVariable localVariable = null, GlobalVariable globalVariable = null)
        {
            FormulaEvaluationResult result;

            if (ParsingError != null)
            {
                // FormulaEditorKey key as parameter for this function
                //if (key != FormulaEditorKey.Delete)
                //{
                //    SelectionStart = ParsingError.Index;
                //    SelectionLength = ParsingError.Length;
                //}
                result = new FormulaEvaluationResult
                {
                    Error = AppResourcesHelper.Get("FormulaInterpreter_Error")
                };
            }
            else
            {
                var value       = FormulaEvaluator.Evaluate(Formula);
                var stringValue = value == null ? string.Empty : value.ToString();

                result = new FormulaEvaluationResult
                {
                    Value = stringValue,
                };
            }
            Messenger.Default.Send(result, ViewModelMessagingToken.FormulaEvaluated);
        }
Exemplo n.º 10
0
        public void UsingLambdaExpressionsIssue212()
        {
            var customers = new object[10000];

            for (int i = 0; i < customers.Length; i++)
            {
                customers[i] = new Customer {
                    Id = i, Name = "Customer" + i
                };
            }

            var eval = new FormulaEvaluator();

            eval.AddVariable("items", customers);
            eval.Evaluate("{{items.Count(c => c.Id == 9999)}}").Should().Be(1);
            eval.Evaluate("{{items.Select(i => i.Name).Skip(1000).First()}}").Should().Be("Customer1000");
        }
Exemplo n.º 11
0
        public GlobalTestSetup()
        {
            //Warm-up DynamicExpressionParser
            var evaluator = new FormulaEvaluator();

            evaluator.AddVariable("item", "warm-up");
            evaluator.Evaluate("&={{item.Length}}");
        }
Exemplo n.º 12
0
        public void EvalMixedArray()
        {
            var mixed = new object[] {
                "string",
                1,
                0.1,
                System.DateTime.Today,
            };

            var eval = new FormulaEvaluator();

            eval.AddVariable("mixed", mixed);
            eval.Evaluate("{{mixed.Count()}}").Should().Be(4);
            foreach (var item in mixed)
            {
                eval.Evaluate("{{item}}", new Parameter("item", item));
            }
        }
Exemplo n.º 13
0
        public void ExpressionParseTestNullPropagation()
        {
            var customers = new Customer[]
            {
                new Customer {
                    Id = 1, Name = "Customer1", Manager = new Customer {
                        Id = 3, Name = "Manager1"
                    }
                },
                new Customer {
                    Id = 2, Name = "Customer2", Manager = null
                }
            };
            var eval = new FormulaEvaluator();

            eval.AddVariable("a", customers[0]);
            eval.AddVariable("b", customers[1]);
            eval.Evaluate(@"{{np(a.Manager.Name, ""test"")}}").Should().Be("Manager1");
            eval.Evaluate(@"{{np(b.Manager.Name, ""test"")}}").Should().Be("test");
            eval.Evaluate(@"{{np(b.Manager.Name, null)}}").Should().BeNull();
        }
Exemplo n.º 14
0
        public void WhenInvalidOperandsAreProvided_ShouldThrowFormulaEvaluatorException()
        {
            // arrange
            var formula = "1 +";

            // act
            var tokens = formula.Split(' ');
            var eval   = new FormulaEvaluator(tokens);

            // assert
            Assert.ThrowsException <FormulaEvaluatorException>(() => eval.Evaluate());
        }
Exemplo n.º 15
0
        public void Part1Sample()
        {
            List <string> formulas = GetPart1SampleData();

            Assert.Equal(71, FormulaEvaluator.Evaluate(formulas[0]));
            Assert.Equal(51, FormulaEvaluator.Evaluate(formulas[1]));
            Assert.Equal(26, FormulaEvaluator.Evaluate(formulas[2]));
            Assert.Equal(437, FormulaEvaluator.Evaluate(formulas[3]));
            Assert.Equal(12240, FormulaEvaluator.Evaluate(formulas[4]));
            Assert.Equal(13632, FormulaEvaluator.Evaluate(formulas[5]));
            Assert.Equal(71 + 51 + 26 + 437 + 12240 + 13632, GetPart1SampleData().Select(x => FormulaEvaluator.Evaluate(x)).Sum());
            Assert.Equal(72077, FormulaEvaluator.Evaluate("9 + 2 * ((7 + 9 + 5 + 7) * 3 + (5 * 3 * 6 * 5 + 6) + (9 * 4 + 9 * 6 + 9)) * 8 + 5"));
        }
Exemplo n.º 16
0
        private void Confirm(FormulaEvaluator fe, Cell cell, String formula,
                             double expectedResult)
        {
            fe.ClearAllCachedResultValues();
            cell.CellFormula = formula;
            CellValue cv = fe.Evaluate(cell);

            if (cv.CellType != CellType.NUMERIC)
            {
                throw new AssertFailedException("expected numeric cell type but got " + cv.FormatAsString());
            }
            Assert.AreEqual(expectedResult, cv.NumberValue, 0.0);
        }
Exemplo n.º 17
0
        public void WhenSimpleFormulaForNegativeResult_ShouldEvaluateCorrectly()
        {
            // arrange
            var formula = "1 2 -";

            // act
            var tokens = formula.Split(' ');
            var eval   = new FormulaEvaluator(tokens);
            var result = eval.Evaluate();

            // assert
            Assert.AreEqual(result, -1);
        }
Exemplo n.º 18
0
        public string EvaluateFormula_Base(string formula, BaseClasses.Data.BaseRecord dataSourceForEvaluate, string format, System.Collections.Generic.IDictionary <string, object> variables, bool includeDS)
        {
            FormulaEvaluator e = new FormulaEvaluator();

            // add variables for formula evaluation
            if (variables != null)
            {
                System.Collections.Generic.IEnumerator <System.Collections.Generic.KeyValuePair <string, object> > enumerator = variables.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    e.Variables.Add(enumerator.Current.Key, enumerator.Current.Value);
                }
            }

            if (includeDS)
            {
                // add datasource as variables for formula evaluation

                if (View_Trap_SummaryCountQuery != null && View_Trap_SummaryCountQuery.Initialized)
                {
                    e.Variables.Add("View_Trap_SummaryCountQuery", View_Trap_SummaryCountQuery);
                }
            }


            e.CallingControl = this;

            // All variables referred to in the formula are expected to be
            // properties of the DataSource.  For example, referring to
            // UnitPrice as a variable will refer to DataSource.UnitPrice
            e.DataSource = dataSourceForEvaluate;

            // Define the calling control.
            e.CallingControl = this;

            object resultObj = e.Evaluate(formula);

            if (resultObj == null)
            {
                return("");
            }

            if (!string.IsNullOrEmpty(format) && (string.IsNullOrEmpty(formula) || formula.IndexOf("Format(") < 0))
            {
                return(FormulaUtils.Format(resultObj, format));
            }
            else
            {
                return(resultObj.ToString());
            }
        }
Exemplo n.º 19
0
        public void WhenSimpleFormulaWithCellReference_ShouldEvaluateCorrectlyBySubstitutingWithZero()
        {
            // arrange
            var formula = "1 A1 + ";

            // act
            var tokens = formula.Split(' ');

            var eval   = new FormulaEvaluator(tokens);
            var result = eval.Evaluate();

            // assert
            Assert.AreEqual(result, 1);
        }
Exemplo n.º 20
0
        public void WhenUnaryOperatorsAreSpecified_ShouldEvaluateCorrectly()
        {
            // arrange
            var formula = "15 ++ 7 + --";

            // act
            var tokens = formula.Split(' ');

            var eval   = new FormulaEvaluator(tokens);
            var result = eval.Evaluate();

            // assert
            Assert.AreEqual(result, 22);
        }
Exemplo n.º 21
0
        public void WhenComplexFormula_ShouldEvaluateCorrectly()
        {
            // arrange
            var formula = "15 7 1 1 + - / 3 * 2 1 1 + + -";

            // act
            var tokens = formula.Split(' ');

            var eval   = new FormulaEvaluator(tokens);
            var result = eval.Evaluate();

            // assert
            Assert.AreEqual(result, 5);
        }
Exemplo n.º 22
0
        public void WhenFormulaHasNegativeNumbers_ShouldEvaluateCorrectly()
        {
            // arrange
            var formula = "-1 2 +";

            // act
            var tokens = formula.Split(' ');
            var eval   = new FormulaEvaluator(tokens);
            var result = eval.Evaluate();

            // assert

            Assert.AreEqual(result, 1);
        }
Exemplo n.º 23
0
        private void Confirm(FormulaEvaluator fe, Cell cell, String formula,
                             ErrorEval expectedResult)
        {
            fe.ClearAllCachedResultValues();
            cell.CellFormula = formula;
            CellValue cv = fe.Evaluate(cell);

            if (cv.CellType != CellType.ERROR)
            {
                throw new AssertFailedException("expected error cell type but got " + cv.FormatAsString());
            }
            int expCode = expectedResult.ErrorCode;

            if (cv.ErrorValue != expCode)
            {
                throw new AssertFailedException("Expected error '" + ErrorEval.GetText(expCode)
                                                + "' but got '" + cv.FormatAsString() + "'.");
            }
        }
Exemplo n.º 24
0
        public string EvaluateFormula_Base(string formula, BaseClasses.Data.BaseRecord dataSourceForEvaluate, string format, System.Collections.Generic.IDictionary<string, object> variables, bool includeDS)
        {
            FormulaEvaluator e = new FormulaEvaluator();

            // add variables for formula evaluation
            if (variables != null)
            {
                System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, object>> enumerator = variables.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    e.Variables.Add(enumerator.Current.Key, enumerator.Current.Value);
                }
            }

            if (includeDS)
            {

            }

            e.CallingControl = this;

            // All variables referred to in the formula are expected to be
            // properties of the DataSource.  For example, referring to
            // UnitPrice as a variable will refer to DataSource.UnitPrice
            e.DataSource = dataSourceForEvaluate;

            // Define the calling control.
            e.CallingControl = this;

            object resultObj = e.Evaluate(formula);
            if (resultObj == null)
                return "";

            if ( !string.IsNullOrEmpty(format) && (string.IsNullOrEmpty(formula) || formula.IndexOf("Format(") < 0) )
            {
                return FormulaUtils.Format(resultObj, format);
            }
            else
            {
                return resultObj.ToString();
            }
        }
Exemplo n.º 25
0
 public void Part1()
 {
     Assert.Equal(280014646144, StringListRetriever.Retreive("InputList18.txt").Select(x => FormulaEvaluator.Evaluate(x)).Sum());
 }
Exemplo n.º 26
0
 protected object Eval(string formula)
 {
     return(_evaluator.Evaluate(formula));
 }
        public virtual string EvaluateFormula(string formula)
        {
            FormulaEvaluator e = new FormulaEvaluator();

            e.DataSource = this.DataSource;

            // Define the calling control.  This is used to add other
            // related table and record controls as variables.
            e.CallingControl = this;

            object resultObj = e.Evaluate(formula);
            if (resultObj == null)
                return "";

            return resultObj.ToString();
        }
Exemplo n.º 28
0
 public void ShouldPassStandardFormula(string formula, string expected)
 {
     _calculationEngine.Variables = _values;
     Assert.Equal(Convert.ToDouble(expected), _calculationEngine.Evaluate(formula));
 }
Exemplo n.º 29
0
        public void WrongExpressionShouldThrowParseException()
        {
            var eval = new FormulaEvaluator();

            Assert.Throws <ParseException>(() => eval.Evaluate("{{missing}}"));
        }
 private object Eval(string formula)
 {
     return(evaluator.Evaluate(formula));
 }