Simple implementation of C # compatibility with Javascript,

Source: Internet
Author: User

Simple implementation of C # compatibility with Javascript,

This article introduces a newly implemented plug-in for c # interaction with js. The requirement comes from a discussion with a friend. The main dialog is as follows:

Friend: Recently I want to simulate some data to test the interface I have written, but it is too troublesome to manually write the test data.

Myself: Yes, there are a lot of open-source libraries that can generate simulated data in. net. But we have a front-end called Mock. js, which is quite useful.

Friend: Let's talk about it.

Myself: I will talk about the simple application and capabilities of Mock. js. My friends are immediately attracted by my words.

Friend: Do you want

Myself: Here, try it.

Just do it, and I began to look for plug-ins that. net can interact with Js on the Internet. As a front-end, I know that the V8 engine is top-notch in parsing Js performance. I just want to use it. Then I searched and finally found it. This is ClearScript. First, a design drawing:

I. Interface and implementation 1.1 IExecute Interface

This interface mainly implements three methods:

ExecuteNoResult: Execution interface with no return value

Execute: Execute the Js Code and receive the returned value. The second parameter resultKeys serves as a set of variable names in the list of returned values.

1.2 IPlugin Interface

This interface standardizes the methods required by a plug-in to make an object class a plug-in, and defines the plug-in: either he has a life cycle (he needs to manually end his life cycle), or he consumes a lot of resources (he needs to release resources ).

Install: Install a plug-in

UnInstall: UnInstall a plug-in

1.3 Implementation of interfaces

V8Execute implements the V8 engine's ability to execute Js Code, while V8ExecuteThridPart inherits from V8Execute and implements the plug-in interface capabilities that can be used for management. The ResultInfo class serves as the return base class for the execution interface, and the output of Js code can be used by. net programs. In this way, the Js simulation data is returned to. net. The implementation code is as follows:

Public class V8ExecuteForThirdPart: V8Execute, IPlugin {private IList <string> thirdFilePaths; /// <summary> /// construct /// </summary> /// <param name = "thridPart"> </param> public V8ExecuteForThirdPart (string [] thirdPart): this (AppDomain. currentDomain. setupInformation. applicationBase, thirdPart) {} public V8ExecuteForThirdPart (string prefix, string [] thirdPart) {this. thirdFilePaths = new List <string> (); foreach (var part in thirdPart) {this. thirdFilePaths. add (System. IO. path. combine (prefix, part);} public bool Uninstall () {this. dispose (); return true;} public bool Install () {foreach (var file in this. thirdFilePaths) {string code = this. readFile (file); if (string. isNullOrWhiteSpace (code) continue; this. executeNonResult (code);} return true;} private string ReadFile (string fileFullPath) {string txt = System. IO. file. readAllText (fileFullPath, Encoding. UTF8); return txt ;}}
Iii. Test

The implementation code is as follows:

static void Main(string[] args)        {            string[] jsFiles = { "jsLib\\mock.js" };            SAM.Framework.Plugins.IPlugin plugin  = new SAM.JavaScript.V8.V8ExecuteForThirdPart(jsFiles);            SAM.Framework.Javascript.IExecute execute = plugin as SAM.Framework.Javascript.IExecute;            plugin.Install();            SAM.Framework.Javascript.ResultInfo resultInfo = execute.Execute("\r\n var result=Mock.mock('@email')");            resultInfo = execute.Execute("\r\n var result=result");            Console.WriteLine(resultInfo.Content["result"]);            Console.ReadKey();        }

First, load the mock. js file under jsLib. This is loaded in the plugin. Install method called real value, and then Execute the relevant code through the Execute method. When the Execute method is called multiple times, the V8 engine instance references one more. This saves the resource overhead and Concatenates the Execution Code context.

Download the test code. If the Code cannot be compiled,Contact me if necessaryThe main reason is that these dll files are extracted and cannot be run, and a real and available example will be completed later.

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.