.NET 动态脚本语言Script.NET系列文章汇总 非常精彩的应用举例
對(duì)于Script.NET,我已經(jīng)寫(xiě)了三篇文章來(lái)介紹它,文章匯總?cè)缦?/p>
.NET 動(dòng)態(tài)腳本語(yǔ)言Script.NET 入門(mén)指南 Quick Start
.NET 動(dòng)態(tài)腳本語(yǔ)言Script.NET 開(kāi)發(fā)指南
.NET 動(dòng)態(tài)腳本語(yǔ)言Script.NET 應(yīng)用舉例
希望這三篇文章能幫助你了解Script.NET。 下面的例子,繼續(xù)講解它的應(yīng)用。
?
發(fā)送郵件 Send Email
mailObj = new MailMessage("lsh2011@163.com", "JamesLi2015@hotmail.com","From Script.NET", "Body"); SMTPServer = new SmtpClient("smtp.163.com"); NTLMAuthentication = new System.Net.NetworkCredential("lsh2011@163.com", "password"); SMTPServer.UseDefaultCredentials = false; SMTPServer.Credentials = NTLMAuthentication; try {SMTPServer.Send(mailObj); } catch (ex) { Console.WriteLine(ex.Message); } finally { } ?生成PDF文檔 Generate PDF Document
對(duì)于PDF文件的操作,選擇開(kāi)源的iText library類(lèi)庫(kù)。腳本代碼如下所示
//Create document at given location BeginDocument(“c:\\output.pdf”);//Change title in documentв’s meta dataВ 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();生成PDF的應(yīng)用,它的原文是《Using S# to generate PDF documents》,請(qǐng)找到這篇文章并下載代碼體會(huì)。
通過(guò)這個(gè)例子,你也可以用它來(lái)生成Word/Excel文件。也許,一個(gè)動(dòng)態(tài)生成文件的系統(tǒng)的方案產(chǎn)生于你的腦海中,根據(jù)用戶選擇的文件類(lèi)型(PDF,DOC,XLS),動(dòng)態(tài)調(diào)用這個(gè)腳本來(lái)生成相應(yīng)類(lèi)型的文件。這里的動(dòng)態(tài)生成是有好處的,你可以不用編譯程序,而只改變這里的腳本代碼,來(lái)適應(yīng)客戶對(duì)文件內(nèi)容格式(比如layout)的更改。
?
外殼命令 Shell Command
來(lái)實(shí)現(xiàn)一個(gè)拷貝文件的copy命令,代碼如下
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;} }有了這個(gè)做基礎(chǔ),你可以實(shí)現(xiàn)這樣的功能:每日構(gòu)建 Daily Build,請(qǐng)參考文章《圖解持續(xù)集成--純命令行實(shí)現(xiàn).Net項(xiàng)目每日構(gòu)建》
也可以做到這樣的功能
原文作者使用的bat/cmd的Windows外殼命令,而這里使用的是Script.NET腳本,可以嵌入到其它應(yīng)用程序中,被應(yīng)用程序啟動(dòng)并執(zhí)行。
?
訪問(wèn)SQL Server數(shù)據(jù)庫(kù)
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 Customers";reader = command.ExecuteReader(); while (reader.Read()) {Console.WriteLine(reader["CompanyName"]+". "+ reader["ContactName"]);} connection.Dispose();這個(gè)例子在前面已經(jīng)舉例過(guò),它可以引深為對(duì)其他數(shù)據(jù)源的操作(MySQL,Oracel…)
?工作流系統(tǒng)中的自定義代碼活動(dòng)
這個(gè)應(yīng)用是我在思考工作流的規(guī)則編輯器時(shí)想到的,請(qǐng)看下圖
我們知道,在自定義的工作流系統(tǒng)中,CodeActivity是最有價(jià)值的活動(dòng),可以做任何想做的事情,但也非常不好用。因?yàn)楣ぷ髁鞯挠脩?#xff0c;不是做編程的,不懂C#.NET,所以,你不能指望他會(huì)改變這一點(diǎn)。Script.NET則彌補(bǔ)了這個(gè)缺陷,可以讓工作流設(shè)計(jì)人員,在我的腳本編輯環(huán)境中,編輯腳本,給工作流添加靈活的腳本代碼,在執(zhí)行時(shí),由Script.NET解析引擎執(zhí)行。只要腳本編輯環(huán)境足夠智能靈活,提供的Script Sample足夠多,這個(gè)CodeActivity(應(yīng)該改名叫ScriptActivity)為增加自定義的工作流系統(tǒng)的靈活性,發(fā)揮極大的作用。
? ?自動(dòng)化操作? Windows Automation
要達(dá)到這個(gè)功能,要參考Windows Automation API,請(qǐng)參考這里this article。
先來(lái)看一下應(yīng)用的腳本是什么樣子的,再來(lái)看實(shí)現(xiàn)原理
// 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 As”); // 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 As”); 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″);這是在做什么,打開(kāi)Notepad,在里面輸入文字,最后保存文件,全部的實(shí)現(xiàn)都是用腳本來(lái)做的。這令我想到了自動(dòng)化測(cè)試,UI自動(dòng)化測(cè)試。確實(shí)是這樣的,自動(dòng)化的腳本代替了人工操作,完全不需要人為干預(yù)。
這個(gè)應(yīng)用的原文是《Windows Automation: Automating Windows 7 Notepad within S# Script》。
?
動(dòng)態(tài)窗體? Dynamic Silverlight Forms. Embedding S# Scripts into Xaml
對(duì)于Silverlight技術(shù)不熟悉,請(qǐng)用文章原文查看具體內(nèi)容。我能理解到意思是,可以把以腳本的方式創(chuàng)建窗體,這樣的窗體是動(dòng)態(tài)的,而不編譯時(shí)就寫(xiě)死的,自然是非常靈活的方法。
?
推薦一個(gè)小技巧,我想把Script.NET的腳本,像對(duì)待外殼命令一樣,雙擊執(zhí)行,或是右鍵點(diǎn)擊執(zhí)行,如下面的效果所示
先把Script.NET的原代碼中的RunTests程序改造成可以接受一個(gè)文件參數(shù)的可執(zhí)行文件,像這樣
它的原來(lái)的用法是這樣:Usage: RunTests.exe folderPath
改成這樣的用法 Usage:? RunTests.exe? scriptFile
這樣的用意是,讓它接受一個(gè)Script.NET腳本文件名,并能執(zhí)行它。
再到外殼中注冊(cè)文件關(guān)聯(lián),比如我把Script.NET的文件擴(kuò)展名定義為spt文件,并添加這樣的注冊(cè)表項(xiàng)
Windows Registry Editor Version 5.00
[-HKEY_CLASSES_ROOT\SystemFileAssociations\.spt\shell\RunTests]
這樣就在外殼命令中關(guān)聯(lián)了Script.NET的腳本文件spt和它的執(zhí)行程序RunTests,達(dá)到可以像bat文件一樣,雙擊執(zhí)行。
?
總結(jié):本質(zhì)上,Script.NET的腳本運(yùn)行還是解析為DotNet代碼的執(zhí)行,所以不必懷疑它能做什么,.NET能實(shí)現(xiàn)的功能,都能做到。問(wèn)題是我們是否需要這樣的動(dòng)態(tài)腳本,來(lái)增強(qiáng)程序的可擴(kuò)展性,靈活性,這取決于你,it is up to you。
轉(zhuǎn)載于:https://www.cnblogs.com/JamesLi2015/archive/2011/09/21/2183072.html
總結(jié)
以上是生活随笔為你收集整理的.NET 动态脚本语言Script.NET系列文章汇总 非常精彩的应用举例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: bootstrapTable导出exce
- 下一篇: Asp.Net文件和文件夹操作大全