Exemplo n.º 1
0
        private void Calculate(IDictionary <MeasurementKey, IMeasurement> measurements)
        {
            m_expressionContext.Variables.Clear();

            // Set the values of variables in the expression
            foreach (MeasurementKey key in m_keyMapping.Keys)
            {
                string name = m_keyMapping[key];

                if (measurements.TryGetValue(key, out IMeasurement measurement))
                {
                    m_expressionContext.Variables[name] = measurement.AdjustedValue;
                }
                else
                {
                    m_expressionContext.Variables[name] = m_sentinelValue;
                }
            }

            // Handle special constants
            m_expressionContext.Variables["TIME"] = RealTime.Value;

            // Compile the expression if it has not been compiled already
            if ((object)m_expression == null)
            {
                m_expression = m_expressionContext.CompileDynamic(m_aliasedExpressionText);
            }

            // Evaluate the expression and generate the measurement
            HandleCalculatedValue(m_expression.Evaluate());
        }
Exemplo n.º 2
0
 public object Execute(Context c)
 {
     m_scriptContext.ExecutionContext = c;
     if (m_compiledExpression == null || m_scriptContext.HaveVariableTypesChanged(m_compiledExpression.Info.GetReferencedVariables(), m_types))
     {
         // Lazy compilation since when the game is loaded, we don't know what types of
         // variables we have.
         try
         {
             m_compiledExpression = m_scriptContext.ExpressionContext.CompileDynamic(m_expression);
             m_scriptContext.PopulateVariableTypesCache(m_compiledExpression.Info.GetReferencedVariables(), m_types);
         }
         catch (Exception ex)
         {
             throw new Exception(string.Format("Error compiling expression '{0}': {1}", Utility.ConvertFleeFormatToVariables(m_expression), ex.Message), ex);
         }
     }
     try
     {
         return(m_compiledExpression.Evaluate());
     }
     catch (Exception ex)
     {
         throw new Exception(string.Format("Error evaluating expression '{0}': {1}", Utility.ConvertFleeFormatToVariables(m_expression), ex.Message), ex);
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Gets the risk score for the given risk score type and expression parameters.
        /// </summary>
        ///
        /// <param name="type">The risk score type.</param>
        /// <param name="parameters">The expression parameters.</param>
        /// <returns>The calculated risk score.</returns>
        ///
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="type"/> or <paramref name="parameters"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// If <paramref name="type"/> or <paramref name="parameters"/> is empty.
        /// </exception>
        /// <exception cref="ServiceException">
        /// If any other errors occur while performing this operation.
        /// </exception>
        public double GetRiskScore(string type, IDictionary <string, object> parameters)
        {
            return(Logger.Process(() =>
            {
                CommonHelper.ValidateArgumentNotNullOrEmpty(type, nameof(type));
                CommonHelper.ValidateArgumentNotNullOrEmpty(parameters, nameof(parameters));

                string expression;
                if (!Expressions.TryGetValue(type, out expression))
                {
                    throw new ServiceException(
                        $"The risk score type '{type}' is not configured in Expressions configuration property.");
                }

                var context = new ExpressionContext();
                context.Imports.AddType(typeof(Math));
                foreach (KeyValuePair <string, object> pair in parameters)
                {
                    context.Variables[pair.Key] = pair.Value;
                }

                IDynamicExpression dynamicExpression = context.CompileDynamic(expression);
                return Convert.ToDouble(dynamicExpression.Evaluate());
            },
                                  "retrieving risk score",
                                  parameters: new object[] { type, parameters }));
        }
Exemplo n.º 4
0
        public void TestMethod1()
        {
            ExpressionContext context = new ExpressionContext();

            // Use string.format
            context.Imports.AddType(typeof(string));
            context.Imports.AddType(typeof(ProcessInstance));
            context.Imports.AddType(typeof(Dictionary <string, object>));
            context.Variables.Add("nextCode", "COMPLETE");

            ProcessInstance pi = new ProcessInstance()
            {
                ProcessInstanceName = "Aiska", SuspensionState = ESuspensionState.ACTIVE
            };
            Dictionary <string, int> g = new Dictionary <string, int>();

            g.Add("gaji", 10000000);
            context.Variables.Add("gaji", 10000000);
            context.Variables.Add("processInstance", pi);
            context.Variables.Add("g", g);
            context.Variables.Add("index", 0);

            IDynamicExpression exp = context.CompileDynamic("nextCode.Equals(\"COMPLETE\")");
            var result             = exp.Evaluate();

            exp    = context.CompileDynamic("gaji > 1000000");
            result = exp.Evaluate();

            exp    = context.CompileDynamic("processInstance.ProcessInstanceName.Equals(\"Aiska\") AND processInstance.ProcessInstanceName.Equals(1)");
            result = exp.Evaluate();

            exp    = context.CompileDynamic("g[\"gaji\"] > 1000000");
            result = exp.Evaluate();
        }
Exemplo n.º 5
0
        /// <summary>
        /// Publish <see cref="IFrame"/> of time-aligned collection of <see cref="IMeasurement"/> values that arrived within the
        /// concentrator's defined <see cref="ConcentratorBase.LagTime"/>.
        /// </summary>
        /// <param name="frame"><see cref="IFrame"/> of measurements with the same timestamp that arrived within <see cref="ConcentratorBase.LagTime"/> that are ready for processing.</param>
        /// <param name="index">Index of <see cref="IFrame"/> within a second ranging from zero to <c><see cref="ConcentratorBase.FramesPerSecond"/> - 1</c>.</param>
        protected override void PublishFrame(IFrame frame, int index)
        {
            ConcurrentDictionary <MeasurementKey, IMeasurement> measurements;
            IMeasurement measurement;
            string       name;

            measurements = frame.Measurements;
            m_expressionContext.Variables.Clear();

            // Set the values of variables in the expression
            foreach (MeasurementKey key in m_keyMapping.Keys)
            {
                name = m_keyMapping[key];

                if (measurements.TryGetValue(key, out measurement))
                {
                    m_expressionContext.Variables[name] = measurement.AdjustedValue;
                }
                else
                {
                    m_expressionContext.Variables[name] = double.NaN;
                }
            }

            // Compile the expression if it has not been compiled already
            if ((object)m_expression == null)
            {
                m_expression = m_expressionContext.CompileDynamic(m_aliasedExpressionText);
            }

            // Evaluate the expression and generate the measurement
            GenerateCalculatedMeasurement(m_expression.Evaluate() as IConvertible);
        }
Exemplo n.º 6
0
 internal void UpdateVars(IDynamicExpression exp)
 {
     foreach (var item in Variables)
     {
         exp.Context.Variables[item.Key] = item.Value;
     }
 }
Exemplo n.º 7
0
        public void ExpressionEvaluationTest()
        {
            ExpressionContext context = new ExpressionContext();

            context.Variables.Add("rand", new Random());

            IDynamicExpression e      = context.CompileDynamic("rand.nextDouble() + 100");
            double             result = (double)e.Evaluate();

            //no LINQ
            //var doc = new XDocument(new XElement("test",
            //    new XElement("val", "result1"),
            //    new XElement("val", "result2"),
            //    new XElement("val", "result3")
            //    ));
            //context.Variables.Add("doc", doc);

            //e = context.CompileDynamic("doc.Elements().First().Value");
            //var r = e.Evaluate();

            //no Dynamic
            //dynamic expando = new ExpandoObject();
            //expando.test = "Passed";
            //context.Variables.Add("expando", expando);
            //e = context.CompileDynamic("expando.test");
            //var r = e.Evaluate();
        }
Exemplo n.º 8
0
 public void Compile(ExpressionContext context)
 {
     // TODO: verify wheather the expression is a value (no need to compile)
     bool isValue = false;
     if (!isValue)
         eDynamic = context.CompileDynamic(AssignmentExpression);
 }
Exemplo n.º 9
0
        public void TestFastVariables()
        {
            //Test should take 200ms or less
            const int expectedTime = 200;
            const int iterations   = 100000;

            var context = new ExpressionContext();
            var vars    = context.Variables;

            vars.DefineVariable("a", typeof(int));
            vars.DefineVariable("b", typeof(int));
            IDynamicExpression e = this.CreateDynamicExpression("a + b", context);

            var sw = new Stopwatch();

            sw.Start();

            for (int i = 0; i < iterations - 1; i++)
            {
                vars["a"] = 200;
                vars["b"] = 300;
                var result = e.Evaluate();
            }
            sw.Stop();
            this.PrintSpeedMessage("Fast variables", iterations, sw);
            Assert.IsTrue(sw.ElapsedMilliseconds < expectedTime, $"Test time {sw.ElapsedMilliseconds} above expected value {expectedTime}");
        }
Exemplo n.º 10
0
        static public string[] GetReferencedVariables(string expression, string[] variables)
        {
            if (String.IsNullOrWhiteSpace(expression))
            {
                return(null);
            }

            if ((variables == null) || (variables.Length < 1))
            {
                return(null);
            }

            ExpressionContext context = new ExpressionContext();

            // Use string.format
            context.Imports.AddType(typeof(string));
            context.Imports.AddType(typeof(CustomFunctions));

            for (int i = 0; i < variables.Length; i++)
            {
                context.Variables[variables[i]] = 1.0;
            }

            IDynamicExpression e = context.CompileDynamic(expression);

            return(e.Info.GetReferencedVariables());
        }
Exemplo n.º 11
0
    // Utils
    public float EvaluateSlopeAtPoint(float x, float y)
    {
        this.context = new ExpressionContext();
        if (this.equation.IndexOf("x") > -1)
        {
            this.context.Variables["x"] = x;
        }


        if (this.equation.IndexOf("y") > -1)
        {
            this.context.Variables["y"] = y;
        }



        IDynamicExpression eGeneric = context.CompileDynamic(this.equation);

        float result = (float)eGeneric.Evaluate();

        if (float.IsNaN(result))
        {
            Debug.LogWarning("Found NAN Slope");
            return(0);
        }



        return(result);
    }
Exemplo n.º 12
0
        protected void DoTest(IDynamicExpression e, string result, Type resultType, CultureInfo testCulture)
        {
            var flag = resultType == typeof(object);

            if (flag)
            {
                var expectedType = Type.GetType(result, false, true);
                var flag2        = expectedType == null;
                if (flag2)
                {
                    result       = $"{this.GetType().Namespace}.{result}";
                    expectedType = this.GetType().Assembly.GetType(result, true, true);
                }
                var expressionResult = RuntimeHelpers.GetObjectValue(e.Evaluate());
                var flag3            = expectedType == typeof(void);
                if (flag3)
                {
                    Assert.IsNull(RuntimeHelpers.GetObjectValue(expressionResult));
                }
                else
                {
                    Assert.IsInstanceOf(expectedType, RuntimeHelpers.GetObjectValue(expressionResult));
                }
            }
            else
            {
                var tc             = TypeDescriptor.GetConverter(resultType);
                var expectedResult = RuntimeHelpers.GetObjectValue(tc.ConvertFromString(null, testCulture, result));
                var actualResult   = RuntimeHelpers.GetObjectValue(e.Evaluate());
                expectedResult = RuntimeHelpers.GetObjectValue(this.RoundIfReal(RuntimeHelpers.GetObjectValue(expectedResult)));
                actualResult   = RuntimeHelpers.GetObjectValue(this.RoundIfReal(RuntimeHelpers.GetObjectValue(actualResult)));
                Assert.AreEqual(RuntimeHelpers.GetObjectValue(expectedResult), RuntimeHelpers.GetObjectValue(actualResult));
            }
        }
        public IActionResult OnPost()
        {
            string formula = Request.Form["formula"];

            //Test out the formula when you get it so that you know the formula is valid
            //It will throw an exception if not and you can tell the user the formula is invalid
            try
            {
                ExpressionContext context = new ExpressionContext();
                context.Imports.AddType(typeof(System.Math));
                context.Variables["c"] = 1m;
                context.Variables["b"] = 2m;
                context.Variables["a"] = 3m;
                IDynamicExpression eDynamic = context.CompileDynamic(formula);
                decimal            result   = (decimal)eDynamic.Evaluate();
            }
            catch (Exception ex)
            {
                this.alertMessage = "Please enter a valid formula";
                return(Page());
            }
            Grade.UpdateFormula(formula);
            this.alertMessage = "Formula updated";
            return(Page());
        }
Exemplo n.º 14
0
        public void RuntimeErrorCheck_DivisionByZero()
        {
            ExpressionContext  context = new ExpressionContext();
            IDynamicExpression e1      = context.CompileDynamic("1 = 1/0");

            e1.Evaluate();
        }
Exemplo n.º 15
0
        public void ArgumentInt_to_DoubleConversion()
        {
            ExpressionContext context = new ExpressionContext();

            context.Imports.AddType(typeof(Math));
            IDynamicExpression e1 = context.CompileDynamic("sqrt(16)");

            Assert.AreEqual(4.0, e1.Evaluate());
        }
Exemplo n.º 16
0
        /// <summary>
        /// Transforms a dynamic <see cref="Expression"/> into an object of type <see cref="T"/>.
        /// </summary>
        /// <exception cref="NotSupportedException">The <paramref name="node"/> does not inherit <see cref="Expression"/> or cannot be reduced.</exception>
        protected virtual T VisitDynamic(IDynamicExpression node)
        {
            if (node is Expression expr && expr.CanReduce)
            {
                return(Visit(expr.Reduce()));
            }

            throw new NotSupportedException();
        }
Exemplo n.º 17
0
        public void NullIsNullCheck()
        {
            ExpressionContext context = new ExpressionContext();

            context.Variables.Add("a", "stringObject");
            IDynamicExpression e1 = context.CompileDynamic("null = null");

            Assert.IsTrue((bool)e1.Evaluate());
        }
Exemplo n.º 18
0
        public void getObject()
        {
            SqlConnection conn = konn.GetConn();

            conn.Open();
            string     roboIp;
            SqlCommand cmd = new SqlCommand("SELECT rumus3 from tbl_perumusan where id_kategoripupuk=9", conn);
            // queryStr = "SELECT nama_pupuk from tbl_perumusan where id_kategoripupuk=9";
            // cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
            var queryResult = cmd.ExecuteScalar();//Return an object so first check for null

            if (queryResult != null)
            {
                // If we have result, then convert it from object to string.
                roboIp = Convert.ToString(queryResult);
                //txtOutput.Text = roboIp.ToString();
            }
            else
            {
                // Else make id = "" so you can later check it.
                roboIp = "";
                //txtOutput.Text = "GAGAL";
                //txtOutput.Text = roboIp.Text;
            }

            //testtin Flee
            ExpressionContext context = new ExpressionContext();

            // Allow the expression to use all static public methods of System.Math
            context.Imports.AddType(typeof(Math));

            // Define an int variable
            context.Variables["a"] = 100;

            // Create a dynamic expression that evaluates to an Object
            IDynamicExpression eDynamic = context.CompileDynamic("sqrt(a) + pi");

            // Create a generic expression that evaluates to a double
            context.Variables["a"] = 100;
            context.Variables["b"] = 300;
            context.Variables["c"] = 320;
            IGenericExpression <double> eGeneric = context.CompileGeneric <double>(roboIp);

            // Evaluate the expressions
            double result = (double)eDynamic.Evaluate();

            result = eGeneric.Evaluate();

            // Update the value of our variable
            // Evaluate again to get the updated result
            result = eGeneric.Evaluate();
            double hasilakhir = (double)result + 5;


            txtOutput.Text = hasilakhir.ToString();
        }
Exemplo n.º 19
0
        public void RuntimeErrorCheck_ParsingInvalidDate()
        {
            ExpressionContext context = new ExpressionContext();

            context.Variables.Add("a", "stringObject");
            context.Imports.AddType(typeof(DateTime));
            IDynamicExpression e1 = context.CompileDynamic("Parse(a)");

            e1.Evaluate();
        }
Exemplo n.º 20
0
        public void CompareLongs()
        {
            // bug #83 test.
            ExpressionContext  context = new ExpressionContext();
            IDynamicExpression e1      = context.CompileDynamic("2432696330L = 2432696330L AND 2432696330L > 0 AND 2432696330L < 2432696331L");

            Assert.IsTrue((bool)e1.Evaluate());
            e1 = context.CompileDynamic("2432696330L / 2");

            Assert.AreEqual(1216348165L, e1.Evaluate());
        }
Exemplo n.º 21
0
        public void Compile(Type modelType)
        {
            this.context = new ExpressionContext();
            this.context.Variables.DefineVariable(this.ModelVariableName, modelType);
            foreach (var variable in this.variables)
            {
                this.context.Variables.DefineVariable(variable.Key, variable.Value == null ? typeof(object) : variable.Value.GetType());
            }

            this.compiled = this.context.CompileDynamic(this.Expression);
        }
Exemplo n.º 22
0
        public void Test_IfExpression_enUS()
        {
            ExpressionContext context = new ExpressionContext();

            context.Options.ParseCulture = new System.Globalization.CultureInfo("en-US");

            int resultWhenTrue = 3;

            IDynamicExpression e = context.CompileDynamic("if(1<2, 3, 4)");

            Assert.IsTrue((int)e.Evaluate() == resultWhenTrue);
        }
Exemplo n.º 23
0
 protected double CalculateByPoint(string func)
 {
     try
     {
         dynamic = context.CompileDynamic(func);
         return(Convert.ToDouble(dynamic.Evaluate()));
     }
     catch
     {
         return(0);
     }
 }
Exemplo n.º 24
0
        public override void Compile(bool recursive = false)
        {
            //Debug.Assert(InputFeatureType != null);

            if (_text.LabelBox != null)
            {
                var renderer = _text.LabelBox.Renderer as IFeatureRenderer;
                if (renderer != null)
                {
                    renderer.InputFeatureType = InputFeatureType;
                    if (recursive)
                        renderer.Compile(true);
                }
            }

            var context = Renderer.Context;
            //var colorContext = context;
            //var contentAlignmentContext = context;

            //_resolver = new FeatureVariableResolver(InputFeatureType);
            //_resolver.BindContext(context);
            //_resolver.BindContext(colorContext);
            //_resolver.BindContext(contentAlignmentContext);

            var oldFeatureType = Renderer.FeatureVarResolver.FeatureType;
            Renderer.FeatureVarResolver.FeatureType = InputFeatureType;
            try
            {
                _contentEvaluator = CompileExpression(context, TextStyle.ContentField, _text.Content, ref _content);
                _angleEvaluator = CompileDoubleExpression(context, TextStyle.AngleField, _text.Angle, ref _angle);
                _sizeEvaluator = CompileDoubleExpression(context, TextStyle.SizeField, _text.Size, ref _size);
                _alignEvaluator = CompileEnumExpression(context, TextStyle.AlignmentField, _text.Alignment, ref _alignment);
                _fontEvaluator = CompileExpression<string>(context, TextStyle.FontField, _text.Font);
                _colorEvaluator = CompileColorExpression(context, TextStyle.ColorField, _text.Color, ref _color);
                _scaleXEvaluator = CompileDoubleExpression(context, TextStyle.ScaleXField, _text.ScaleX, ref _scaleX);
                _scaleYvaluator = CompileDoubleExpression(context, TextStyle.ScaleYField, _text.ScaleY, ref _scaleY);
                _opacityEvaluator = CompileFloatExpression(context, TextStyle.OpacityField, _text.Opacity, ref _opacity);
                _overlapableEvaluator = CompileBoolExpression(context, TextStyle.OverlapableField, _text.Overlappable, ref _overlapable);
                _allowOverlapEvaluator = CompileBoolExpression(context, TextStyle.AllowOverlapField, _text.AllowOverlap, ref _allowOverlap);
            }
            finally
            {
                Renderer.FeatureVarResolver.FeatureType = oldFeatureType;
            }

            //_labelBoxRenderer = _text.LabelBox != null && _text.LabelBox.Renderer != null && !string.IsNullOrWhiteSpace(_text.Content)
            //    ? _text.LabelBox.Renderer as IFeatureRenderer
            //    : null;
            _labelBoxRenderer = _text.LabelBox != null ? new ContainerNodeRenderer(Renderer, _text.LabelBox, this) : null;

            _compiled = true;
        }
Exemplo n.º 25
0
        public void ProfileCompilationTime()
        {
            int expectedTime = 1000;
            int iterations   = 10;

            var context = new ExpressionContext();

            context.Variables.ResolveVariableType  += Variables_ResolveVariableType;
            context.Variables.ResolveVariableValue += Variables_ResolveVariableValue;
            Stopwatch sw;


            sw = new Stopwatch();
            sw.Start();

            for (int i = 0; i < iterations - 1; i++)
            {
                IDynamicExpression e = this.CreateDynamicExpression(BigExpression, context);
            }
            sw.Stop();
            this.PrintSpeedMessage("Compile Big", iterations, sw);
            Assert.Less(sw.ElapsedMilliseconds, expectedTime, "Test time above expected value");


            iterations   = 100;
            expectedTime = 100;

            sw = new Stopwatch();
            sw.Start();

            for (int i = 0; i < iterations - 1; i++)
            {
                IDynamicExpression e = this.CreateDynamicExpression(SmallExpression, context);
            }
            sw.Stop();
            this.PrintSpeedMessage("Compile Small", iterations, sw);
            Assert.Less(sw.ElapsedMilliseconds, expectedTime, "Test time above expected value");

            iterations   = 100;
            expectedTime = 100;

            sw = new Stopwatch();
            sw.Start();

            for (int i = 0; i < iterations - 1; i++)
            {
                IDynamicExpression e = this.CreateDynamicExpression(SmallExpression, context);
            }
            sw.Stop();
            this.PrintSpeedMessage("Compile Small Branching", iterations, sw);
            Assert.Less(sw.ElapsedMilliseconds, expectedTime, "Test time above expected value");
        }
Exemplo n.º 26
0
 protected double CalculateByPoint(double x)
 {
     try
     {
         string tmpStr = CurrentFunction.Replace("x", x.ToString());
         dynamic = context.CompileDynamic(tmpStr);
         return(Convert.ToDouble(dynamic.Evaluate()));
     }
     catch
     {
         return(0);
     }
 }
Exemplo n.º 27
0
        public void Test_IfExpression_fiFI()
        {
            ExpressionContext context = new ExpressionContext();

            context.Imports.AddType(typeof(Math));
            context.Options.ParseCulture = new System.Globalization.CultureInfo("fi-FI");

            int resultWhenFalse = 4;

            IDynamicExpression e = context.CompileDynamic("if(1>2; 3; 4)");

            Assert.IsTrue((int)e.Evaluate() == resultWhenFalse);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Initialize dynamic expression
        /// </summary>
        /// <param name="expression"></param>
        public void InitDynamicExpression(string expression)
        {
            if (m_contextExpression == null)
            {
                m_contextExpression = new ExpressionContext();
                m_contextExpression.Imports.AddType(typeof(Math));
                m_contextExpression.Variables["X"] = 0F;
                m_contextExpression.Variables["Y"] = 0F;
                m_contextExpression.Variables["Z"] = 0F;
            }

            // Create a dynamic expression that evaluates to an Object
            m_eDynamicExpression = m_contextExpression.CompileDynamic(expression);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Publish <see cref="IFrame"/> of time-aligned collection of <see cref="IMeasurement"/> values that arrived within the
        /// concentrator's defined <see cref="ConcentratorBase.LagTime"/>.
        /// </summary>
        /// <param name="frame"><see cref="IFrame"/> of measurements with the same timestamp that arrived within <see cref="ConcentratorBase.LagTime"/> that are ready for processing.</param>
        /// <param name="index">Index of <see cref="IFrame"/> within a second ranging from zero to <c><see cref="ConcentratorBase.FramesPerSecond"/> - 1</c>.</param>
        protected override void PublishFrame(IFrame frame, int index)
        {
            ConcurrentDictionary <MeasurementKey, IMeasurement> measurements;
            IMeasurement measurement;
            string       name;
            long         timestamp;

            measurements = frame.Measurements;
            m_expressionContext.Variables.Clear();

            // Set the values of variables in the expression
            foreach (MeasurementKey key in m_keyMapping.Keys)
            {
                name = m_keyMapping[key];

                if (measurements.TryGetValue(key, out measurement))
                {
                    m_expressionContext.Variables[name] = measurement.AdjustedValue;
                }
                else
                {
                    m_expressionContext.Variables[name] = double.NaN;
                }
            }

            // Compile the expression if it has not been compiled already
            if ((object)m_expression == null)
            {
                m_expression = m_expressionContext.CompileDynamic(m_aliasedExpressionText);
            }

            // Get the timestamp of the measurement to be generated
            switch (m_timestampSource)
            {
            default:
                timestamp = frame.Timestamp;
                break;

            case TimestampSource.RealTime:
                timestamp = RealTime;
                break;

            case TimestampSource.LocalClock:
                timestamp = DateTime.UtcNow.Ticks;
                break;
            }

            // Evaluate the expression and generate the measurement
            GenerateCalculatedMeasurement(timestamp, m_expression.Evaluate() as IConvertible);
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            ExpressionContext context = new ExpressionContext();

            context.Imports.AddType(typeof(CustomFunctions));

            IDynamicExpression e = context.CompileDynamic("sum(1,2,3,4,5,6)");
            int result           = (int)e.Evaluate();

            Console.WriteLine("result: " + result);

            Console.WriteLine("Done");
            Console.ReadKey();
        }
Exemplo n.º 31
0
        public void DerivedUnaryOperatorPlusOperator()
        {
            var m1 = new Derived {
                Value = 2
            };

            ExpressionContext context = new ExpressionContext();

            context.Variables.Add("m1", m1);
            IDynamicExpression e1 = context.CompileDynamic("-m1 + m1");

            Base negated = (Base)e1.Evaluate();

            Assert.AreEqual(0, negated.Value);
        }
Exemplo n.º 32
0
        internal void FixTemporaryHead(IDynamicExpression expression, ExpressionContext context, Type resultType)
        {
            var pairType = typeof(GenericExpressionResultPair <>);

            pairType = pairType.MakeGenericType(resultType);
            var pair     = (ExpressionResultPair)Activator.CreateInstance(pairType);
            var headName = context.CalcEngineExpressionName;

            pair.SetName(headName);
            pair.SetExpression(expression);
            var oldPair = this.myNameNodeMap[headName];

            this.myDependencies.ReplaceDependency(oldPair, pair);
            this.myNameNodeMap[headName] = pair;
            pair.Recalculate();
        }
Exemplo n.º 33
0
        public void Compile(bool recursive = false)
        {
            //var context = FeatureRenderer.CreateContext();
            //if (InputFeatureType != null)
            //{
            //    _resolver = new FeatureVariableResolver(InputFeatureType);
            //    _resolver.BindContext(context);
            //}
            var _context = _renderer.Context;
            _exprEval = FeatureRenderer.CompileExpression(_caseNode, _context, Case.ExpressionField, _caseNode.Expression, ref _caseValue);
            _expressions = new List<IExpression>(_caseNode.Nodes.Count);
            _whenValues = new ArrayList(_caseNode.Nodes.Count);

            _renderers = new List<IBaseRenderer>(_caseNode.Nodes.Count);
            foreach (ContainerNode child in _caseNode.Nodes)
            {
                var renderer = child.Renderer ?? (child.Renderer = _renderer.CreateRenderer(child, null, this));
                if (renderer == null) continue;

                var when = child as When;
                if (when != null)
                {
                    object whenValue = null;
                    var expr = when.Expression != null ?
                        _exprEval != null || _caseValue != null
                            ? (IExpression)FeatureRenderer.CompileExpression(_caseNode, _context, When.ExpressionField, when.Expression, ref whenValue)
                            : FeatureRenderer.CompileExpression<bool>(_renderer, _caseNode, _context, When.ExpressionField, when.Expression)
                        : null;

                    _expressions.Add(expr);
                    _whenValues.Add(whenValue);
                }
                else if (!(child is Else))
                    continue;
                
                _renderers.Add(renderer);

                if (recursive)
                    renderer.Compile(true);
            }
            
            _compiled = true;
        }
Exemplo n.º 34
0
        /// <summary>
        /// Publish <see cref="IFrame"/> of time-aligned collection of <see cref="IMeasurement"/> values that arrived within the
        /// concentrator's defined <see cref="ConcentratorBase.LagTime"/>.
        /// </summary>
        /// <param name="frame"><see cref="IFrame"/> of measurements with the same timestamp that arrived within <see cref="ConcentratorBase.LagTime"/> that are ready for processing.</param>
        /// <param name="index">Index of <see cref="IFrame"/> within a second ranging from zero to <c><see cref="ConcentratorBase.FramesPerSecond"/> - 1</c>.</param>
        protected override void PublishFrame(IFrame frame, int index)
        {
            ConcurrentDictionary<MeasurementKey, IMeasurement> measurements;
            IMeasurement measurement;
            string name;
            long timestamp;

            measurements = frame.Measurements;
            m_expressionContext.Variables.Clear();

            // Set the values of variables in the expression
            foreach (MeasurementKey key in m_keyMapping.Keys)
            {
                name = m_keyMapping[key];

                if (measurements.TryGetValue(key, out measurement))
                    m_expressionContext.Variables[name] = measurement.AdjustedValue;
                else
                    m_expressionContext.Variables[name] = double.NaN;
            }

            // Compile the expression if it has not been compiled already
            if ((object)m_expression == null)
                m_expression = m_expressionContext.CompileDynamic(m_aliasedExpressionText);

            // Get the timestamp of the measurement to be generated
            switch (m_timestampSource)
            {
                default:
                    timestamp = frame.Timestamp;
                    break;

                case TimestampSource.RealTime:
                    timestamp = RealTime;
                    break;

                case TimestampSource.LocalClock:
                    timestamp = DateTime.UtcNow.Ticks;
                    break;
            }

            // Evaluate the expression and generate the measurement
            GenerateCalculatedMeasurement(timestamp, m_expression.Evaluate() as IConvertible);
        }
Exemplo n.º 35
0
        /// <summary>
        /// Publish <see cref="IFrame"/> of time-aligned collection of <see cref="IMeasurement"/> values that arrived within the
        /// concentrator's defined <see cref="ConcentratorBase.LagTime"/>.
        /// </summary>
        /// <param name="frame"><see cref="IFrame"/> of measurements with the same timestamp that arrived within <see cref="ConcentratorBase.LagTime"/> that are ready for processing.</param>
        /// <param name="index">Index of <see cref="IFrame"/> within a second ranging from zero to <c><see cref="ConcentratorBase.FramesPerSecond"/> - 1</c>.</param>
        protected override void PublishFrame(IFrame frame, int index)
        {
            ConcurrentDictionary<MeasurementKey, IMeasurement> measurements;
            IMeasurement measurement;
            string name;

            measurements = frame.Measurements;
            m_expressionContext.Variables.Clear();

            // Set the values of variables in the expression
            foreach (MeasurementKey key in m_keyMapping.Keys)
            {
                name = m_keyMapping[key];

                if (measurements.TryGetValue(key, out measurement))
                    m_expressionContext.Variables[name] = measurement.AdjustedValue;
                else
                    m_expressionContext.Variables[name] = double.NaN;
            }

            // Compile the expression if it has not been compiled already
            if ((object)m_expression == null)
                m_expression = m_expressionContext.CompileDynamic(m_aliasedExpressionText);

            // Evaluate the expression and generate the measurement
            GenerateCalculatedMeasurement(m_expression.Evaluate() as IConvertible);
        }
Exemplo n.º 36
0
 public void Compile(ExpressionContext context)
 {
     if (_expression != string.Empty && _expression != "true" && _expression != "false")
         eDynamic = context.CompileDynamic(_expression);
 }