static void Main(string[] args) { //Sample Scenario 1 ExpressionContext context = new ExpressionContext(); context.ParserOptions.DecimalSeparator = '.'; context.ParserOptions.FunctionArgumentSeparator = ','; VariableCollection variables = context.Variables; variables.Add("a", 1); variables.Add("b", 1); IGenericExpression <bool> e = context.CompileGeneric <bool>("a=1 AND b=0"); bool result = e.Evaluate(); //Sample Scenario 2 ExpressionContext context2 = new ExpressionContext(); VariableCollection variables2 = context2.Variables; variables2.Add("a", 100); variables2.Add("b", 1); variables2.Add("c", 24); IGenericExpression <bool> ge = context2.CompileGeneric <bool>("(a = 100 OR b > 0) AND c <> 2"); bool result2 = ge.Evaluate(); IGenericExpression <decimal> ge1 = context2.CompileGeneric <decimal>("1/2"); decimal result3 = ge1.Evaluate(); System.Console.ReadKey(); }
public void Formula_Simple_Calculations() { // 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)); context.Variables.ResolveVariableType += Formula_Simple_Calculation_Variables_ResolveVariableType; // this will visit Variables_ResolveVariableType context.Variables.ResolveVariableValue += Formula_Simple_Calculation_Variables_ResolveVariableValue; IGenericExpression <Double> eDynamic = context.CompileGeneric <Double>("sqrt(a) + b"); // This will visit Variables_ResolveVariableValue var result = eDynamic.Evaluate(); Assert.True(result == 9.64575131106459); IGenericExpression <Double> eDynamic1 = context.CompileGeneric <Double>("a + b"); var result1 = eDynamic1.Evaluate(); Assert.True(result1 == 14); IGenericExpression <bool> eDynamic2 = context.CompileGeneric <bool>("a + 1 > b"); var result2 = eDynamic2.Evaluate(); Assert.True(result2); IGenericExpression <bool> eDynamic3 = context.CompileGeneric <bool>("a > b"); var result3 = eDynamic3.Evaluate(); Assert.False(result3); }
/// <summary> /// Perform integration /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Integrate1D_Click(object sender, EventArgs e) { double a = 0, b = 0; int n = 2; if (double.TryParse(textBox1.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out a) != true) { MessageBox.Show("First point \"a\" of interval is invalid!"); label5.Text = ""; return; } if (double.TryParse(textBox2.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out b) != true) { MessageBox.Show("Second point \"b\" of interval is invalid!"); label5.Text = ""; return; } if (int.TryParse(comboBox4.Text, NumberStyles.None, CultureInfo.InvariantCulture, out n) != true) { MessageBox.Show("Number of points is invalid!"); label5.Text = ""; return; } if (n > 64) { MessageBox.Show("Number of points must be less than 65!"); label5.Text = ""; return; } try { var funstr = textFunction.Text; function = context.CompileGeneric <double>(funstr); } catch (Exception ex) { MessageBox.Show("Error in fun definition. ERROR: " + ex.Message); label5.Text = "I=n/a"; return; } double[][] pi = new double[2][]; pi[0] = new double[2]; pi[1] = new double[2]; pi[0][0] = a; pi[1][0] = b; //perform integration double retVal = GaussIntegrator.Calculate1DIntegral(function, register, n, pi); label5.Text = string.Format("I={0:0.0000000000}", retVal); }
public void IN_OperatorTest() { ExpressionContext context = new ExpressionContext(); var e1 = context.CompileGeneric <bool>("NOT 15 IN (1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19,20,21,22,23)"); Assert.IsTrue(e1.Evaluate()); e1 = context.CompileGeneric <bool>("\"a\" IN (\"a\",\"b\",\"c\",\"d\") and true and 5 in (2,4,5)"); Assert.IsTrue(e1.Evaluate()); e1 = context.CompileGeneric <bool>("\"a\" IN (\"a\",\"b\",\"c\",\"d\") and true and 5 in (2,4,6,7,8,9)"); Assert.IsFalse(e1.Evaluate()); }
public static bool ValidadeEquation(string text) { if (!text.Any()) { return(true); } //alterei para text.any() também ExpressionContext context = new ExpressionContext(); VariableCollection variables = context.Variables; foreach (IInvariant invariant in InvariantNum.List()) { if (text.Contains(invariant.getCode() + "_G")) { context.Variables[invariant.getCode() + "_G"] = invariant.Calculate(new Graph(new int[0, 0])); } if (text.Contains(invariant.getCode() + "_lG")) { context.Variables[invariant.getCode() + "_lG"] = invariant.Calculate(new Graph(new int[0, 0])); } if (text.Contains(invariant.getCode() + "_cG")) { context.Variables[invariant.getCode() + "_cG"] = invariant.Calculate(new Graph(new int[0, 0])); } } IGenericExpression <bool> e = context.CompileGeneric <bool>(text); return(e.Evaluate()); }
public void AddGeneric <T>(string expressionName, string expression) { ExpressionContext linkedContext = this.ParseAndLink(expressionName, expression); IExpression e = linkedContext.CompileGeneric <T>(expression); this.AddCompiledExpression(expressionName, e); }
public static (string expression, bool isValid) IsValid(this string json, string condition) { JObject obj; try { obj = JObject.Parse(json); } catch (Exception error) { Console.WriteLine("========================= Json With Error ========================="); Console.WriteLine(json); Console.WriteLine("========================= Json With Error ========================="); return(error.Message, false); } var expression = ReplaceParameters(obj, condition); ExpressionContext context = new ExpressionContext(); IGenericExpression <bool> e = context.CompileGeneric <bool>(expression); return(expression, e.Evaluate()); }
public Widgets ReadWidgets(List <Filter> filters) { Widgets widgets = _repository; string linqExpression = filters.ToLinqExpression <Widget>("o"); if (linqExpression != String.Empty) { ExpressionContext context = new ExpressionContext(); context.Variables.DefineVariable("o", typeof(Widget)); for (int i = 0; i < widgets.Count; i++) { context.Variables["o"] = widgets[i]; var expression = context.CompileGeneric <bool>(linqExpression); try { if (!expression.Evaluate()) { widgets.RemoveAt(i--); } } catch { } //If Expression fails to eval for item ignore item. } } return(widgets); }
static void Main(string[] args) { //Sample Scenario 1 ExpressionContext context = new ExpressionContext(); VariableCollection variables = context.Variables; variables.Add("a", 1); variables.Add("b", 1); IGenericExpression <bool> e = context.CompileGeneric <bool>("a=1 AND b=0"); bool result = e.Evaluate(); //Sample Scenario 2 ExpressionContext context2 = new ExpressionContext(); VariableCollection variables2 = context2.Variables; variables2.Add("a", 100); variables2.Add("b", 1); variables2.Add("c", 24); IGenericExpression <bool> ge = context2.CompileGeneric <bool>("(a = 100 OR b > 0) AND c <> 2"); bool result2 = ge.Evaluate(); System.Console.ReadKey(); }
/// <summary> /// Gets the FLEE context. /// </summary> /// <param name="owner">The owner.</param> /// <param name="filter">The filter.</param> /// <returns></returns> private static IGenericExpression <bool> GetFLEEContext(object owner, string filter) { ExpressionContext context = new ExpressionContext(owner); context.Variables.Add("Now", DateTime.Now); return(context.CompileGeneric <bool>(filter)); }
public static bool EvaluateText(string text, Graph g) { if (!text.Any()) { return(true); } //Alterei de text.count() == 0 para text.any() ExpressionContext context = new ExpressionContext(); VariableCollection variables = context.Variables; foreach (IInvariant invariant in InvariantNum.List()) { if (text.Contains(invariant.getCode() + "_G")) { context.Variables[invariant.getCode() + "_G"] = invariant.Calculate(g); } if (text.Contains(invariant.getCode() + "_lG")) { context.Variables[invariant.getCode() + "_lG"] = invariant.Calculate(Operation.Line(g)); } if (text.Contains(invariant.getCode() + "_cG")) { context.Variables[invariant.getCode() + "_cG"] = invariant.Calculate(Operation.Complement(g)); } } IGenericExpression <bool> e = context.CompileGeneric <bool>(text); return(e.Evaluate()); //throw new ExpressionCompileException(); }
private bool EvaluateExpression(string expression, ExpressionContext context) { IGenericExpression <bool> eGeneric = context.CompileGeneric <bool>(expression); var result = eGeneric.Evaluate(); return(result); }
//************************************************************************* //* Private * //************************************************************************* //************************************************************************* //* Protected * //************************************************************************* //************************************************************************* //* Public * //************************************************************************* //*-----------------------------------------------------------------------* //* GetCollection * //*-----------------------------------------------------------------------* /// <summary> /// Return the first collection matching the specified expression. /// </summary> /// <param name="expression"> /// Basic expression to parse. Any attribute names are square bracketed. /// For example, to find a collection where the datatype attribute value /// is equal to 'object', use [datatype] = object /// </param> /// <returns> /// Reference to the first matching collection, if found. Otherwise, null. /// </returns> public AttributeCollection GetCollection(string expression) { string content = ""; ExpressionContext context = null; IGenericExpression <bool> evaluator = null; string expressionText = ""; StringCollection fieldNames = new StringCollection(); string keyword = ""; MatchCollection matches = null; //double nValue = 0d; AttributeCollection result = null; VariableCollection variables = null; if (expression?.Length > 0) { expressionText = expression; context = new ExpressionContext(); variables = context.Variables; matches = Regex.Matches(expression, ResourceMain.AttributeKeywordPattern); foreach (Match match in matches) { keyword = Tools.GetValue(match, "keyword"); content = Tools.GetValue(match, "content"); if (content.Length > 0) { // This value is either a field name or a match value. if (keyword.Length > 0) { // Field name found. fieldNames.AddUnique(content); expressionText = expressionText.Replace(keyword, "F" + content); variables.Add("F" + content, content); } else { // Normal value. variables.Add(content, content); } } } foreach (AttributeCollection collection in this) { // Prepare the local variables. foreach (string field in fieldNames) { variables["F" + field] = collection.GetValue(field); } evaluator = context.CompileGeneric <bool>(expressionText); if (evaluator.Evaluate()) { result = collection; break; } } } return(result); }
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 ConditionalFlowCanReadAndEvaluateTFormalExpression() { var doc = XDocument.Parse(TestFileLoader.Load(@"Bpmn20/simple-exclusive-gateway.bpmn")); string json = JsonConvert.SerializeXNode(doc); JObject bpmn = JObject.Parse(json); var process = bpmn["bpmn:definitions"]["bpmn:process"]; var flow = process["bpmn:sequenceFlow"].Where(p => p["@id"].Value <string>() == "Flow_0gzbcgc").Single()["bpmn:conditionExpression"]["#text"]; ExpressionContext context = new ExpressionContext(); context.Variables["A"] = 1; IGenericExpression <bool> eDynamic = context.CompileGeneric <bool>((string)flow); var result = eDynamic.Evaluate(); Assert.True(result); flow = process["bpmn:sequenceFlow"].Where(p => p["@id"].Value <string>() == "Flow_1fg2zon").Single()["bpmn:conditionExpression"]["#text"]; eDynamic = context.CompileGeneric <bool>((string)flow); result = eDynamic.Evaluate(); Assert.False(result); }
public MoveData(string[] args, Dictionary <string, object> variables, string line) : base(variables, line, args) { ExpressionContext expression = FleeHelper.GetExpression(variables); string exceptionMessage = ""; if (args.Length > 2) { throw new ParsingException("Extra agruments supplied, maximum of 2 allowed for this function.", line); } try { exceptionMessage = "Invalid expression for X coordinate!"; x = expression.CompileGeneric <double>(args[0]); exceptionMessage = "Invalid expression for Y coordinate!"; y = expression.CompileGeneric <double>(args[1]); } catch (Exception e) { throw new ParsingException(exceptionMessage, line, e); } }
public ParametersCollection GetFunctionTree(YamlScriptController controller, string expression = null) { localContext = new ExpressionContext(controller); localContext.Options.ParseCulture = CultureInfo.InvariantCulture; // Allow the expression to use all static public methods of System.Math localContext.Imports.AddType(typeof(Math)); // Allow the expression to use all static overload public methods our CustomFunctions class localContext.Imports.AddType(typeof(CustomFunctions)); var variables = new System.Collections.Generic.Dictionary <string, Type>(); var parameters = new ParametersCollection(); localContext.Variables.ResolveVariableType += (object sender, ResolveVariableTypeEventArgs e) => { parameters.Add(new Parameter(e.VariableName, 0, null, ref _model)); variables.Add(e.VariableName, typeof(object)); e.VariableType = typeof(object); }; if (expression != null) { try { IGenericExpression <object> eDynamic = localContext.CompileGeneric <object>(expression); } catch { } return(parameters); } foreach (var formula in _model.Formulas) { try { IGenericExpression <object> eDynamic = localContext.CompileGeneric <object>(formula.Functions[0].Expression); } catch { } } return(parameters); }
public ResponseEvaluator(string expression) { _context.Imports.AddType(typeof(Math)); foreach (var letter in _letters) { _context.Variables[letter] = default(double); } _expression = _context.CompileGeneric <double>(expression.ToUpper()); }
/// <summary> /// Evaluates an expression to an object like <see cref="bool"/> or <see cref="int"/> bases on a set of variables that should be used when evaluating /// For example evaluating to bool: /// Expression: a > 6 AND b = true /// With variables: a = 7 and b = false (these values will come from user input for parameters in the projectmodel) /// Will result in: false /// Uses https://github.com/mparlak/Flee for evaluation /// </summary> /// <param name="expression">The expression to be evaluated like a > 6 AND b = true</param> /// <param name="variables">A dictionary with the values for the variables and the letters they should replace in the evaluation</param> /// <returns></returns> public static T Evaluate(string expression, Dictionary <string, object> variables) { var context = new ExpressionContext(); VariableCollection vars = context.Variables; foreach (KeyValuePair <string, object> variable in variables) { vars.Add(variable.Key, variable.Value); } return(context.CompileGeneric <T>(expression).Evaluate()); }
public bool IsValid(JObject obj) { var expression = this.ReplaceParameters(obj, this.Condition); ExpressionContext context = new ExpressionContext(); IGenericExpression <bool> e = context.CompileGeneric <bool>(expression); bool conditionFailed = e.Evaluate(); return(conditionFailed == false); }
private static IGenericExpression <T> ParseGenericExpression <T>(string line, string fullLine, Dictionary <string, object> variables) { ExpressionContext context = FleeHelper.GetExpression(variables); try { return(context.CompileGeneric <T>(line)); } catch (Exception e) { throw new ParsingException($"Unable to parse expression of {typeof(T).FullName} from '{line}'", line, e); } }
public bool ValidateValue(double value, string validationExpression) { var expressionContext = new ExpressionContext(); expressionContext.Options.ParseCulture = CultureInfo.InvariantCulture; expressionContext.Variables.Clear(); expressionContext.Variables.Add("value", value); var expression = expressionContext.CompileGeneric <bool>(validationExpression); return(expression.Evaluate()); }
public static (string expression, bool isValid) IsValid(this string json, string condition) { JObject obj = JObject.Parse(json); var expression = ReplaceParameters(obj, condition); ExpressionContext context = new ExpressionContext(); IGenericExpression <bool> e = context.CompileGeneric <bool>(expression); return(expression, e.Evaluate()); }
public Condition(string expression) { const string variablesPattern = "{[^}]*}"; //{Field} const string inStatementPattern = @"(\w+)(\s+)(IN)(\s+)\([^\(\)]*\)"; //Field IN (value1, value2) expression = ParseVariables(expression, variablesPattern); expression = ParseINStatement(expression, inStatementPattern); // Replace "Field IN (value1, value2)" -> Field = value1 OR Field = value2 this.expression = expression.Replace("!=", "<>"); genericExpression = context.CompileGeneric <bool>(this.expression); }
public bool SatisfiesFormula(Formula formula) { VariableCollection variable = _expressionContext.Variables; foreach (var statu in _status) { variable.Add(statu.Key.ToString(), statu.Value); } bool eval = _expressionContext.CompileGeneric <bool>(formula.Expression).Evaluate(); variable.Clear(); return(eval); }
// нажатие кнопки табуляции private void TabButton_Click(object sender, RoutedEventArgs e) { int selectedId = Convert.ToInt32(IdList.SelectedItem); try { searchList.Clear(); MySqlConnection conn = new MySqlConnection(connStr); MySqlCommand command = new MySqlCommand(); string commandString = "SELECT * FROM functions WHERE id = '" + selectedId + "';"; command.CommandText = commandString; command.Connection = conn; MySqlDataReader reader; command.Connection.Open(); reader = command.ExecuteReader(); int counter = 0; while (reader.Read()) { searchList.Add(new Formula((int)reader[0], (string)reader[1], (double)reader[2], (double)reader[3], (double)reader[4], (double)reader[5])); counter++; } reader.Close(); selectList.Items.Clear(); selectList.Items.Add(searchList[0].Function + " [" + searchList[0].A + " ; " + searchList[0].B + "] dx = " + searchList[0].Dx); ExpressionContext context = new ExpressionContext(); context.Imports.AddType(typeof(Math)); context.Variables["c"] = Convert.ToDouble(searchList[0].C); context.Variables["x"] = Convert.ToDouble(searchList[0].A); IGenericExpression <double> eGeneric = context.CompileGeneric <double>(searchList[0].Function); for (double i = Convert.ToDouble(searchList[0].A); i < Convert.ToDouble(searchList[0].B) + Convert.ToDouble(searchList[0].Dx); i = i + Convert.ToDouble(searchList[0].Dx)) { context.Variables["x"] = i; double result = eGeneric.Evaluate(); selectList.Items.Add(" x = " + i + " ; y = " + result); } this.outButton.IsEnabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message + char.ConvertFromUtf32(13) + char.ConvertFromUtf32(13) + "Немає звязку з базою " + " Помилка пошуку", "Помилка", MessageBoxButton.OK, MessageBoxImage.Error); } }
protected bool EvaluateCondition(ExpressionContext context, string condition) { try { condition = condition.TrimStart("${".ToCharArray()); condition = condition.TrimEnd('}'); IGenericExpression <bool> e = context.CompileGeneric <bool>(condition); return(e.Evaluate()); } catch (System.Exception) { return(false); } }
static void Main(string[] args) { var strExp = "NOT (Zadost.NezadanaPriloha(\"50574d8389b94e6d9024eb2967565dc7\") AND _337fc4e428e84e0492db0af1f8af4458 <> null)"; var context = new ExpressionContext(); var zadostExpr = new ZadostExpression(); context.Imports.ImportBuiltinTypes(); context.Variables.Add("Zadost", zadostExpr); context.Variables.ResolveVariableType += Variables_ResolveVariableType; context.Variables.ResolveVariableValue += Variables_ResolveVariableValue; var exp = context.CompileGeneric <bool>(strExp); bool result = exp.Evaluate(); }
// валидатор математических выражений private bool Validate(string func, double c) { try { ExpressionContext context = new ExpressionContext(); context.Imports.AddType(typeof(Math)); context.Variables["c"] = c; context.Variables["x"] = 1;//test value IGenericExpression <double> eGeneric = context.CompileGeneric <double>(func); double result = eGeneric.Evaluate(); return(true); }catch (Exception ex) { return(false); } }
public void MatchReGroups_Evaluate_Test() { var exp = "MatchReGroups(_4a11d5af8466473892e0998b3d4ad37a; \"a\"; _337fc4e428e84e0492db0af1f8af4459; \"b\")"; var context = new ExpressionContext(); var zadostExpr = new ZadostExpression(); context.Imports.ImportBuiltinTypes(); context.Imports.AddType(typeof(ExpressionFunctions)); context.Variables.ResolveVariableType += ResolveVariableType_MatchReGroups_Evaluate; context.Variables.ResolveVariableValue += ResolveVariableValue_MatchReGroups_Evaluate; var method = context.CompileGeneric <bool>(exp); var result = method.Evaluate(); Assert.IsTrue(result); }
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(); }
/// <summary>Used to filter the PlayerStatsRow results based on any user-specified metric stats criteria.</summary> /// <param name="o">The o.</param> /// <returns></returns> private bool filter(object o) { var psr = (PlayerStatsRow) o; var ps = new PlayerStats(psr); var keep = true; var context = new ExpressionContext(); IGenericExpression<bool> ige; if (!String.IsNullOrWhiteSpace(_yearsProVal)) { ige = context.CompileGeneric<bool>(psr.YearsPro.ToString() + _yearsProOp + _yearsProVal); if (ige.Evaluate() == false) { return false; } } if (!String.IsNullOrWhiteSpace(_yobVal)) { context = new ExpressionContext(); ige = context.CompileGeneric<bool>(psr.YearOfBirth.ToString() + _yobOp + _yobVal); if (ige.Evaluate() == false) { return false; } } if (!String.IsNullOrWhiteSpace(_heightVal)) { var metricHeight = MainWindow.IsImperial ? PlayerStatsRow.ConvertImperialHeightToMetric(_heightVal) : Convert.ToDouble(_heightVal); context = new ExpressionContext(); ige = context.CompileGeneric<bool>(psr.Height.ToString() + _heightOp + metricHeight.ToString()); if (ige.Evaluate() == false) { return false; } } if (!String.IsNullOrWhiteSpace(_weightVal)) { var imperialWeight = MainWindow.IsImperial ? Convert.ToDouble(_weightVal) : PlayerStatsRow.ConvertMetricWeightToImperial(_weightVal); context = new ExpressionContext(); ige = context.CompileGeneric<bool>(psr.Weight.ToString() + _weightOp + imperialWeight.ToString()); if (ige.Evaluate() == false) { return false; } } if (!String.IsNullOrWhiteSpace(_contractYearsLeftVal)) { context = new ExpressionContext(); ige = context.CompileGeneric<bool>( (chkExcludeOption.IsChecked.GetValueOrDefault() ? psr.ContractYearsMinusOption.ToString() : psr.ContractYears.ToString()) + _contractYearsLeftOp + _contractYearsLeftVal); if (ige.Evaluate() == false) { return false; } } foreach (var contractYear in _contractYears) { var parts = contractYear.Split(' '); ige = context.CompileGeneric<bool>( psr.GetType().GetProperty("ContractY" + parts[1]).GetValue(psr, null) + parts[2] + parts[3]); keep = ige.Evaluate(); if (!keep) { return false; } } var stopped = false; Parallel.ForEach( _totalsFilters, (item, loopState) => { var parts = item.Split(' '); parts[0] = parts[0].Replace("3P", "TP"); parts[0] = parts[0].Replace("TO", "TOS"); context = new ExpressionContext(); ige = context.CompileGeneric<bool>(psr.GetType().GetProperty(parts[0]).GetValue(psr, null) + parts[1] + parts[2]); keep = ige.Evaluate(); if (!keep) { stopped = true; loopState.Stop(); } }); if (!keep || stopped) { return false; } Parallel.ForEach( _pgFilters, (item, loopState) => { var parts = item.Split(' '); parts[0] = parts[0].Replace("3P", "TP"); parts[0] = parts[0].Replace("%", "p"); context = new ExpressionContext(); var value = psr.GetType().GetProperty(parts[0]).GetValue(psr, null); if (!Double.IsNaN(Convert.ToDouble(value))) { ige = context.CompileGeneric<bool>(value + parts[1] + parts[2]); keep = ige.Evaluate(); } else { keep = false; } if (!keep) { stopped = true; loopState.Stop(); } }); if (!keep || stopped) { return false; } Parallel.ForEach( _metricFilters, (item, loopState) => { var parts = item.Split(' '); //parts[0] = parts[0].Replace("%", "p"); //double val = Convert.ToDouble(parts[2]); context = new ExpressionContext(); var actualValue = ps.Metrics[parts[0]]; var filterType = parts[1]; if (!double.IsNaN(actualValue)) { if (double.IsPositiveInfinity(actualValue)) { switch (filterType) { case ">": case ">=": keep = true; break; default: keep = false; break; } } else if (double.IsNegativeInfinity(actualValue)) { switch (filterType) { case "<": case "<=": keep = true; break; default: keep = false; break; } } else { ige = context.CompileGeneric<bool>(actualValue + filterType + parts[2]); keep = ige.Evaluate(); } } else { keep = false; } if (!keep) { stopped = true; loopState.Stop(); } }); if (!keep || stopped) { return false; } var expCount = _customExpressions.Count; Parallel.For( 0, expCount, (i, loopState) => { var index = i; var exp = _customExpressions[index]; var itemSParts = exp.Split(new[] { ": " }, StringSplitOptions.None); var filterParts = itemSParts[2].Split(new[] { ' ' }, 2); var filterType = filterParts[0]; var filterVal = filterParts.Length == 2 ? filterParts[1] : ""; if (filterType == "All") { return; } var actualValue = psr.Custom[index]; if (!double.IsNaN(actualValue)) { if (double.IsPositiveInfinity(actualValue)) { switch (filterType) { case ">": case ">=": keep = true; break; default: keep = false; break; } } else if (double.IsNegativeInfinity(actualValue)) { switch (filterType) { case "<": case "<=": keep = true; break; default: keep = false; break; } } else { ige = new ExpressionContext().CompileGeneric<bool>(actualValue + filterType + filterVal); keep = ige.Evaluate(); } } else { keep = false; } if (!keep) { stopped = true; loopState.Stop(); } }); if (!keep || stopped) { return false; } return keep; }
/// <summary> /// Handles the Click event of the btnSearch control. /// Implements the searching algorithm by accumulating the criteria and filtering the available players based on those criteria. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e"> /// The <see cref="RoutedEventArgs" /> instance containing the event data. /// </param> private void btnSearch_Click(object sender, RoutedEventArgs e) { dgvPlayerStats.ItemsSource = null; Dictionary<int, PlayerStats> pst = MainWindow.PST; IEnumerable<KeyValuePair<int, PlayerStats>> filteredPST = pst.AsEnumerable(); if (!String.IsNullOrWhiteSpace(txtLastName.Text)) { filteredPST = cmbLastNameSetting.SelectedItem.ToString() == "Contains" ? filteredPST.Where(pair => pair.Value.LastName.Contains(txtLastName.Text)) : filteredPST.Where(pair => pair.Value.LastName == txtLastName.Text); } if (!String.IsNullOrWhiteSpace(txtFirstName.Text)) { filteredPST = cmbFirstNameSetting.SelectedItem.ToString() == "Contains" ? filteredPST.Where(pair => pair.Value.FirstName.Contains(txtFirstName.Text)) : filteredPST.Where(pair => pair.Value.FirstName == txtFirstName.Text); } if (cmbPosition1.SelectedIndex != -1 && cmbPosition1.SelectedItem.ToString() != "Any") { filteredPST = filteredPST.Where(pair => pair.Value.Position1.ToString() == cmbPosition1.SelectedItem.ToString()); } if (cmbPosition2.SelectedIndex != -1 && cmbPosition2.SelectedItem.ToString() != "Any") { filteredPST = filteredPST.Where(pair => pair.Value.Position2.ToString() == cmbPosition2.SelectedItem.ToString()); } if (cmbContractOpt.SelectedIndex != -1 && cmbContractOpt.SelectedItem.ToString() != "Any") { filteredPST = filteredPST.Where(pair => pair.Value.Contract.Option.ToString() == cmbContractOpt.SelectedItem.ToString()); } if (chkIsActive.IsChecked.GetValueOrDefault()) { filteredPST = filteredPST.Where(pair => pair.Value.IsActive); } else if (chkIsActive.IsChecked != null) { filteredPST = filteredPST.Where(pair => !pair.Value.IsActive); } if (chkIsInjured.IsChecked.GetValueOrDefault()) { filteredPST = filteredPST.Where(pair => pair.Value.Injury.IsInjured); } else if (chkIsInjured.IsChecked != null) { filteredPST = filteredPST.Where(pair => !pair.Value.Injury.IsInjured); } if (chkIsAllStar.IsChecked.GetValueOrDefault()) { filteredPST = filteredPST.Where(pair => pair.Value.IsAllStar); } else if (chkIsAllStar.IsChecked != null) { filteredPST = filteredPST.Where(pair => !pair.Value.IsAllStar); } if (chkIsChampion.IsChecked.GetValueOrDefault()) { filteredPST = filteredPST.Where(pair => pair.Value.IsNBAChampion); } else if (chkIsChampion.IsChecked != null) { filteredPST = filteredPST.Where(pair => !pair.Value.IsNBAChampion); } if (cmbTeam.SelectedItem != null && !String.IsNullOrEmpty(cmbTeam.SelectedItem.ToString()) && chkIsActive.IsChecked.GetValueOrDefault() && cmbTeam.SelectedItem.ToString() != "- Any -") { filteredPST = filteredPST.Where(pair => pair.Value.TeamF == GetTeamIDFromDisplayName(cmbTeam.SelectedItem.ToString())); } Dictionary<int, PlayerStats> pstDict = filteredPST.ToDictionary(ps => ps.Value.ID, ps => ps.Value); List<PlayerStatsRow> psrListSea = pstDict.Values.AsParallel().Select(ps => new PlayerStatsRow(ps)).ToList(); List<PlayerStatsRow> psrListPl = pstDict.Values.AsParallel().Select(ps => new PlayerStatsRow(ps)).ToList(); List<TeamStatsRow> tsrListSea = MainWindow.TST.Values.Select(ts => new TeamStatsRow(ts)).ToList(); List<TeamStatsRow> tsrListPl = MainWindow.TST.Values.Select(ts => new TeamStatsRow(ts, true)).ToList(); List<TeamStatsRow> tsrOppListSea = MainWindow.TSTOpp.Values.Select(ts => new TeamStatsRow(ts)).ToList(); List<TeamStatsRow> tsrOppListPl = MainWindow.TSTOpp.Values.Select(ts => new TeamStatsRow(ts, true)).ToList(); #region Custom Expressions parsing dgvPlayerStats.Columns.SkipWhile(col => col.Header.ToString() != "Custom") .Skip(1) .ToList() .ForEach(col => dgvPlayerStats.Columns.Remove(col)); dgvPlayoffStats.Columns.SkipWhile(col => col.Header.ToString() != "Custom") .Skip(1) .ToList() .ForEach(col => dgvPlayoffStats.Columns.Remove(col)); List<int> includedIDs = pstDict.Keys.ToList(); var context = new ExpressionContext(); int j = 0; string message = ""; foreach (string itemS in _customExpressions) { Dictionary<int, string> expByPlayer = includedIDs.ToDictionary(id => id, id => ""); Dictionary<int, string> plExpByPlayer = includedIDs.ToDictionary(id => id, id => ""); string[] itemSParts = itemS.Split(new[] {": "}, StringSplitOptions.None); string name = itemSParts[0]; string item = itemSParts[1]; string decimalPoints = itemSParts[3]; string[] parts = item.Split(_splitOn.ToArray(), StringSplitOptions.RemoveEmptyEntries); int k = 0; PlayerStatsRow curPSR; PlayerStatsRow curPSRPl; var ignoredIDs = new List<int>(); var ignoredPlIDs = new List<int>(); for (int i = 0; i < item.Length; i++) { char c1 = item[i]; char c2; if (_numericOperators.Contains(c1.ToString())) { foreach (int id in includedIDs) { if (!ignoredIDs.Contains(id)) { expByPlayer[id] += c1; } if (!ignoredPlIDs.Contains(id)) { plExpByPlayer[id] += c1; } } } else if (c1 == '$') { try { try { c2 = item[i + 1]; } catch (IndexOutOfRangeException) { MessageBox.Show("Encountered '$' at end of custom expression."); return; } bool isPlayer; bool? isOwnTeam = null; string part; if (c2 != '$') { part = parts[k++].Substring(1); isPlayer = true; } else { part = parts[k++].Substring(3); isPlayer = false; if (item[i + 2] == 't') { isOwnTeam = true; } else if (item[i + 2] == 'o') { isOwnTeam = false; } else { MessageBox.Show("Encountered unknown/malformed parameter: " + parts[k - 1]); return; } } part = part.Replace("3P", "TP"); part = part.Replace("TO", "TOS"); part = part.Replace("%", "p"); foreach (int id in includedIDs) { if (!ignoredIDs.Contains(id)) { string val; curPSR = psrListSea.Single(psr => psr.ID == id); if (isPlayer) { val = Convert.ToDouble(typeof (PlayerStatsRow).GetProperty(part).GetValue(curPSR, null)) .ToString(".0###############"); } else { if (curPSR.TeamF == -1) { val = "NaN"; } else { TeamStatsRow curTSR = isOwnTeam == true ? tsrListSea.Single(tsr => tsr.ID == curPSR.TeamF) : tsrOppListSea.Single(tsr => tsr.ID == curPSR.TeamF); val = Convert.ToDouble(typeof (TeamStatsRow).GetProperty(part).GetValue(curTSR, null)) .ToString(".0###############"); } } if (val != "NaN") { expByPlayer[id] += val; } else { ignoredIDs.Add(id); expByPlayer[id] = "$$INVALID"; } } if (!ignoredPlIDs.Contains(id)) { string plVal; curPSRPl = psrListPl.Single(psr => psr.ID == id); if (isPlayer) { plVal = Convert.ToDouble(typeof (PlayerStatsRow).GetProperty(part).GetValue(curPSRPl, null)) .ToString(".0###############"); } else { if (curPSRPl.TeamF == -1) { plVal = "NaN"; } else { TeamStatsRow curTSRPl = isOwnTeam == true ? tsrListPl.Single(tsr => tsr.ID == curPSRPl.TeamF) : tsrOppListPl.Single(tsr => tsr.ID == curPSRPl.TeamF); plVal = Convert.ToDouble(typeof (TeamStatsRow).GetProperty(part).GetValue(curTSRPl, null)) .ToString(".0###############"); } } if (plVal != "NaN") { plExpByPlayer[id] += plVal; } else { ignoredPlIDs.Add(id); plExpByPlayer[id] = "$$INVALID"; } } } if (isPlayer) { i += part.Length; // should be Length-1 but we're using Substring(1) in part's initialization } else { i += part.Length + 2; // we're using Substring(3) } } catch (Exception ex) { MessageBox.Show("Error encountered while trying to evaluate custom expression parameter.\n\n" + ex.Message); return; } } else if (Tools.IsNumeric(parts[k])) { string part = parts[k++]; foreach (int id in includedIDs) { if (!ignoredIDs.Contains(id)) { expByPlayer[id] += part; } if (!ignoredPlIDs.Contains(id)) { plExpByPlayer[id] += part; } } i += part.Length - 1; } } foreach (int id in includedIDs) { curPSR = psrListSea.Single(psr => psr.ID == id); curPSRPl = psrListPl.Single(psr => psr.ID == id); if (!ignoredIDs.Contains(id)) { try { IGenericExpression<double> compiled = context.CompileGeneric<double>(expByPlayer[id]); curPSR.Custom.Add(compiled.Evaluate()); } catch (Exception ex) { message = string.Format("Expression {0}:\n{1}\nevaluated to\n{2}\n\nError: {3}", (j + 1), item, expByPlayer[id], ex.Message); curPSR.Custom.Add(double.NaN); } } else { curPSR.Custom.Add(double.NaN); } if (!ignoredPlIDs.Contains(id)) { try { IGenericExpression<double> compiled = context.CompileGeneric<double>(plExpByPlayer[id]); curPSRPl.Custom.Add(compiled.Evaluate()); } catch (Exception ex) { message = string.Format("Expression {0}:\n{1}\nevaluated to\n{2}\n\nError: {3}", (j + 1), item, plExpByPlayer[id], ex.Message); curPSRPl.Custom.Add(double.NaN); } } else { curPSRPl.Custom.Add(double.NaN); } } dgvPlayerStats.Columns.Add(new DataGridTextColumn { Header = name, Binding = new Binding { Path = new PropertyPath(string.Format("Custom[{0}]", j)), Mode = BindingMode.OneWay, StringFormat = "{0:F" + decimalPoints + "}" } }); dgvPlayoffStats.Columns.Add(new DataGridTextColumn { Header = name, Binding = new Binding { Path = new PropertyPath(string.Format("Custom[{0}]", j)), Mode = BindingMode.OneWay, StringFormat = "{0:F" + decimalPoints + "}" } }); j++; } #endregion Custom Expressions parsing ICollectionView psrView = CollectionViewSource.GetDefaultView(psrListSea); psrView.Filter = filter; ICollectionView plPSRView = CollectionViewSource.GetDefaultView(psrListPl); plPSRView.Filter = filter; dgvPlayerStats.ItemsSource = psrView; dgvPlayoffStats.ItemsSource = plPSRView; string sortColumn; foreach (string item in lstMetrics.Items.Cast<string>()) { sortColumn = item.Split(' ')[0]; sortColumn = sortColumn.Replace("%", "p"); psrView.SortDescriptions.Add(new SortDescription(sortColumn, ListSortDirection.Descending)); plPSRView.SortDescriptions.Add(new SortDescription(sortColumn, ListSortDirection.Descending)); } foreach (string item in lstAvg.Items.Cast<string>()) { sortColumn = item.Split(' ')[0]; sortColumn = sortColumn.Replace("3P", "TP"); sortColumn = sortColumn.Replace("%", "p"); psrView.SortDescriptions.Add(new SortDescription(sortColumn, ListSortDirection.Descending)); plPSRView.SortDescriptions.Add(new SortDescription(sortColumn, ListSortDirection.Descending)); } foreach (string item in lstTotals.Items.Cast<string>()) { sortColumn = item.Split(' ')[0]; sortColumn = sortColumn.Replace("3P", "TP"); sortColumn = sortColumn.Replace("TO", "TOS"); psrView.SortDescriptions.Add(new SortDescription(sortColumn, ListSortDirection.Descending)); plPSRView.SortDescriptions.Add(new SortDescription(sortColumn, ListSortDirection.Descending)); } if (psrView.SortDescriptions.Count == 0) { dgvPlayerStats.Columns.Single(col => col.Header.ToString() == "GmSc").SortDirection = ListSortDirection.Descending; dgvPlayoffStats.Columns.Single(col => col.Header.ToString() == "GmSc").SortDirection = ListSortDirection.Descending; psrView.SortDescriptions.Add(new SortDescription("GmSc", ListSortDirection.Descending)); plPSRView.SortDescriptions.Add(new SortDescription("GmSc", ListSortDirection.Descending)); } tbcPlayerSearch.SelectedItem = tabResults; if (!String.IsNullOrWhiteSpace(message)) { const string warning = "An error occurred while trying to evaluate one or more of the custom column expressions:\n\n"; const string contact = "\n\nIf you believe your expression is correct and that you shouldn't be getting this error, contact the developer " + "and give them this information."; var cmw = new CopyableMessageWindow(warning + message + contact, "Error while evaluating expression", beep: true); cmw.ShowDialog(); } }
/// <summary> /// Used to filter the PlayerStatsRow results based on any user-specified metric stats criteria. /// </summary> /// <param name="o">The o.</param> /// <returns></returns> private bool filter(object o) { var psr = (PlayerStatsRow) o; var ps = new PlayerStats(psr); bool keep = true; var context = new ExpressionContext(); IGenericExpression<bool> ige; if (!String.IsNullOrWhiteSpace(txtYearsProVal.Text)) { ige = context.CompileGeneric<bool>(psr.YearsPro.ToString() + cmbYearsProOp.SelectedItem + txtYearsProVal.Text); if (ige.Evaluate() == false) { return false; } } if (!String.IsNullOrWhiteSpace(txtYOBVal.Text)) { context = new ExpressionContext(); ige = context.CompileGeneric<bool>(psr.YearOfBirth.ToString() + cmbYOBOp.SelectedItem + txtYOBVal.Text); if (ige.Evaluate() == false) { return false; } } if (!String.IsNullOrWhiteSpace(txtHeightVal.Text)) { double metricHeight = MainWindow.IsImperial ? PlayerStatsRow.ConvertImperialHeightToMetric(txtHeightVal.Text) : Convert.ToDouble(txtHeightVal.Text); context = new ExpressionContext(); ige = context.CompileGeneric<bool>(psr.Height.ToString() + cmbHeightOp.SelectedItem + metricHeight.ToString()); if (ige.Evaluate() == false) { return false; } } if (!String.IsNullOrWhiteSpace(txtWeightVal.Text)) { double imperialWeight = MainWindow.IsImperial ? Convert.ToDouble(txtWeightVal.Text) : PlayerStatsRow.ConvertMetricWeightToImperial(txtWeightVal.Text); context = new ExpressionContext(); ige = context.CompileGeneric<bool>(psr.Weight.ToString() + cmbWeightOp.SelectedItem + imperialWeight.ToString()); if (ige.Evaluate() == false) { return false; } } if (!String.IsNullOrWhiteSpace(txtContractYLeftVal.Text)) { context = new ExpressionContext(); ige = context.CompileGeneric<bool>((chkExcludeOption.IsChecked.GetValueOrDefault() ? psr.ContractYearsMinusOption.ToString() : psr.ContractYears.ToString()) + cmbContractYLeftOp.SelectedItem + txtContractYLeftVal.Text); if (ige.Evaluate() == false) { return false; } } foreach (string contractYear in lstContract.Items.Cast<string>()) { string[] parts = contractYear.Split(' '); ige = context.CompileGeneric<bool>(psr.GetType().GetProperty("ContractY" + parts[1]).GetValue(psr, null) + parts[2] + parts[3]); keep = ige.Evaluate(); if (!keep) { return keep; } } IEnumerable<string> totalsFilters = lstTotals.Items.Cast<string>(); Parallel.ForEach(totalsFilters, (item, loopState) => { string[] parts = item.Split(' '); parts[0] = parts[0].Replace("3P", "TP"); parts[0] = parts[0].Replace("TO", "TOS"); context = new ExpressionContext(); ige = context.CompileGeneric<bool>(psr.GetType().GetProperty(parts[0]).GetValue(psr, null) + parts[1] + parts[2]); keep = ige.Evaluate(); if (!keep) { loopState.Stop(); } }); if (!keep) { return keep; } IEnumerable<string> pgFilters = lstAvg.Items.Cast<string>(); Parallel.ForEach(pgFilters, (item, loopState) => { string[] parts = item.Split(' '); parts[0] = parts[0].Replace("3P", "TP"); parts[0] = parts[0].Replace("%", "p"); context = new ExpressionContext(); object value = psr.GetType().GetProperty(parts[0]).GetValue(psr, null); if (!Double.IsNaN(Convert.ToDouble(value))) { ige = context.CompileGeneric<bool>(value + parts[1] + parts[2]); keep = ige.Evaluate(); } else { keep = false; } if (!keep) { loopState.Stop(); } }); if (!keep) { return keep; } IEnumerable<string> metricFilters = lstMetrics.Items.Cast<string>(); Parallel.ForEach(metricFilters, (item, loopState) => { string[] parts = item.Split(' '); parts[0] = parts[0].Replace("%", "p"); //double val = Convert.ToDouble(parts[2]); context = new ExpressionContext(); double actualValue = ps.Metrics[parts[0]]; string filterType = parts[1]; if (!double.IsNaN(actualValue)) { if (double.IsPositiveInfinity(actualValue)) { switch (filterType) { case ">": case ">=": keep = true; break; default: keep = false; break; } } else if (double.IsNegativeInfinity(actualValue)) { switch (filterType) { case "<": case "<=": keep = true; break; default: keep = false; break; } } else { ige = context.CompileGeneric<bool>(actualValue + filterType + parts[2]); keep = ige.Evaluate(); } } else { keep = false; } if (!keep) { loopState.Stop(); } }); if (!keep) { return keep; } int expCount = _customExpressions.Count; Parallel.For(0, expCount, (i, loopState) => { int index = i; string exp = _customExpressions[index]; string[] itemSParts = exp.Split(new[] {": "}, StringSplitOptions.None); string[] filterParts = itemSParts[2].Split(new[] {' '}, 2); string filterType = filterParts[0]; string filterVal = filterParts.Length == 2 ? filterParts[1] : ""; if (filterType == "All") { return; } double actualValue = psr.Custom[index]; if (!double.IsNaN(actualValue)) { if (double.IsPositiveInfinity(actualValue)) { switch (filterType) { case ">": case ">=": keep = true; break; default: keep = false; break; } } else if (double.IsNegativeInfinity(actualValue)) { switch (filterType) { case "<": case "<=": keep = true; break; default: keep = false; break; } } else { ige = new ExpressionContext().CompileGeneric<bool>(actualValue + filterType + filterVal); keep = ige.Evaluate(); } } else { keep = false; } if (!keep) { loopState.Stop(); } }); return keep; }
private void btnSearch_Click(object sender, RoutedEventArgs e) { _playersToHighlight.Clear(); _teamsToHighlight.Clear(); var bsToCalculate = new List<BoxScoreEntry>(); var notBsToCalculate = new List<BoxScoreEntry>(); foreach (BoxScoreEntry bse in MainWindow.BSHist) { bool keep = true; foreach (var filter in _filters) { if (filter.Key.SelectionType == SelectionType.Team) { if (!_teamsToHighlight.Contains(filter.Key.ID)) { _teamsToHighlight.Add(filter.Key.ID); } //string teamName = MainWindow.TeamOrder.Single(pair => pair.Value == filter.Key.ID).Key; if (bse.BS.Team1ID != filter.Key.ID && bse.BS.Team2ID != filter.Key.ID) { keep = false; break; } string p = bse.BS.Team1ID == filter.Key.ID ? "1" : "2"; string oppP = p == "1" ? "2" : "1"; foreach (Filter option in filter.Value) { string parameter; if (!option.Parameter1.StartsWith("Opp")) { switch (option.Parameter1) { case "PF": parameter = "PTS" + p; break; case "PA": parameter = "PTS" + oppP; break; default: parameter = option.Parameter1 + p; break; } } else { parameter = option.Parameter1.Substring(3) + oppP; } parameter = parameter.Replace("3P", "TP"); parameter = parameter.Replace("TO", "TOS"); string parameter2; if (!option.Parameter2.StartsWith("Opp")) { switch (option.Parameter2) { case "PF": parameter2 = "PTS" + p; break; case "PA": parameter2 = "PTS" + oppP; break; default: parameter2 = option.Parameter2 + p; break; } } else { parameter2 = option.Parameter2.Substring(3) + oppP; } parameter2 = parameter2.Replace("3P", "TP"); parameter2 = parameter2.Replace("TO", "TOS"); var context = new ExpressionContext(); IGenericExpression<bool> ige; if (String.IsNullOrWhiteSpace(parameter2)) { if (!parameter.Contains("%")) { ige = context.CompileGeneric<bool>(string.Format("{0} {1} {2}", bse.BS.GetType() .GetProperty(parameter) .GetValue(bse.BS, null), option.Operator, option.Value)); } else { string par1 = parameter.Replace("%", "M"); string par2 = parameter.Replace("%", "A"); ige = context.CompileGeneric<bool>( string.Format("(Cast({0}, double) / Cast({1}, double)) {2} Cast({3}, double)", bse.BS.GetType().GetProperty(par1).GetValue(bse.BS, null), bse.BS.GetType().GetProperty(par2).GetValue(bse.BS, null), option.Operator, option.Value)); } } else { if (!parameter.Contains("%")) { if (!parameter2.Contains("%")) { ige = context.CompileGeneric<bool>(string.Format("{0} {1} {2}", getValue(bse, parameter), option.Operator, getValue(bse, parameter2))); } else { string par2Part1 = parameter2.Replace("%", "M"); string par2Part2 = parameter2.Replace("%", "A"); ige = context.CompileGeneric<bool>( string.Format("Cast({0}, double) {1} (Cast({2}, double) / Cast({3}, double))", getValue(bse, parameter), option.Operator, getValue(bse, par2Part1), getValue(bse, par2Part2))); } } else { if (!parameter2.Contains("%")) { string par1Part1 = parameter.Replace("%", "M"); string par1Part2 = parameter.Replace("%", "A"); ige = context.CompileGeneric<bool>( string.Format("(Cast({0}, double) / Cast({1}, double)) {2} Cast({3}, double)", getValue(bse, par1Part1), getValue(bse, par1Part2), option.Operator, getValue(bse, parameter2))); } else { string par1Part1 = parameter.Replace("%", "M"); string par1Part2 = parameter.Replace("%", "A"); string par2Part1 = parameter2.Replace("%", "M"); string par2Part2 = parameter2.Replace("%", "A"); ige = context.CompileGeneric<bool>( string.Format( "(Cast({0}, double) / Cast({1}, double)) {2} (Cast({3}, double) / Cast({4}, double))", getValue(bse, par1Part1), getValue(bse, par1Part2), option.Operator, getValue(bse, par2Part1), getValue(bse, par2Part2))); } } } if (ige.Evaluate() == false) { keep = false; notBsToCalculate.Add(bse); break; } } if (!keep) { break; } } else { if (!_playersToHighlight.Contains(filter.Key.ID)) { _playersToHighlight.Add(filter.Key.ID); } PlayerBoxScore pbs; try { pbs = bse.PBSList.Single(pbs1 => pbs1.PlayerID == filter.Key.ID); } catch (InvalidOperationException) { keep = false; break; } foreach (Filter option in filter.Value) { string parameter = option.Parameter1; parameter = parameter.Replace("3P", "TP"); parameter = parameter.Replace("TO", "TOS"); var context = new ExpressionContext(); IGenericExpression<bool> ige; if (!parameter.Contains("%")) { ige = context.CompileGeneric<bool>(string.Format("{0} {1} {2}", pbs.GetType().GetProperty(parameter).GetValue(pbs, null), option.Operator, option.Value)); } else { string par1 = parameter.Replace("%", "M"); string par2 = parameter.Replace("%", "A"); ige = context.CompileGeneric<bool>( string.Format("(Cast({0}, double) / Cast({1}, double)) {2} Cast({3}, double)", pbs.GetType().GetProperty(par1).GetValue(pbs, null), pbs.GetType().GetProperty(par2).GetValue(pbs, null), option.Operator, option.Value)); } if (ige.Evaluate() == false) { keep = false; notBsToCalculate.Add(bse); break; } } if (!keep) { break; } } } if (keep) { bsToCalculate.Add(bse); } } calculateAdvancedStats(bsToCalculate, notBsToCalculate); tbcAdv.SelectedItem = tabPlayerStats; }
private void compileExpression() { ExpressionContext context = new ExpressionContext(); // Allows use of all public static Math functions: //context.Imports.AddType(typeof(Math)); // Load values into Flee context. foreach (KeyValuePair<string, long> pair in formulaIDToIntegerValue) { context.Variables[pair.Key] = pair.Value; } foreach (KeyValuePair<string, double> pair in formulaIDToFloatingPointValue) { context.Variables[pair.Key] = pair.Value; } compiledExpression = context.CompileGeneric<double>(cleanFormula(ScoringFormula)); }
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 void btnSearch_Click(object sender, RoutedEventArgs e) { _playersToHighlight.Clear(); _teamsToHighlight.Clear(); var bsToCalculate = new List<BoxScoreEntry>(); var notBsToCalculate = new List<BoxScoreEntry>(); var doPlays = chkUsePBP.IsChecked == true; #region Initialize PBP Filters int curEventKey; if (cmbEventType.SelectedIndex <= 0) { curEventKey = -2; } else { curEventKey = PlayByPlayEntry.EventTypes.Single(pair => pair.Value == cmbEventType.SelectedItem.ToString()).Key; } int curPlayer1ID; if (cmbPlayer1.SelectedIndex <= 0) { curPlayer1ID = -1; } else { curPlayer1ID = ((KeyValuePair<int, string>) (((cmbPlayer1)).SelectedItem)).Key; _playersToHighlight.Add(curPlayer1ID); } int curPlayer2ID; if (cmbPlayer2.SelectedIndex <= 0) { curPlayer2ID = -1; } else { curPlayer2ID = ((KeyValuePair<int, string>) (((cmbPlayer2)).SelectedItem)).Key; _playersToHighlight.Add(curPlayer2ID); } int curLocation; if (cmbLocationShotDistance.SelectedIndex <= 0) { curLocation = -2; } else { curLocation = curEventKey == 2 ? ShotEntry.ShotDistances.Single( dist => dist.Value == cmbLocationShotDistance.SelectedItem.ToString()).Key : PlayByPlayEntry.EventLocations.Single( loc => loc.Value == cmbLocationShotDistance.SelectedItem.ToString()).Key; } int shotOrigin; if (cmbShotOrigin.SelectedIndex <= 0 || cmbShotOrigin.IsEnabled == false) { shotOrigin = -2; } else { shotOrigin = ShotEntry.ShotOrigins.Single(orig => orig.Value == cmbShotOrigin.SelectedItem.ToString()).Key; } int shotType; if (cmbShotType.SelectedIndex <= 0 || cmbShotType.IsEnabled == false) { shotType = -2; } else { shotType = ShotEntry.ShotTypes.Single(orig => orig.Value == cmbShotType.SelectedItem.ToString()).Key; } var shotIsMade = chkShotIsMade.IsEnabled ? chkShotIsMade.IsChecked : null; var shotIsAssisted = chkShotIsAssisted.IsEnabled ? chkShotIsAssisted.IsChecked : null; double timeLeft; if (cmbTimeLeftOp.SelectedIndex > 0) { try { timeLeft = PlayByPlayWindow.ConvertTimeStringToDouble(txtTimeLeftPar.Value as string); } catch { timeLeft = -1; } } else { timeLeft = -1; } double shotClock; if (cmbShotClockOp.SelectedIndex > 0) { try { shotClock = PlayByPlayWindow.ConvertTimeStringToDouble(txtShotClockPar.Value as string); } catch { shotClock = -1; } } else { shotClock = -1; } int period; if (cmbPeriodOp.SelectedIndex > 0) { try { period = (txtPeriodPar.Value as string).ToInt32(); } catch { period = Int32.MinValue; } } else { period = Int32.MinValue; } #endregion foreach (var bse in MainWindow.BSHist) { var keep = true; #region Apply Box Score Filters foreach (var filter in _filters) { if (filter.Key.SelectionType == SearchItem.SelectionType.Team) { if (!_teamsToHighlight.Contains(filter.Key.ID)) { _teamsToHighlight.Add(filter.Key.ID); } //string teamName = MainWindow.TeamOrder.Single(pair => pair.Value == filter.Key.ID).Key; if (bse.BS.Team1ID != filter.Key.ID && bse.BS.Team2ID != filter.Key.ID) { keep = false; break; } var p = bse.BS.Team1ID == filter.Key.ID ? "1" : "2"; var oppP = p == "1" ? "2" : "1"; foreach (var option in filter.Value) { string parameter; if (!option.Parameter1.StartsWith("Opp")) { switch (option.Parameter1) { case "PF": parameter = "PTS" + p; break; case "PA": parameter = "PTS" + oppP; break; default: parameter = option.Parameter1 + p; break; } } else { parameter = option.Parameter1.Substring(3) + oppP; } parameter = parameter.Replace("3P", "TP"); parameter = parameter.Replace("TO", "TOS"); var parameter2 = ""; if (!String.IsNullOrWhiteSpace(option.Parameter2)) { if (!option.Parameter2.StartsWith("Opp")) { switch (option.Parameter2) { case "PF": parameter2 = "PTS" + p; break; case "PA": parameter2 = "PTS" + oppP; break; default: parameter2 = option.Parameter2 + p; break; } } else { parameter2 = option.Parameter2.Substring(3) + oppP; } parameter2 = parameter2.Replace("3P", "TP"); parameter2 = parameter2.Replace("TO", "TOS"); } var context = new ExpressionContext(); IGenericExpression<bool> ige; if (String.IsNullOrWhiteSpace(parameter2)) { if (!parameter.Contains("%")) { ige = context.CompileGeneric<bool>( string.Format( "{0} {1} {2}", bse.BS.GetType().GetProperty(parameter).GetValue(bse.BS, null), option.Operator, option.Value)); } else { var par1 = parameter.Replace("%", "M"); var par2 = parameter.Replace("%", "A"); ige = context.CompileGeneric<bool>( string.Format( "(Cast({0}, double) / Cast({1}, double)) {2} Cast({3}, double)", bse.BS.GetType().GetProperty(par1).GetValue(bse.BS, null), bse.BS.GetType().GetProperty(par2).GetValue(bse.BS, null), option.Operator, option.Value)); } } else { if (!parameter.Contains("%")) { if (!parameter2.Contains("%")) { ige = context.CompileGeneric<bool>( string.Format( "{0} {1} {2}", getValue(bse, parameter), option.Operator, getValue(bse, parameter2))); } else { var par2Part1 = parameter2.Replace("%", "M"); var par2Part2 = parameter2.Replace("%", "A"); ige = context.CompileGeneric<bool>( string.Format( "Cast({0}, double) {1} (Cast({2}, double) / Cast({3}, double))", getValue(bse, parameter), option.Operator, getValue(bse, par2Part1), getValue(bse, par2Part2))); } } else { if (!parameter2.Contains("%")) { var par1Part1 = parameter.Replace("%", "M"); var par1Part2 = parameter.Replace("%", "A"); ige = context.CompileGeneric<bool>( string.Format( "(Cast({0}, double) / Cast({1}, double)) {2} Cast({3}, double)", getValue(bse, par1Part1), getValue(bse, par1Part2), option.Operator, getValue(bse, parameter2))); } else { var par1Part1 = parameter.Replace("%", "M"); var par1Part2 = parameter.Replace("%", "A"); var par2Part1 = parameter2.Replace("%", "M"); var par2Part2 = parameter2.Replace("%", "A"); ige = context.CompileGeneric<bool>( string.Format( "(Cast({0}, double) / Cast({1}, double)) {2} (Cast({3}, double) / Cast({4}, double))", getValue(bse, par1Part1), getValue(bse, par1Part2), option.Operator, getValue(bse, par2Part1), getValue(bse, par2Part2))); } } } if (ige.Evaluate() == false) { keep = false; notBsToCalculate.Add(bse); break; } } if (!keep) { break; } } else { if (!_playersToHighlight.Contains(filter.Key.ID)) { _playersToHighlight.Add(filter.Key.ID); } PlayerBoxScore pbs; try { pbs = bse.PBSList.Single(pbs1 => pbs1.PlayerID == filter.Key.ID); } catch (InvalidOperationException) { keep = false; break; } foreach (var option in filter.Value) { var parameter = option.Parameter1; parameter = parameter.Replace("3P", "TP"); parameter = parameter.Replace("TO", "TOS"); var context = new ExpressionContext(); IGenericExpression<bool> ige; if (!parameter.Contains("%")) { ige = context.CompileGeneric<bool>( string.Format( "{0} {1} {2}", pbs.GetType().GetProperty(parameter).GetValue(pbs, null), option.Operator, option.Value)); } else { var par1 = parameter.Replace("%", "M"); var par2 = parameter.Replace("%", "A"); ige = context.CompileGeneric<bool>( string.Format( "(Cast({0}, double) / Cast({1}, double)) {2} Cast({3}, double)", pbs.GetType().GetProperty(par1).GetValue(pbs, null), pbs.GetType().GetProperty(par2).GetValue(pbs, null), option.Operator, option.Value)); } if (ige.Evaluate() == false) { keep = false; notBsToCalculate.Add(bse); break; } } if (!keep) { break; } } } #endregion if (doPlays) { var pbpeList = bse.PBPEList.ToList(); // Event Type if (curEventKey > -2) { pbpeList = pbpeList.Where(pbpe => pbpe.EventType == curEventKey).ToList(); if (curEventKey == -1) { pbpeList = pbpeList.Where(pbpe => pbpe.EventDesc == txtEventDesc.Text).ToList(); } } // Player 1 if (curPlayer1ID > -1) { pbpeList = pbpeList.Where(pbpe => pbpe.Player1ID == curPlayer1ID).ToList(); } // Player 2 if (curPlayer2ID > -1) { pbpeList = pbpeList.Where(pbpe => pbpe.Player2ID == curPlayer2ID).ToList(); } // Location if (curLocation > -2) { pbpeList = curEventKey == 2 ? pbpeList.Where(pbpe => pbpe.ShotEntry.Distance == curLocation).ToList() : pbpeList.Where(pbpe => pbpe.Location == curLocation).ToList(); if (curLocation == -1) { pbpeList = pbpeList.Where(pbpe => pbpe.LocationDesc == txtLocationDesc.Text).ToList(); } } // Shot Origin if (shotOrigin > -2) { pbpeList = pbpeList.Where(pbpe => pbpe.ShotEntry.Origin == shotOrigin).ToList(); } // Shot Type if (shotType > -2) { pbpeList = pbpeList.Where(pbpe => pbpe.ShotEntry.Type == shotType).ToList(); } // Shot Is Made if (shotIsMade != null) { pbpeList = pbpeList.Where(pbpe => pbpe.ShotEntry.IsMade == (shotIsMade == true)).ToList(); } // Shot Is Assisted if (shotIsAssisted != null) { pbpeList = pbpeList.Where(pbpe => pbpe.ShotEntry.IsAssisted == (shotIsAssisted == true)).ToList(); } // Time Left if (timeLeft > -0.5) { pbpeList = pbpeList.Where( pbpe => new ExpressionContext().CompileGeneric<bool>( string.Format("{0} {1} {2}", pbpe.TimeLeft, cmbTimeLeftOp.SelectedItem.ToString(), timeLeft)) .Evaluate()).ToList(); } // Shot Clock if (shotClock > -0.5) { pbpeList = pbpeList.Where( pbpe => new ExpressionContext().CompileGeneric<bool>( string.Format("{0} {1} {2}", pbpe.ShotClockLeft, cmbShotClockOp.SelectedItem.ToString(), shotClock)) .Evaluate()).ToList(); } // Period if (period > Int32.MinValue) { pbpeList = pbpeList.Where( pbpe => new ExpressionContext().CompileGeneric<bool>( string.Format("{0} {1} {2}", pbpe.Quarter, cmbPeriodOp.SelectedItem.ToString(), period)).Evaluate()) .ToList(); } // Players on the floor pbpeList = PlayersOnTheFloor.Aggregate( pbpeList, (current, pid) => current.Where(pbpe => pbpe.Team1PlayerIDs.Contains(pid) || pbpe.Team2PlayerIDs.Contains(pid)).ToList()); // Check if we should include this box score if (pbpeList.Count == 0) { keep = false; notBsToCalculate.Add(bse); } bse.FilteredPBPEList = pbpeList; } if (keep) { bsToCalculate.Add(bse); } } calculateAdvancedStats(bsToCalculate, notBsToCalculate, doPlays); tbcAdv.SelectedItem = tabPlayerStats; }
public Widgets ReadWidgets(List<Filter> filters) { Widgets widgets = _repository; string linqExpression = filters.ToLinqExpression<Widget>("o"); if (linqExpression != String.Empty) { ExpressionContext context = new ExpressionContext(); context.Variables.DefineVariable("o", typeof(Widget)); for (int i = 0; i < widgets.Count; i++) { context.Variables["o"] = widgets[i]; var expression = context.CompileGeneric<bool>(linqExpression); try { if (!expression.Evaluate()) { widgets.RemoveAt(i--); } } catch { } //If Expression fails to eval for item ignore item. } } return widgets; }