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 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()); }
public void RuntimeErrorCheck_DivisionByZero() { ExpressionContext context = new ExpressionContext(); IDynamicExpression e1 = context.CompileDynamic("1 = 1/0"); e1.Evaluate(); }
/// <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); }
/// <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 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(); }
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 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); } }
// 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); }
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}"); }
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 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 NullIsNullCheck() { ExpressionContext context = new ExpressionContext(); context.Variables.Add("a", "stringObject"); IDynamicExpression e1 = context.CompileDynamic("null = null"); Assert.IsTrue((bool)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(); }
protected double CalculateByPoint(string func) { try { dynamic = context.CompileDynamic(func); return(Convert.ToDouble(dynamic.Evaluate())); } catch { return(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); }
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); }
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> /// 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(); }
protected void DoTest(IDynamicExpression e, string result, Type resultType, CultureInfo testCulture) { if (resultType == typeof(object)) { var expectedType = Type.GetType(result, false, true); if (expectedType == null) { // Try to get the type from the Tests assembly result = $"{this.GetType().Namespace}.{result}"; expectedType = this.GetType().Assembly.GetType(result, true, true); } var expressionResult = e.Evaluate(); if (expectedType == typeof(void)) { Assert.IsNull(expressionResult, $"{e.Text} should be null, but is {expressionResult}"); } else { Assert.IsInstanceOfType(expressionResult, expectedType, $"{e.Text} should be of type {expectedType}, but is {expressionResult.GetType()}"); } } else { var tc = TypeDescriptor.GetConverter(resultType); var expectedResult = tc.ConvertFromString(null, testCulture, result); var actualResult = e.Evaluate(); expectedResult = RoundIfReal(expectedResult); actualResult = RoundIfReal(actualResult); Assert.AreEqual(expectedResult, actualResult, $"{e.Text} should be {expectedResult} but is {actualResult}"); } }
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); }
internal static decimal GetAverageForStudentByYear(Student student, int year) { //Get all Grades for the Student, by program if no semester passed in, or by semester if it is IEnumerable <Grade> grades = student.GetGradesForYear(year); List <decimal> results = new List <decimal>(); decimal average = 0; using (var connection = DbConn.GetConnection()) { connection.Open(); SqlCommand selectCommand = new SqlCommand("mcftacademics.dbo.SelectFormula", connection); selectCommand.CommandType = System.Data.CommandType.StoredProcedure; SqlDataReader reader = selectCommand.ExecuteReader(); if (reader.Read()) { // Define the context of our expression ExpressionContext context = new ExpressionContext(); // Allow the expression to use all static public methods of System.Math context.Imports.AddType(typeof(Math)); //Get the total Course credit hours for use in the expression context.Variables["c"] = grades.Sum(gg => gg.Subject.Credit); foreach (Grade g in grades) { // Define an int variable if (g.Supplemental) { context.Variables["a"] = 60m; } else { context.Variables["a"] = g.GradeAssigned; } context.Variables["b"] = g.Subject.Credit; // Create a dynamic expression that evaluates to an Object IDynamicExpression eDynamic = context.CompileDynamic(reader["Formula"].ToString()); // Evaluate the expressions decimal result = (decimal)eDynamic.Evaluate(); results.Add(result); } average = results.Sum(); } } return(Math.Round(average, 2)); }
public static Func <double, double, double> CreateExpressionForTX(string expression) { ExpressionContext context = new ExpressionContext(); context.Variables["x"] = 0.0d; context.Variables["t"] = 0.0d; IDynamicExpression e = context.CompileDynamic(expression); Func <double, double, double> expressionEvaluator = (double input, double input2) => { context.Variables["x"] = input; context.Variables["t"] = input2; var result = (double)e.Evaluate(); return(result); }; return(expressionEvaluator); }
private void tryCalcul() { if (bracketCount == 0) { try { ExpressionContext context = new ExpressionContext(); IDynamicExpression ide = context.CompileDynamic(calculTop); var res = ide.Evaluate(); tb_mainDisplay.Text = res.ToString(); // 진법 변환 추가 } catch (Exception) { return; } } }
private void btn_equals_Click(object sender, EventArgs e) { try { ExpressionContext context = new ExpressionContext(); IDynamicExpression ide = context.CompileDynamic(calculTop); var res = ide.Evaluate(); tb_mainDisplay.Text = res.ToString(); } catch (ExpressionCompileException ex) { // Handle expression compile error if (ex.Reason == CompileExceptionReason.SyntaxError) { MessageBox.Show("Check your expression syntax"); } } }
void Formula_Table_Lookup_Test() { // -naam: woonlandfactoren // woonland, factor: // - [Finland, 0.7161] var controller = new YamlScriptController(); var result = controller.Parse(YamlTestFileLoader.Load(@"Rijksoverheid/Zorgtoeslag.yaml")); ExpressionContext context = new ExpressionContext(controller); // Tsjechië, 0.2412 context.Variables.Add("woonland", "Tsjechië"); var formula = controller.GetFormula("woonlandfactor"); // select(string tableName, string lookupValue, string lookupColumn, string resultColumn) IDynamicExpression e = context.CompileDynamic(formula.Functions[0].Expression); double result1 = (double)e.Evaluate(); Assert.True(result1 == 0.2412); }
//public List<double> Evaluate(string expression, DataTable dt) public DataTable Evaluate(string expression, DataTable dt) { List <double> calcValues = 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)); context.Imports.AddType(typeof(CustomFunctions)); // 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 result = (double)e.Evaluate(); calcValues.Add(result); dr = dtCalcValues.NewRow(); dr[0] = MyCurrentRow[0] as string; dr[1] = result; dtCalcValues.Rows.Add(dr); Console.WriteLine("Row {0} = {1}", i, result); } //return calcValues; return(dtCalcValues); }