dynamically evaluating javascript expressions in winrt/xaml/c# applications - c#

Is there a way of evaluating javascript expressions, which are loaded from an external source at runtime, in a winrt application written in XAML and c#?
Consider the following pseudo-code:
String expression = File.ReadAll(somefile);
String result = AnyJavascriptEngineAvailableUnderWinRT.Evaluate(expression);
before winrt, we have been using Microsoft.JScript engine.
Now, with winrt, we have been trying Jint, which led to runtime exception "The API 'System.Type.ReflectionOnlyGetType(System.String, Boolean, Boolean)' cannot be used on the current platform. See http://go.microsoft.com/fwlink/?LinkId=248273 for more information."
To be honest, I would prefer addressing the built-in javascript engine coming with winrt, but I would also accept "AnyJavascriptEngineAvailableUnderWinRT", if it allows expressions to be evaluated dynamically.

You can do this easily by tapping into IE directly through the WebView.
Like this:
var js = "whatever you want";
var webView = new WebView();
var result = webView.InvokeScript("eval", new[] { js });
Best of luck!

Related

Is the text templating feature in .netcore logging available for use in our code?

.netcore logger supports a text templating feature that is different than string interpolation.
For example, the following call:
_logger.LogInformation("About page visited at {DT}",DateTime.UtcNow.ToLongTimeString());
... replaces {DT} with a date.
Is this templating capability a special feature in the .netcore logging or a new C# feature?
If it is only implemented in .netcore logging, can I re-use it in my code string processing operation?
Update 1
You cannot use the string with text template like what logging do.
You could use String.Format like below as a alternative way:
string s = string. Format("About page visited at {0}", DateTime.UtcNow.ToLongTimeString());
Reference: get started with the String.Format method
Or you can use in this way:
var time = DateTime.UtcNow.ToLongTimeString();
string s = $"About page visited at {time}";

How can one syntax highlight and format GraphQL queries on an HTML page with C# on .NET Core / Blazor?

Basically what the title says; I would like to syntax highlight aka colourize the GraphQL queries like they do it in the "GraphiQL Explorer", and print it on an HTML page with .NET Core using C#. Im working with Blazor, so the pages are .razor.
See this screenshot:
And I also want to auto-format the queries so that the queries aren't on a single line, but with line-breaks and indentations as the button "prettify" does in the "GraphiQL explorer".
So here's a sample.
Convert this => {human(id: "1000") {name height(unit: FOOT)}}
to this =>
Edit:
Here's a blazorFiddle i created. BlazorFiddleSample
Basically format\indent the graphql queries in a component page like this converter does, freetooldev
This could be achieved using BlazorMonaco
https://github.com/serdarciplak/BlazorMonaco
the code setup should look like this for the options
private StandaloneEditorConstructionOptions EditorConstructionOptions(MonacoEditor editor)
{
return new StandaloneEditorConstructionOptions
{
AutomaticLayout = true,
Language = "graphql",
};
}
please follow the instructions to get it setup if this is something you want to try.
you can get more info on the use of Monaco Editor here:
https://microsoft.github.io/monaco-editor/

Using Javascript for Google Maps API from WPF

I am creating an application that interfaces with Google's Maps API v3. My current approach is using a WebBrowser control by WebBrowser.Navigate("Map.html"). This is working correctly at the moment; however, I am also aware of WebBrowser.InvokeScript(). I have seen this used to execute a javascript function, but I would like to have something like the following structure:
APICalls.js - Contains different functions that can be called, or even separated out into a file for each function if necessary.
MapInterface.cs
WebBrowser.InvokeScript("APICalls.js", args) - Or control the javascript variables directly.
I have seen the InvokeScript method used, but none of the examples gave any detail to the source of the function, so I'm not sure if it was calling it from an html file or js file. Is it possible to have a structure like this, or a similarly organized structure, rather than creating an html file with javascript in each one and using Navigate()?
Additionally, are there any easier ways to use Google Maps with WPF. I checked around, but all of the resources I found were at least 2-3 years old, which I believe is older than the newest version of the maps API.
I can't suggest a better way of using Google Maps API with WPF (although I'm sure it exists), but I can try to answer the rest of the question.
First, make sure to enable FEATURE_BROWSER_EMULATION for your WebBrowser app, so Google Maps API recognizes is it as modern HTML5-capable browser.
Then, navigate to your "Map.html" page and let it finish loading. Here's how it can be done using async/await (the code is for the WinForms version of WebBrowser control, but the concept remains the same).
You can have your APICalls.js as a separate local file, but you'd need to create and populate a <script> element for it from C#. You do it once for the session.
Example:
var scriptText = File.ReadAllText("APICalls.js");
dynamic htmlDocument = webBrowser.Document;
var script = htmlDocument.createElement("script");
script.type = "text/javascript";
script.appendChild(htmlDocument.createTextNode(scriptText));
htmlDocument.body.appendChild(script);
Then you can call functions from this script in a few different ways.
For example, your JavaScript entry point function in APICalls.js may look like this:
(function() {
window.callMeFromCsharp = function(arg1, arg2) {
window.alert(arg1 + ", " +arg2);
}
})();
Which you could call from C# like this:
webBrowser.InvokeScript("callMeFromCsharp", "Hello", "World!");
[UPDATE] If you're looking for a bit more modular or object-oriented approach, you can utilize the dynamic feature of C#. Example:
JavaScript:
(function() {
window.apiObject = function() {
return {
property: "I'm a property",
Method1: function(arg) { alert("I'm method 1, " + arg); },
Method2: function() { return "I'm method 2"; }
};
}
})();
C#:
dynamic apiObject = webBrowser.InvokeScript("apiObject");
string property = apiObject.property;
MessageBox.Show(property);
apiObject.Method1("Hello!");
MessageBox.Show(apiObject.Method2());

emulating a browser programmatically in C# / .Net

We would like to automate certain tasks in a website, like having a user 'login', perform some functionality, read their account history etc.
We have tried emulating this with normal POST/GETs, however the problem is that for example for 'login', the website uses javascript code to execute an AJAX call, and also generate some random tokens.
Is it possible to literally emulate a web-browser? For example:
Visit 'www.[test-website].com'
Fill in these DOM items
DOM item 'username' fill in with 'testuser'
DOM item 'password' fill in with 'testpass'
Click' button DOM item 'btnSubmit'
Visit account history
Read HTML (So we can parse information about each distinct history item)
...
The above could be translated into say the below sample code:
var browser = new Browser();
var pageHomepage = browser.Load("www.test-domain.com");
pageHomepage.DOM.GetField("username").SetValue("testUser");
pageHomepage.DOM.GetField("password").SetValue("testPass");
pageHomepage.DOM.GetField("btnSubmit").Click();
var pageAccountHistory = browser.Load("www.test-domain.com/account-history/");
var html = pageAccountHistory.GetHtml();
var historyItems = parseHistoryItems(html);
You could use for example Selenium in C#. There is a good tutorial: Data Driven Testing Using Selenium (webdriver) in C#.
I would suggest to instantiate a WebBrowser control in code and do all your work with this instance but never show it on any form. I've done this several times and it works pretty good. The only flaw is that it makes use of the Internet Explorer ;-)
Try JMeter, it is a nice too for automating web requests, also quite popularly used for performance testing of web sites
Or just try System.Windows.Forms.WebBrowser, for example:
this.webBrowser1.Navigate("http://games.powernet.com.ru/login");
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
System.Windows.Forms.Application.DoEvents();
HtmlDocument doc = webBrowser1.Document;
HtmlElement elem1 = doc.GetElementById("login");
elem1.Focus();
elem1.InnerText = "login";
HtmlElement elem2 = doc.GetElementById("pass");
elem2.Focus();
elem2.InnerText = "pass";

Parse JavaScript code in C#

I have the following JavaScript code as a string literal:
var $Page = new function()
{
var _url= 'http://www.some.url.com';
this.Download = function()
{
window.location = _url;
}
}
Is there a way I could get the value of the _url variable from my C# code? An open source library perhaps? I did this using a Regular Expression, but I was hoping for a more elegant way.
You should take a look at the open-source Javascript .NET (http://javascriptdotnet.codeplex.com/) on Codeplex.
This sample of code should help you:
Javascript context = new JavascriptContext();
context.Run("var _url= 'http://www.some.url.com';") // You put your javascript in the function run
String url = (String)context.GetParameter("_url"); // You get your url from javascript
That's it.
There is an open-source JavaScript interpreter in C# at http://jint.codeplex.com, if you need more than just getting the value.
This is now moved to GITHUB
You could execute the javascript function using the DLR and/or MyJScript.
You could use a javascript parser, but parsing javascript for just that one value is probably way overkill.

Categories

Resources