About dynamic values in templates---Reflection and JavaScript script compilation

Source: Internet
Author: User

Often in projects, when you print Word or print Excel, we often make changes to the template using one-to-many assignment or batch substitution.

But now there are two kinds of scenarios:

1, the value is determined by the method to take the value.

such as: A sales document, there are many kinds of fees, and these costs are configured in the background, very flexible. But we're going to take a value on the cost of making a print template. How do we define him, and how to assign him a value? If we have a special definition for a template under this scenario, do we need to do special processing when we print another document or encounter the same data with very flexible values?

2, the value is by the self-defined to take the value.

such as: or a sales document, we may print the sale price, cost, gross profit, but if we print the time involved in the proportion of the Commission, the ratio of the Commission may be based on the sales price, may be calculated according to the profit, it may be calculated according to the benefits, then is not we do this template when defined: Commission (by cost) , Commission (by gross margin), commission ....

In this case, my solution is to use reflection and JavaScript for processing:

Here about my solution to the idea, you pass the great God, you fight the first line of the procedure apes, have seen a laugh, do not like to spray ~

Step one: Set up two eval methods to parse an expression

C#eval Reflective: (This approach mainly to the custom method in the program, according to the parameters and methods to simulate the calculation in the program, and return the results in the past, this method must be developed to deal with his principal object)

<summary>///Cshrapeval Summary description///</summary>public class cshrapeval{//<summary>//    Evaluates, throws an exception if an expression is faulted     //</summary> public static Object Eval (String Action,type type,object obj,object[] Parm)    {        return type. InvokeMember (                    action,                    BindingFlags.InvokeMethod,                    null,                    obj,                  parm                  );    }    public static Object Eval (string Cstring, type type, object obj)    {        string action = Cstring.split (' | ') [0];        object[] Parm = cstring.split (' | ') [1]. Split (', ');        return type. InvokeMember (                    action,                    BindingFlags.InvokeMethod,                    null,                    obj,                  parm                 );}    }

JavaScript scripting Way: Simulate how JavaScript works to handle a representation, you can use a common JavaScript function (such as getdate () length, etc.), flexible and convenient

 

/**////<summary>///Dynamic Evaluation///</summary>public class javaeval{/**///<summary>///calculation result, if expression Error throws exception///</summary>//<param name= "statement" > expression, such as "1+2+3+4" </param>///<returns> Results                    </returns> public static Object Eval (String statement) {return _evaluatortype.invokemember (                    "Eval", BindingFlags.InvokeMethod, NULL, _evaluator,    New object[] {statement});        }/**////<summary>///</summary> static javaeval () {//construct JScript for compiled driver code        CodeDomProvider Provider = Codedomprovider.createprovider ("JScript");        CompilerParameters parameters;        Parameters = new CompilerParameters (); Parameters.        GenerateInMemory = true;        CompilerResults results;        Results = provider.compileassemblyfromsource (parameters, _jscriptsource); AssembLY assembly = results.compiledassembly; _evaluatortype = assembly.        GetType ("Evaluator");    _evaluator = Activator.CreateInstance (_evaluatortype);    } private static Object _evaluator = NULL;    private static Type _evaluatortype = null;        /**///<summary>//JScript code//</summary> private static readonly string _jscriptsource =                      @ "class Evaluator {public Function Eval (expr:string): String {                   return eval (expr); }              }";}

The second step, build up two eval we need to identify in the program those are C #, those are JavaScript code broken

Here I deal with the method is: <c ... Code/> and <j ... The code/> uses these two methods to identify the type of code separately

And then in the process we just need to find out that those are C codes, those are J codes, and the code breaks.

       public void Exportdoc () {exportreplace ();            foreach (Nodetemplate temp in doctemplatelist) {Exportdoc (temp);            } if (Actionobject! = null) {//Dynamic value exportdymic (); }}//define C-expression System.Text.RegularExpressions.Regex Regexc = new System.Text.RegularExpressions.Regex (@        "\<c\w*\|\w*[\,\w*]*\\\>"); Defines the J-expression System.Text.RegularExpressions.Regex regexj = new System.Text.RegularExpressions.Regex (@ "\<j^\>*\\\&        gt; "); The business logic theory is to process the C in Process J first, but C and J by the existence of the cyclic process public void exportdymic () {var matchess = regexc.matches (DOC.G            Ettext ()); foreach (System.Text.RegularExpressions.Match matchc in matchess) {string Cstring = Matchc.valu E.replace ("<c", "").                Replace ("\\>", "" ");                string result = Ceval (Cstring); Cshrapeval.eval (Cstring, ThiS.gettype (), this).                ToString ();                A = A.replace (Matchc.value, result); Doc.            Range.replace (Matchc.value, result, false, false); } matchess = Regexj.matches (Doc.            GetText ()); foreach (System.Text.RegularExpressions.Match matchc in matchess) {string jstring = Matchc.valu E.replace ("<j", "").                Replace ("\\>", "" "); string result = Javaeval.eval (jstring).                ToString (); Doc.            Range.replace (Matchc.value, result, false, false);            }} public string Ceval (string A) {var matchess = regexc.matches (A); foreach (System.Text.RegularExpressions.Match matchc in matchess) {string Cstring = Matchc.valu E.replace ("<c", "").                Replace ("\\>", "" "); string result = Ceval (Cstring).                ToString ();            A = A.replace (Matchc.value, result); } matchess = Regexj.matches (A);            foreach (System.Text.RegularExpressions.Match matchc in matchess) {string jstring = MatchC.Value.Replace ("<j", "").                Replace ("\\>", "" "); string result = Jeval (jstring).                ToString ();            A = A.replace (Matchc.value, result); } return Cshrapeval.eval (A, Actionobject.gettype (), Actionobject).        ToString ();            public string Jeval (string a) {var matchess = regexc.matches (A); foreach (System.Text.RegularExpressions.Match matchc in matchess) {string Cstring = Matchc.valu E.replace ("<c", "").                Replace ("\\>", "" "); string result = Ceval (Cstring).                ToString ();            A = A.replace (Matchc.value, result);            } matchess = Regexj.matches (A); foreach (System.Text.RegularExpressions.Match matchc in matchess) {string jstring = Matchc.valu E.replace ("<j", ""). REplace ("\\>", "" "); string result = Jeval (jstring).                ToString ();            A = A.replace (Matchc.value, result); } return Javaeval.eval (A).        ToString (); }

  

This can be accurate interpretation of the expression, of course, there are still some not considered the complete place, waiting for you to show the master guidance.

OK ~ Today is posted here, later to see the extent of being sprayed to determine whether to continue to send some logs in the blog park

About dynamic values in templates---Reflection and JavaScript script compilation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.