Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Executing JavaScript Compliance Formula from C#

0.00/5 (No votes)
23 Nov 2015 1  
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...

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here