65.9K
CodeProject is changing. Read more.
Home

Executing JavaScript Compliance Formula from C#

starIconstarIconstarIconstarIconstarIcon

5.00/5 (5 votes)

Nov 23, 2015

CPOL

1 min read

viewsIcon

14103

Executing JavaScript eval function from C#

Introduction

Execute JavaScript validation formula input from the UX layer of Windows application from C# code. This is to simplify the validation complexities of executing user defined formulas by C#.

Background

The requirement is to execute the formula against dynamic values for validation. Validation is done for the values of variables to which the formula is applied. All values are unknown to the user at the time of defining the formula but variables.

Using the Code

Sample screen for fields to which the formula needs to be applied is shown below.

Input sample

Alternatively, formula can be defined to columns of data which is in tabular format. See the below screen shot.

Sample input 2

For this POC, we are stimulating the above dummy data to a console application. To achieve the above depicted scenario, we follow the below steps.

Step 1

Define classes in C# which can be converted to JSON. (Doing this, the data is visible to the JavaScript function.)

Class diagram

Step 2

Generated JSON data and its code is shown below.

JSON output

JSON conversion relevant code is as follows:

//
 private static JavascriptContext context = new JavascriptContext();
  ........//Other code...
 Console.WriteLine(JsonConvert.SerializeObject(document));
//

Main Code

private static void initJS()
        {
            context.SetParameter("console", new SystemConsole());
            context.SetParameter("expression", JSONComplianceExpression(expression));
        }

        private static string getJS()
        {
            return "vary data = " + JsonConvert.SerializeObject(document) + "; " +
               "console.Print('Result='+eval(expression));";
        }

        private static string JSONComplianceExpression(string expression)
        {
            for (int i = 0; i < document.Fields.Count; i++)
                if (expression.Contains(document.Fields[i].ID))
                    expression = expression.Replace(document.Fields[i].ID, 
                    "eval(data.Fields[" + i + "].Value)");

            for (int i = 0; i < document.Table.Columns.Count; i++)
                if (expression.Contains(document.Table.Columns[i].ID))
                {
                    int offset = expression.IndexOf(document.Table.Columns[i].ID)+ 
                    	document.Table.Columns[i].ID.Length;
                    string op = expression.Substring(offset, 1);
                    if(op==")")
                    {
                        offset = expression.IndexOf(document.Table.Columns[i].ID);
                        op = expression.Substring(offset-1, 1);
                    }
                    switch(op)
                    {
                        case "+":
                        case "*":
                        case "/":
                        case "-":
                            double sigma = 0;
                            foreach (string s in document.Table.Columns[i])
                            {
                                sigma += double.Parse(s);
                            }
                            expression = expression.Replace
				(document.Table.Columns[i].ID,sigma.ToString());
                            break;   
                    }                    
                }

            return expression;
        }
    }

Tested Input Formula

Field001+Field002+Field003
(Field001+Field002)+Field003 
(Column001+Column002)+Field002 

-- sum of all first column values + sum of all second column values. 
-- Applicable to all other formulas as well.

(Column001*Column002)+Field002
(Column001-Column002)+Field002

Sample Input

JavaScriptValidation [input without space]

e.g. JavaScriptValidation (Column001+Column002)+Field002

Sample Output

Points of Interest

Converting the data to JSON format is the key here. So it can be scalable for many formulas. JavaScript functions can do processing on this data to get the desired result.

History

I will update this in a more intuitive way later...