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(); }
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()); }
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); } }
/// <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 })); }
public void RuntimeErrorCheck_DivisionByZero() { ExpressionContext context = new ExpressionContext(); IDynamicExpression e1 = context.CompileDynamic("1 = 1/0"); e1.Evaluate(); }
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()); }
public C(int times) { var r = new Random(); var context = new ExpressionContext(); context.Imports.AddType(typeof(Math)); var c = 0; var qs = Enumerable.Range(0, times).ToList().Select(i => { var type = _types.Keys.ToList()[r.Next(_types.Count)]; c++; var v = "a" + c; context.Variables[v] = r.Next(-2000, 10000); return(string.Format("{0} {1}", v, type)); }); Q = string.Join(" ", qs.ToArray()).Trim(); Q = Q.Substring(0, Q.Length - 1); var eDynamic = context.CompileDynamic(Q); Res = (int)eDynamic.Evaluate(); Console.WriteLine(Q + " = " + Res); _types.ToList().ForEach(type => Q = Q.Replace(type.Key, type.Value)); context.Variables.Keys.ToList().ForEach(key => Q = Q.Replace(key, "" + context.Variables[key])); }
public void AddDynamic(string expressionName, string expression) { ExpressionContext linkedContext = this.ParseAndLink(expressionName, expression); IExpression e = linkedContext.CompileDynamic(expression); this.AddCompiledExpression(expressionName, e); }
// 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); }
/// <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); }
public bool Evaluate(Stock stock) { var expressionContext = new ExpressionContext(); expressionContext.Imports.AddType(typeof(Regex), "Regex"); var variables = expressionContext.Variables; variables.Add("Stock", stock); variables.ResolveVariableType += new EventHandler <ResolveVariableTypeEventArgs>((sender, e) => { var propertyInfo = typeof(Stock).GetProperty(e.VariableName); if (propertyInfo != null) { e.VariableType = propertyInfo.PropertyType; } }); variables.ResolveVariableValue += new EventHandler <ResolveVariableValueEventArgs>((sender, e) => { var propertyInfo = typeof(Stock).GetProperty(e.VariableName); if (propertyInfo != null) { e.VariableValue = Convert.ChangeType(propertyInfo.GetValue(stock, null), e.VariableType); } }); var expression = expressionContext.CompileDynamic(this._expression); var retVal = (bool)expression.Evaluate(); return(retVal); }
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()); }
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(); }
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); }
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()); }
public void NullIsNullCheck() { ExpressionContext context = new ExpressionContext(); context.Variables.Add("a", "stringObject"); IDynamicExpression e1 = context.CompileDynamic("null = null"); Assert.IsTrue((bool)e1.Evaluate()); }
public void Add(string atomName, string expression, ExpressionContext context) { Utility.AssertNotNull(atomName, "atomName"); Utility.AssertNotNull(expression, "expression"); Utility.AssertNotNull(context, "context"); this.AddTemporaryHead(atomName); context.SetCalcEngine(this, atomName); context.CompileDynamic(expression); }
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()); }
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(); }
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(); }
private static IDynamicExpression ParseDynamicExpression(string line, string fullLine, Dictionary <string, object> variables) { ExpressionContext context = FleeHelper.GetExpression(variables); try { return(context.CompileDynamic(line)); } catch (Exception e) { throw new ParsingException($"Unable to parse expression from '{line}'", line, e); } }
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); }
public void SeparatorExpressionParse() { var context = new ExpressionContext(); context.Options.ParseCulture = new System.Globalization.CultureInfo("de-DE"); context.ParserOptions.RecreateParser(); var script = @"If(2,57 < 2,7; 3,57; 1000)"; var expr = context.CompileDynamic(script); var result = expr.Evaluate(); Assert.AreEqual(3.57d, result); }
public void DivideByZero() { var context = new ExpressionContext(); context.Options.IntegersAsDoubles = true; var script = @"1 / (1/0)"; var expr = context.CompileDynamic(script); var result = expr.Evaluate(); Assert.AreEqual(0d, result); }
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); }
private Parameter NonSituationalEvaluate(out IDynamicExpression e) { try { e = _context.CompileDynamic(_formula.Functions[0].Expression); var result = e.Evaluate().Infer(); Parameter parameter; parameter = new Parameter(_formula.Name, result.Infer(), null, ref _model); parameter.IsCalculated = true; _parameters.Add(parameter); if (_context.Variables.ContainsKey(parameter.Name)) { _context.Variables.Remove(parameter.Name); } _context.Variables.Add(parameter.Name, parameter.Value.Infer()); return(parameter); } catch (ExpressionCompileException) { // Function can not evaluate further, before a Question/Answer sequence is fullfilled by the client. throw new UnresolvedException($"Function {_formula.Functions[0].Expression} can not evaluate further, before a Question/Answer sequence is fullfilled by the client."); } }
/// <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); }
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(); }
/// <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); }
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); }
public void MissingOperator() { var m1 = new Derived { Value = 2 }; var m2 = new OtherDerived { Value = 5 }; ExpressionContext context = new ExpressionContext(); context.Variables.Add("m1", m1); context.Variables.Add("m2", m2); //// var message = "ArithmeticElement: Operation 'Subtract' is not defined for types 'Derived' and 'OtherDerived'"; context.CompileDynamic("m1 - m2"); }
private static void Test(IQuestion qs) { Console.WriteLine(qs.Question); var q = qs.Question; q = q.Replace("pluss", "+"). Replace("minus", "-"). Replace("ganger", "*"). Replace("delt på", "/"). Replace("Hva er", ""); Console.WriteLine(q); var context = new ExpressionContext(); context.Imports.AddType(typeof (Math)); var eDynamic = context.CompileDynamic(q); var res = eDynamic.Evaluate(); Assert.IsTrue(qs.Run("" + res)); }
public static 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(); }
public static void Main() { ExpressionContext context = new ExpressionContext(); context.Options.EmitToAssembly = true; //context.ParserOptions.RequireDigitsBeforeDecimalPoint = True //context.ParserOptions.DecimalSeparator = ","c //context.ParserOptions.RecreateParser() //context.Options.ResultType = GetType(Decimal) context.Variables["a"] = 2; context.Variables["b"] = 4; IDynamicExpression e1 = context.CompileDynamic("If (19 in (13,28,33,48,71,73,101,102,103,104,23,23,234,34,345,345,45,34,34,4555,445,20),1,0)"); var res1 = e1.Evaluate(); var e = context.CompileGeneric<bool>("b > a"); object result = e.Evaluate(); Console.ReadLine(); }
//public List<double> Evaluate(string expression, DataTable dt) public DataTable Evaluate(string expression, DataTable dt) { List<double> lstCalcValues = new List<double>(); DataTable dtCalcValues = new DataTable(); dtCalcValues.Columns.Add("ID", typeof(string)); dtCalcValues.Columns.Add("CalcValue", typeof(double)); MyTable = dt; ExpressionContext context = new ExpressionContext(); // Use string.format context.Imports.AddType(typeof(string)); // Use on demand variables to provide the values for the columns context.Variables.ResolveVariableType += new EventHandler<ResolveVariableTypeEventArgs>(Variables_ResolveVariableType); context.Variables.ResolveVariableValue += new EventHandler<ResolveVariableValueEventArgs>(Variables_ResolveVariableValue); // Create the expression; Flee will now query for the types of ItemName, Price, and Tax IDynamicExpression e = context.CompileDynamic(expression); Console.WriteLine("Computing value of '{0}' for all rows", e.Text); DataRow dr = null; for (int i = 0; i < dt.Rows.Count; i++) { MyCurrentRow = dt.Rows[i]; // Evaluate the expression; Flee will query for the values of the columns double dlbResult = (double) e.Evaluate(); lstCalcValues.Add(dlbResult); dr = dtCalcValues.NewRow(); dr[0] = MyCurrentRow[0] as string; dr[1] = dlbResult; dtCalcValues.Rows.Add(dr); Console.WriteLine("Row {0} = {1}", i, dlbResult); } return dtCalcValues; }
public void Compile(ExpressionContext context) { if (_expression != string.Empty && _expression != "true" && _expression != "false") eDynamic = context.CompileDynamic(_expression); }
public void TestNoStateHeldInContext() { ExpressionContext context = new ExpressionContext(); IGenericExpression<int> e1 = context.CompileGeneric<int>("300"); // The result type of the cloned context should be set to integer Assert.IsTrue(object.ReferenceEquals(e1.Context.Options.ResultType, typeof(Int32))); // The original context should not be affected Assert.IsNull(context.Options.ResultType); // This should compile IDynamicExpression e2 = context.CompileDynamic("\"abc\""); Assert.IsTrue(object.ReferenceEquals(e2.Context.Options.ResultType, typeof(string))); // The original context should not be affected Assert.IsNull(context.Options.ResultType); }
private Func<double, double> CreateExpressionEvaluator(string expression) { ExpressionContext context = new ExpressionContext(); context.Options.EmitToAssembly = false; context.Imports.AddType(typeof(Math)); context.Variables["x"] = 0.0d; IDynamicExpression fx = null; try { fx = context.CompileDynamic(expression); } catch (ExpressionCompileException) { return null; } Func<Double, Double> expressionEvaluator = (Double i) => { context.Variables["x"] = i; return (Double)fx.Evaluate(); }; return expressionEvaluator; }
public C(int times) { var r = new Random(); var context = new ExpressionContext(); context.Imports.AddType(typeof (Math)); var c = 0; var qs = Enumerable.Range(0, times).ToList().Select(i => { var type = _types.Keys.ToList()[r.Next(_types.Count)]; c++; var v = "a" + c; context.Variables[v] = r.Next(-2000, 10000); return string.Format("{0} {1}", v, type); }); Q = string.Join(" ", qs.ToArray()).Trim(); Q = Q.Substring(0, Q.Length - 1); var eDynamic = context.CompileDynamic(Q); Res = (int) eDynamic.Evaluate(); Console.WriteLine(Q + " = " + Res); _types.ToList().ForEach(type => Q = Q.Replace(type.Key, type.Value)); context.Variables.Keys.ToList().ForEach(key => Q = Q.Replace(key, "" + context.Variables[key])); }
private IDynamicExpression CreateExpression(string expression, ExpressionContext context) { return context.CompileDynamic(expression); }