. NET Dynamic scripting language script. Net Development Guide

Source: Internet
Author: User
Tags net regex

Previous ArticleArticleThis article introduces the basic knowledge of the. NET Dynamic scripting language script. Net Getting Started Guide quick start.

Script. Net IDE environment

Previously mentioned method for writing script. Net scripts, which is written in Visual StudioCodeAnd then run the code in the form of debugging. This method is suitable for the use of Visual Studio's powerful debugging functions to find problems only when you are not familiar with script. Net or encounter an incomprehensible error. Script. Net also takes into account the development script environment and provides an IDE.

Syntax highlighting, parsing and running scripts, and outputting results to the output window. This is enough for daily Script Development.

If you can configure the. NET Framework smart prompt for it, it will be more perfect.

 

Contract Contract

Script. net is a dynamic language. Similar to Javascript, which is often used in web development, dynamic language does not need to specify the type of the variable during definition, but instead allocates the type according to the value at runtime.

First introduce the Exception Handling of script. net. The basic structure is the same as that of. net.

 
Try{......}Catch(E ){......}Finally{......}

Let's look at the dynamic language example. by teaching the following two examples, we can help understand its "dynamic" meaning.

Let's change the parameters and call method Inc. The code is like this.

 
Function Inc (a) {A = a + 1;ReturnA;} console. writeline (INC ('Abc'));

The output result in the output window is ABC1. This example explains the main differences between dynamic languages and determines the type at runtime.

If you want function Inc to only accept int type variables, you need to process them like this.

Function Inc (a) [pre (Is Int); Post (); invariant ();] {A = a + 1;ReturnA;} console. writeline (INC (10 ));

If console. writeline (INC ('Abc'). If you call the INC function with contract added, a script exception is thrown.

This is the role of the Contract. Its complete definition is as follows: add three expressions before the body of the Function Definition body.

 
[Pre (expression); Post (expression); invariant (expression);]

Let's look at the post processing in contract. Let's look at the following script.

Function Inc (a) [pre (Is Int); Post (A <5); invariant ();] {A = a + 1;ReturnA ;}Try{Console. writeline (INC (10 ));}Catch(E) {console. writeline (E );}Finally{}

When F5 runs the code, the output window displays the post condition for function call failed exception.

If it is called with Inc (3), no exception is thrown. In this example, we can understand that pre can be used to constrain parameter types, and post can constrain function return results.

 

Use scripts to create. Net Applications Program

As mentioned in the previous section, the script can reference the host variable and operate on it. The host can also obtain the running results of the script. Replace the scenario with the Form in winforms, which is easy to implement as shown in the following application.

Pass the current form mainform into the script. The script can operate the input variable form and set the text attribute.

 

. Net integration. Net Integration

Script. Net can use the existing types of. NET Framework to provide the types required in most cases.

Sin = math. sin; console. writeline (sin (0.75); console. writeline (datetime. Now); A ='1, 2, 3, 4'; Array = RegEx. Split (,',');Foreach(InArray) console. writeline ();

The. NET RegEx type does not require using.

Like the above RegEx. Split is a static method. If it is a real example method, you can use the using command to simplify the script. Net script code.

 
Using(Math ){// Build-in objects // Using the POW function from math classA = POW (2, 3); console. writeline ();}

 

Script. Net has three built-in functions,

Eval-evaluate the expression value and return (evaluates value of an expression). Example A = eval ('2 + 3*4 ');

Clear-Clear the context variable (clears all variables in context), out of date

Array-create an array (creates typed array of objects)

 

If you need to extend the built-in functions of script. net, refer to this example.

 Class Program { Static   Void Main ( String [] ARGs) {runtimehost. initialize (); Script script = script. Compile ( @ "Return Inc (10 );" ); Script. Context. setitem ( "Inc" , New Incrementfunction ()); Object Result = script. Execute (); console. writeline (result); console. Readline ();}} Public   Class Incrementfunction: iinvokable { Public   Bool Caninvoke (){ Return   True ;} Public   Object Invoke (iscriptcontext context, Object [] ARGs ){ Int OBJ = convert. toint32 (ARGs [0]); Return ++ OBJ ;}}

After calculation, the result is 11. After such processing, you can call the INC function directly.

 

No Dynamic Language, instead of dynamic compilation

I want to give an example of the benefits and usage of the script. NET Dynamic language so that its value can be reflected.

When I judge a workflow expression statement, there is such a piece of code

Salesorder order = New Salesorder ( "Oe0913" , 100); rule DR =New Rule ( "This. orderno = \" oe0913 \"" , "Rule1" , New Statement [] { New Assignment ( "This. Failed" , "True" ),}, New Statement [0]); parser = New Parser (); parser. Fields. Add ( "_ Orderno" ); Parser. Fields. Add ("_ Failed" ); Ruleset DRS = New Ruleset (); Drs. ruletypes. Add ( New Ruletypeset ( Typeof (Salesorder ), New Rule [] {Dr}); Drs. eval (parser ); Bool Pass = order. failed; Drs. runrules (order); pass = order. failed;

It indicates a conditional statement.

If orderno = 'oe0913'

Then failed = true;

The above. Net code is the. NET encapsulation of this rule statement.

The workflow engine accepts a variable to represent the current object, such as salesorder. I defined an if else statement block in the Code. When orderno is oe0913, it runs the statement this. failed = true; otherwise, skip this step. Then, add two environment variables _ orderno and _ failed to the parser and reference the above rules. For the first time, the value obtained is order. failed. This value is directly transmitted by the engine. runrules (Order) will pass in the object salesorder ("oe0913", 100) and run the rule because it complies with the rule this. orderno = 'oe0913 '. If the condition is met, run the statement this. failed = true, pass = order obtained in the last sentence. failed is the value after the engine operation. The Code is the unit test code of the custom rule editor in my workflow engine, which can help you understand.

Sorry, if you cannot understand this example, please refer to the document "informatization infrastructure workflow development" or implement a workflow custom rule editor, you should be able to understand the meaning of the Code. It is quite difficult to implement an if else condition without a dynamic language.

 

Code snippet

After you are familiar with the BASIC script. Net syntax, you may need the following code snippets as a reference to implement your own script logic.

For statement

 
Z = 0;For(I = 0; I <10; I ++) {z + = 2 ;}

Foreach statement 

 
A = [1, 2, 4]; S = 0;Foreach(CInA) {S + = C ;}

Access the SQL Server database

 SQL = dbproviderfactories. getfactory ( "system. data. sqlclient "); connection = SQL. createconnection (); connection. connectionstring =  "Data Source = (local); initial catalog = northwind; Integrated Security = true" ; connection. open (); command = SQL. createcommand (); command. connection = connection; command. commandtext =  "select * from MERs" ; reader = command. executereader ();  while  (reader. read () {console. writeline (Reader [ "companyName" ] +  ". " + reader [" contactname "]);} connection. dispose (); 

Operate Windows Forms

F =NewForm (); F. width = 320; f. Height = 240; f. Text ='Script demo'; F. Show (); G = graphics. fromhwnd (F. Handle );For(I = 0; I <10; I ++) g. drawrectangle (pens. Red,NewRectangle (10 + I * 10, 10 + I * 10,290 -I * 20,180 -I * 20); system. Threading. thread. Sleep (1500 );

Access the network and read RSS aggregation

 
A =NewXmldocument (); A. Load ("Http://protsyk.com/cms? Feed = RSS2 & cat = 10");Foreach(NInA. selectnodes ('/RSS/channel/item') Console. writeline (N ['Title']. Innertext +''+ N ['Link']. Innertext );

Generic Array

 V =  New   int  [10];  for  (I = 0; I 
  
    ''; 
    foreach  (I 
    in  V) S = S + I + 
    ''; A = 
    New  List <| 
    string  |> [10]; A [0] = 
    New  List <| 
    string  |> (); A [0]. add (
    'hello' ); B = A [0]. toarray (); C = B [0]; 
  
 
 

Recursion (Fibonacci, maximum common divisor)

Function fib (n ){If(N = 1)Return1;Else If(N = 2)Return2;Else ReturnFIB (n-1) + fib (n-2 );}
 
Function FAC (n ){If(N = 1)Return1;Else ReturnN * FAC (n-1 );}
 
Function gcd (a, B ){If(A> B)ReturnGcd (A-B, B );ElseIf(B>)ReturnGcd (a, B-);ElseReturnA ;}

 

Dynamic Language

Start with script. NET and. NET Dynamic compilation.Source codeA lot like this. After studying these two articles, I found that it has far exceeded. NET Dynamic compilation capability, from syntax, compilation and processing to the interaction capability between host and script, should be compared with dynamic languages such as iron and python. Although the documents are incomplete, some of them are outdated (obsolete). You can get familiar with and understand it from its unittest project. The example project folder also contains many script examples. The unittest project is both a good tool for unit testing and a document for developers. It is very valuable.

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.