I have written three articles about script. net.ArticleTo introduce it. The article is summarized as follows:
Quick Start
. NET Dynamic scripting language script. Net Development Guide
. NET Dynamic scripting language script. NET application example
I hope these three articles will help you understand script. net. In the following example, we will continue to explain its application.
Send email
Mailobj =NewMailmessage (Lsh2011@163.com",JamesLi2015@hotmail.com","From script. Net","Body"); Smtpserver =NewSmtpclient ("Smtp.163.com"); Ntlmauthentication =NewSystem. net. networkcredential (Lsh2011@163.com","Password"); Smtpserver. usedefaultcredentials =False; Smtpserver. Credentials = ntlmauthentication;Try{Smtpserver. Send (mailobj );}Catch(Ex) {console. writeline (ex. Message );}Finally{}
Generate PDF document generate PDF document
For PDF file operations, select the open-source itext Library Class Library. ScriptCodeAs shown below
// create document at given location begindocument ("C: \ outputdocument "); // change title in document processing's meta data processing activedocument. addtitle ('sample document'); // create paragraphs with different alignment and color options paragraph ('Hello world', align_center ); paragraph ('this is demo', align_right, blue); paragraph ('this PDF was generated by S # ', green ); // create a list of string items beginlist (); listitem ('one'); listitem ('two '); listitem ('Three '); endlist (); // create a table with tree columns begintable (3 ); // create cells for the first row cell ('1'); cell ('one '); cell (paragraph ('description of one', red); // create cells for second row cell ('2 ′); cell ('two'); cell ('description of two'); endtable (); // flush and close document enddocument ();
Generate a PDF application. The original document is using S # To generate PDF documents. Please find this article and download the code.
In this example, you can also use it to generate WORD/Excel files. Perhaps, a dynamic file generation system is generated in your mind. Based on the selected file type (PDF, Doc, XLS), you can dynamically call this script to generate corresponding types of files. Dynamic generation here is advantageous. You do not need to compileProgramOnly the script code here is changed to adapt to the change to the file content format (such as layout.
Shell Command
To copy a file. The Code is as follows:
Class Program { Static Void Main ( String [] ARGs) {runtimehost. initialize (); Script script = script. Compile ( @ "Return copy('a.xls ', 'd: \ document ');" ); Script. Context. setitem ( "Copy" , New Copyfunction ()); Object Result = script. Execute (); console. writeline (result); console. Readline ();}} Public Class Copyfunction: iinvokable { Public Bool Caninvoke (){ Return True ;} Public Object Invoke (iscriptcontext context, Object [] ARGs ){ String Sourcefile = convert. tostring (ARGs [0]); String Destintionfolder = convert. tostring (ARGs [1]); If (! Directory. exists (destintionfolder) directory. createdirectory (destintionfolder );String Targetfile = path. Combine (destintionfolder, path. getfilenamewithoutextension (sourcefile) + path. getextension (sourcefile); file. Copy (sourcefile, targetfile ); Return Targetfile ;}}
With this foundation, you can implement this function: Build a daily build every day. Refer to the article graphic continuous integration-implement a. Net project daily build with pure command line.
This function can also be used.
The original article uses the BAT/CMD Windows Shell Command, which uses the script. Net script, which can be embedded into other applications and started and executed by the application.
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 ();
This example has already been used as an example. It can be used to deeply operate other data sources (MySQL, El ...)
Custom Code activity in Workflow System
This application was created when I was thinking about the workflow rule editor. Please refer
We know that codeactivity is the most valuable activity in a custom workflow system and can do anything we want, but it is also very difficult to use. Because the workflow user is not programming and does not understand C #. net, you cannot expect him to change this point. Script. net makes up for this defect, allowing workflow designers to edit scripts in my script editing environment and add flexible script code to the workflow. net parsing engine execution. As long as the script editing environment is intelligent and flexible enough script samples are provided, this codeactivity (which should be renamed scriptactivity) plays a significant role in increasing the flexibility of the custom workflow system.
Automated windows Automation
To achieve this function, refer to Windows Automation API. For more information, see this article.
Let's first look at what the application script looks like, and then look at the implementation principle.
// Close existing instances of notepad Kill ("Notepad "); // Launch a new notepad instance and get Main Window Window = launch ("Notepad "); // Wait 1 second Wait (1000 ); // Get main editor Region Edit = findbyclassname (window, "edit ");// Focus main editor Focuseditor (edit ); // Send sample text to the editor Region Sendkeys. sendwait ("automating notepad Using Windows UI automation and S # "); wait (3000 ); // Find [file] menu Mnufile = findbyid (window, "item 1 ″); // Expand [file] menu Expand (mnufile); wait (1000 ); // Invoke [Save As] menu item Invokebyid (window, "item 4"); wait (1000 ); // Get [Save As] Dialog Saveasdialog = findbyname (window, "Save "); // Get access to [filename] textbox Saveasname = findbyid (saveasdialog "1001 ″); // Focus filename Editor Focuseditor (saveasname ); // Write down file name Sendkeys. sendwait ("d :\\ mytextfile "); // Send [enter] keypress Sendkeys. sendwait ('{enter}'); wait (1000 ); // Check whether overwrite dialog appeared Confirmsaveas = findbyname (saveasdialog, "confirm Save "); If (Confirmsaveas! = Null ){ // Click [OK] button Invokebyid (confirmsaveas, "commandbutton_6"); wait (1000 );} // Expand [file] menu Expand (mnufile); wait (1000 ); // Click [exit] item Invokebyid (window, "Item 7 ″);
What is this? Open notepad, input text in it, and save the file. All implementations are implemented using scripts. This reminds me of automated testing and UI automated testing. Indeed, automated scripts replace manual operations without human intervention.
The original Article of this application is Windows automation: Automatic windows 7 notepad within S # script.
Dynamic form
Dynamic Silverlight forms. Embedding s # scripts into XAML
If you are not familiar with the Silverlight technology, use the original article to view the specific content. I can understand that it is a very flexible method to create a form in the form of a script. Such a form is dynamic without being compiled.
I recommend a tip. I want to double-click the script. Net script like a shell command, or right-click the script, as shown in the following figure.
First, the runtests program in the original script. Net code is transformed into an executable file that can accept a file parameter, like this
Its original usage is as follows: Usage: runtests.exe folderpath
Use usage: runtests.exe scriptfile.
The intention is to make it accept a script. Net script file name and execute it.
Register File Associations in the shell. For example, I define the file extension of script. NET as a SPT file and add such a registry entry.
Windows Registry Editor Version 5.00
[-Hkey_classes_root \ systemfileassociations \. SPT \ shell \ runtests]
In this way, the shell command is associated with the script. Net script file SPT and its execution program runtests, which can be executed by double-clicking like a bat file.
Summary: in essence, the script. Net script is resolved to the DOTNET code execution, so you don't have to worry about what it can do. Net can achieve all the functions. The problem is whether we need such dynamic scripts to enhance program scalability and flexibility. It depends on you, it is up to you.