Embedding Chakra Javascript Engine in Windows 8 / .Net 4.5 - javascript

Given the rise of Javascript in Windows 8, does Windows 8 / .Net 4.5 / VS 2012 provide a mechanism to embed the Chakra javascript engine in application to enable scripting? If so, is there documentation for this somewhere?

There is no mechanism to do this that has been released or talked about. For now, it is available only in IE and to Metro style apps. There isn't even a Windows Scripting Host style exposure of it.
What is it about Chakra that you want in your scripting?

Doesn't IE ActiveX use the same JavaScript engine as IE standalone?
You can simply embed Internet Explorer ActiveX frame and keep it hidden.

Yes, exists.
See: https://github.com/Microsoft/ChakraCore/wiki/Embedding-ChakraCore
using System;
using System.Runtime.InteropServices;
using ChakraHost.Hosting;
public class HelloWorld
{
static void Main() {
JavaScriptRuntime runtime;
JavaScriptContext context;
JavaScriptSourceContext currentSourceContext = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero);
JavaScriptValue result;
// Your script, try replace the basic hello world with something else
string script = "(()=>{return \'Hello world!\';})()";
// Create a runtime.
Native.JsCreateRuntime(JavaScriptRuntimeAttributes.None, null, out runtime);
// Create an execution context.
Native.JsCreateContext(runtime, out context);
// Now set the execution context as being the current one on this thread.
Native.JsSetCurrentContext(context);
// Run the script.
Native.JsRunScript(script, currentSourceContext++, "", out result);
// Convert your script result to String in JavaScript; redundant if your script returns a String
JavaScriptValue resultJSString;
Native.JsConvertValueToString(result, out resultJSString);
// Project script result in JS back to C#.
IntPtr resultPtr;
UIntPtr stringLength;
Native.JsStringToPointer(resultJSString, out resultPtr, out stringLength);
string resultString = Marshal.PtrToStringUni(resultPtr);
Console.WriteLine(resultString);
Console.ReadLine();
// Dispose runtime
Native.JsSetCurrentContext(JavaScriptContext.Invalid);
Native.JsDisposeRuntime(runtime);
}
}

Related

Microsoft Visual Foxpro DLL call in Node or Java

I'm new to Visual Foxpro. I want to build a dynamic link library (dll) file using Visual Foxpro for calling the Visual Foxpro function in Node or Java to build rest API.
I tried it with Node and Java. I had an issue when I used the Foxpro dll file. So I created a C# dll, and got the same issue. So then I read a document which said to use > [DLLEXPORT] tag above the function which I want to call in another native language.
I built a 32-bit and 64-bit dll to use with my native language code. It was successful. My question is that I want to build both 32-bit and 64-bit dll files with Visual Foxpro to use with Node.js code.
This is my C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using net.r_eg.DllExport;
namespace FDLL
{
public class First
{
[DllExport]
public static String getData()
{
Console.Write("Call Function Successfully!");
return "HI Welcome";
}
}
[DllExport]
public static String getData1(String a)
{
Console.Write("Call Function Successfully!");
return "HI Welcome"+ a;
}
}
If I did not use [DllExport] tag, getData could not be invoked in my Node or java code.
This is my Node.js code:
const ffi = require("#saleae/ffi");
const libm = ffi.Library("./FDLL", {
getData: ["string", []],
getData1: ["string", ["string"]]
});
It works fine, but my Foxpro dll is not working.
This is my Visual Foxpro code:
This is the JavaScript code for accessing my Foxpro GetDrugsJSON() function
var libm1 = ffi.Library("./cw/comdemo", {
GetDrugsJSON: ["String", []],
});
console.log(libm1.GetDrugsJSON())
But I cannot invoke GetDrugsJSON() function with JavaScript code.
How do I fix this issue?
Long story short, you cannot build 32 and 64 bits DLL with VFP.
Also a DLL is a broad term (while it is short for Dynamic Link Library, there are different DLLs).
You are saying "in Node or Java to build rest API". For creating REST API you wouldn't want to use VFP. Use something else, be it C#, Go, ...
With other languages too, if you are accessing VFP data via VFPOLEDB then it needs to be 32 bits.

Open a Browser Window with Javascript on Xamarin.Forms

I have a Xamarin.Forms app. It includes a button like this:
<Button x:Name="Buy_Button" Text="Satın Al" FontAttributes="Bold" TextColor="#e2e2e2" BackgroundColor="#2A52BE" FontFamily="Segoe UI" Grid.Column="2" Grid.ColumnSpan="1" Grid.RowSpan="1" CornerRadius="5" VerticalOptions="Start" HorizontalOptions="Center" FontSize="15.667" Grid.Row="0" Margin="0,10,10,0" Clicked="Buy_Button_ClickedAsync" CommandParameter="{Binding Buy_URL}" />
I'm sending a URL link to click event for opening specific web page. Code is:
private async void Buy_Button_ClickedAsync(object sender, EventArgs e)
{
Button btn = (Button)sender; // Coming button from click event handler.
var buylink = btn.CommandParameter.ToString(); // Get the CommandParameter.
// await DisplayAlert("Satın alma linki", buylink, "Anladım"); // Show the link.
try // Uwp & iOS & Android
{
await Browser.OpenAsync(new Uri(buylink), BrowserLaunchMode.SystemPreferred); // Open url in-app browser for iOS & Android- native in UWP
}
catch (NotImplementedInReferenceAssemblyException ex) //Wasm falls here because lack of Xamarin.Essentials.
{
// await DisplayAlert("Hata", ex.Message, "Anladım"); // Show the info about exception.
// Jint - nt is a Javascript interpreter for .NET which provides full ECMA 5.1 compliance and can run on any .NET platform.
//Because it doesn't generate any .NET bytecode nor use the DLR it runs relatively small scripts faster.
//https://github.com/sebastienros/jint
var engine = new Engine();
engine.SetValue("log", new Action<object>(Console.WriteLine));
engine.Execute(#"function openurl() { log('" + buylink + "'); }; openurl(); ");
}
}
In UWP, Xamarin.iOS and Xamarin. Android this code is running via Xamarin.Esssentials:
await Browser.OpenAsync(new Uri(buylink), BrowserLaunchMode.SystemPreferred); // Open url in-app browser for iOS & Android- native in UWP
However, my Xamarin.Forms app projected to WebAssembly code with Uno Platform, so this code block not running. As a result. I install Jint to Xamarin.Forms app. This catch block prints the link to Browser console, but no window.open function track in API reference:
catch (NotImplementedInReferenceAssemblyException ex) //Wasm falls here because lack of Xamarin.Essentials.
{
// await DisplayAlert("Hata", ex.Message, "Anladım"); // Show the info about exception.
// Jint - nt is a Javascript interpreter for .NET which provides full ECMA 5.1 compliance and can run on any .NET platform.
//Because it doesn't generate any .NET bytecode nor use the DLR it runs relatively small scripts faster.
//https://github.com/sebastienros/jint
var engine = new Engine();
engine.SetValue("log", new Action<object>(Console.WriteLine));
engine.Execute(#"function openurl() { log('" + buylink + "'); }; openurl(); ");
}
}
How can I open WebBrowser page on WASM via Javascript form Xamarin.Forms C# code? Thanks.
2 things:
1. Use the browser!
On Wasm, you're running in a webassembly environment, which is running in a javascript virtual machine (that's not totally accurate, but close enough for my point). That means you can directly invoke the javascript of the running environment (browser).
Making a call to native javascript...
WebAssemblyRuntime
.InvokeJS("(function(){location.href=\"https://www.wikipedia.com/\";})();");
In your case, since you want to open a browser window, it's required to use this approach, because Jint can't access anything from the browser itself.
2. You can still call Jint anyway (but not to open a new window)
If you still want to call code using Jint (because you can!!), you need to exclude the Jint.dll assembly from the linking process. Probably because it's using reflection to operate. Again, it won't work to open a window as you're asking, but if you need to call Jint for any other reason, it will work as on other platforms!
Add this to your LinkerConfig.xml (in the Wasm project):
<assembly fullname="Jint" />
Also... You gave me an idea and I did something cool with Jint...
I put the entire solution there: https://github.com/carldebilly/TestJint
It works, even on Wasm:
Interesting code:
https://github.com/carldebilly/TestJint/blob/master/TestJint/TestJint.Shared/MainPage.xaml.cs#L18-L40
private void BtnClick(object sender, RoutedEventArgs e)
{
void Log(object o)
{
output.Text = o?.ToString() ?? "<null>";
}
var engine = new Engine()
.SetValue("log", new Action<object>(Log));
engine.Execute(#"
function hello() {
log('Hello World ' + new Date());
};
hello();
");
#if __WASM__
output2.Text =
WebAssemblyRuntime.InvokeJS("(function(){return 'Hello World ' + new Date();})();");
#else
output2.Text = "Not supported on this platform.";
#endif
}
Final Note
On UWP/WinUI XAML, you can directly put a <Hyperlink /> in your XAML. I'm not familiar enough with Xamarin Forms to know if there's an equivalent.
I am using Device.OpenUri and it works in WASM with Xamarin.Forms
Device.OpenUri(new Uri("https://www.bing.com"));

MATLAB as COM Automation Server with Javascript

I am trying to make a connection between Matlab and a Javascript (typescript in my case) program with a COM automation server as suggested on the MathWorks website. The docs on the website have examples for some languages created by MS, not for javascript.
I can't seem to find a lot of information on how to establish such a COM connection with JS. From what I've read, it's an old Microsoft feature that was only used with Internet Explorer.
Problem
The program I am writing is a VS Code extension, thus I am not using Internet Explorer at all. As a result, I do not believe I can use ActiveXObjects.
Question
Is there another way to establish a connection between my typescript code and the Matlab instance?
Goal
I am trying to run Matlab files from the VS Code terminal without opening a custom Matlab terminal or the complete Matlab GUI. The output should be displayed in the VS Code terminal as well. On MacOS and Linux, I can simply use the CLI tools, but due to the differences between the Windows version and MacOS/Linux versions, this is not possible on Windows.
I haven't used TypeScript very much, and what little I did, it was a long time ago when it was completely new.
However, the NPM package win32ole can be used in NodeJS, so I would assume you would be able to use it in Typescript as well (perhaps with some minor modifications to the example, or a small wrapper).
win32ole npm page
This is an example from that page, showing how to interact with Excel to create and save a worksheet.
try{
var win32ole = require('win32ole');
// var xl = new ActiveXObject('Excel.Application'); // You may write it as:
var xl = win32ole.client.Dispatch('Excel.Application');
xl.Visible = true;
var book = xl.Workbooks.Add();
var sheet = book.Worksheets(1);
try{
sheet.Name = 'sheetnameA utf8';
sheet.Cells(1, 2).Value = 'test utf8';
var rg = sheet.Range(sheet.Cells(2, 2), sheet.Cells(4, 4));
rg.RowHeight = 5.18;
rg.ColumnWidth = 0.58;
rg.Interior.ColorIndex = 6; // Yellow
var result = book.SaveAs('testfileutf8.xls');
console.log(result);
}catch(e){
console.log('(exception cached)\n' + e);
}
xl.ScreenUpdating = true;
xl.Workbooks.Close();
xl.Quit();
}catch(e){
console.log('*** exception cached ***\n' + e);
}

How to pass a variable from javascript to objective C and Objective C to Javasctipt in ios

I am a iOS Developer, am new to javascript.
I wants to create a communication between Javascript to Objective C and Objective C to Javascript.
How to pass a variable from javascript to objective C and Objective C to Javasctipt in ios.
If any one have references please let us know about this?
I program JavaScript when using Parse CloudCode. In my case, I use CloudCode to call the Stripe API.
For example:
Objective-C
NSDictionary *parameters = #{
#"customerId": stripeCustomerId,
#"amount": #(100),
};
[PFCloud callFunctionInBackground:#"chargeCustomer" withParameters:parameters block:block];
JavaScript
Parse.Cloud.define("chargeCustomer", function(request, response) {
Stripe.Charges.create({
amount: request.params.amount, // in cents
currency: "usd",
customer: request.params.customerId,
},{
success: function (httpResponse) {
console.log(httpResponse);
response.success(httpResponse);
},
error: function (httpResponse) {
console.error(httpResponse.message);
response.error(httpResponse.message);
}
});
});
As you can see, to pass on the variable from objective-c to javascript in this case, you use request.params.
If you are targeting iOS8, you could consider to use WKWebView rather than UIWebView, which has considerably improved in this regard. Good starting points are the the WKWebView reference docs and this NSHipster article.
You can use native iOS objects to do this.
From Obj-C to JS
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
It injects or calls pre-existing method/object in the page loaded in the UIWebview. It returns the value that JS return to you
UIWebView Class Reference
From JS to Obj-C
Implementing UIWebView protocol you can handle the request before it will start:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest (NSURLRequest *)request navigationType (UIWebViewNavigationType)navigationType
So, from JS you have to call a URL with a custom schema http such as test://. Then you will parse the request in the delegate method I wrote before.

How to call COM object function from classic ASP

In my classic ASP site I need to call COM object function.
Here is the COM component definition:
interface IMyComponent : IDispatch
{
HRESULT GetVersion([in] int, [out] double*, [out] BSTR*);
}
In server side I create component object and try to call 'GetVersion' function:
<%
Dim app
Set app = CreateObject("MyComponent")
Dim someUsefulValue
Dim version
app.GetVersion 1, someUsefulValue, version
%>
But this code fails with error "Type mismatch".
How I should call this function?
first of all, keep in mind that no other browser supports ActiveX rather than Internet Explorer, so I would re-think if you shouldn't get other approach to the problem, maybe using other component that is more open to other browsers...
like Microsoft Silverlight (if you are going the .NET way), Adobe Flash, Shockwave, Air...
in HTML
Your ASP page needs to have the <object> code of your ActiveX
<OBJECT ID="myActiveX "
CLASSID="clsid: yourControlId">
</OBJECT>
then you just act as a normal DOM object
var myActiveX = document.getElementById("myObject");
alert( myActiveX.GetVersion(...) );
Change the type of first parameter of the COM method to long, rather than int. Long translates to the variant type VT_I4, while int translates to VT_INT. If memory serves me right, VBScript doesn't recognize VT_INT as it's not an "automation compatible type" (the size of int may not be fixed across compilers/platforms!)
Try:
<%
Dim app
Set app = Server.CreateObject("MyComponent")
Dim someUsefulValue
Dim version
app.GetVersion 1, someUsefulValue, version
%>
On the server side you should use Server.CreateObject, not just CreateObject as it is normally used for client side VBScript.
Make sure the COM object has been installed and registered using regsvr32 MyComponent.dll

Categories