Click here to Skip to main content
15,881,173 members
Articles / Programming Languages / Javascript
Tip/Trick

Executing JavaScript Compliance Formula from C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
23 Nov 2015CPOL1 min read 13.7K   3   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:

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

Main Code

C#
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

Image 5

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Automation Anywhere
India India
Working as Lead Architect at Automation Anywhere.

Comments and Discussions

 
AnswerFormat issues.. Pin
Afzaal Ahmad Zeeshan23-Nov-15 2:04
professionalAfzaal Ahmad Zeeshan23-Nov-15 2:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.