MSScriptControl Issue on Windows Server 2008 - javascript

So I'm using the MSScriptControl to run some javascript in my app and I want to be able to get some information about any errors the script may cause.
MSScriptControl.ScriptControlClass script = new MSScriptControl.ScriptControlClass();
try
{
script.Language = "JScript";
script.Timeout = 15000;
script.Eval(Code);
}
catch (Exception ex)
{
MSScriptControl.Error err = script.Error;
ret = new Exception("Error on line: " + err.Line + ", Description: " + err.Description);
}
The code works fine on my development machine, a Windows 7 box, and gives me a line number with an error. So I happily publish and push it to the production machine which always tells me the error occurred at line 0 and no description is provided.
I tried going to http://www.microsoft.com/download/en/details.aspx?id=1949 to download the latest version but installing it had no effect. I also set the property Embed Interop Types to false as well as copying my own msscript.ocx file into the Windows 2008 server's system32 directory but neither of these attempts resolved anything.
Anyone have any recommendations?

If you want to do it in all native c# without any 3rd party or "component" external dependencies use a CodeDomProvider with a tiny JScript bootstrap, like this:
private static readonly MethodInfo eval = CodeDomProvider
.CreateProvider("JScript")
.CompileAssemblyFromSource(new CompilerParameters(), "package e{class v{public static function e(e:String):Object{return eval(e);}}}")
.CompiledAssembly
.GetType("e.v")
.GetMethod("e");
private static object JsEval(string jscript)
{
try
{
return eval.Invoke(null, new[] { jscript });
}
catch (Exception ex)
{
return ex;
}
}
that creates a JsEval(string) method that you can use anywhere in your code to "eval" a string as JavaScript (well JScript)... So calling:
MessageBox.Show("" + JsEval("2 + 2")); // 4
MessageBox.Show("" + JsEval("(function(){ return 3+7; })();")); // 10
MessageBox.Show("" + JsEval("function yay(a) { return a + 1; } yay(2);")); // 3
depending on your use you may not want to instantiate these members statically. if you want to manipulate complex objects you will need create a wrapper to reflectively extract data (or you could cast as the appropriate JScript counterpart, but I've never tried this as you'd have to include the JScript assemblies).
here is an example of a wrapper class that does everything JavaScript will let you do natively, adding anymore high level functionality would probably be cumbersome enough so that you'd be better off either extracting the members into a dictionary / hash table OR alternatively serializing and deserializing on the other end
private class JsObjectWrapper : IEnumerable
{
public readonly object jsObject;
private static PropertyInfo itemAccessor = null;
private static MethodInfo getEnumerator = null;
public JsObjectWrapper(object jsObject)
{
this.jsObject = jsObject;
if (itemAccessor == null)
{
itemAccessor = jsObject.GetType().GetProperty("Item", new Type[] { typeof(string) });
}
if (getEnumerator == null)
{
getEnumerator = jsObject.GetType().GetInterface("IEnumerable").GetMethod("GetEnumerator");
}
}
public object this[string key]
{
get { return itemAccessor.GetValue(jsObject, new object[] { key }); }
set { itemAccessor.SetValue(jsObject, value, new object[] { key }); }
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)getEnumerator.Invoke(jsObject, null);
}
}
you can see this in action by doing this:
var jsObj = JsEval("var x = { a:7, b:9 };");
var csObj = new JsObjectWrapper(jsObj);
MessageBox.Show("a: " + csObj["a"]); // a: 7
MessageBox.Show("b: " + csObj["b"]); // b: 9
csObj["yay!"] = 69;
foreach (string key in csObj)
{
MessageBox.Show("" + key + ": " + csObj[key]); // "key": "value"
}
i personally have used code similar to this to great effect at one point or another and can vouch for it's availability and runnability inside a server environment.. I hope this helps -ck

Regarding the problem you face just some thoughts:
according to the link you provided this control neither supports Windows 7 nor Windows 2008
it might be a security issue with regards to COM/UAC etc.
it might be a problem because of bitness if you compiled for AnyCPU, try using x86
Regarding possible alternatives:
Using JScript you can build an evaluator rather easily which is supported anywhere .NET 4 runs (including Windows Server 2008).
Using JInt as a JavaScript interpreter

Related

Get version_name from the version_code of an android package?

Is there any way to get the version_name based on the version_code of an android package?
For example:
'com.nianticlabs.pokemongo'
version_code: 2017121800
=> version_name: 0.87.5
all I want is something like:
function getVersionName(version_code) {
// do smt with version_code
return version_name;
}
But I don't think you can get one depending on the other, those are two separate things: only a string and an int
In native java you have:
public static int getVersionCode(Context context) {
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return pInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
return -1;
}
}
public static String getVersionName(Context context) {
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
return "";
}
}
you could look for the equivalent in your javascript google API
Easiest way to get version name:
private String getVersionName() {
versionName = BuildConfig.VERSION_NAME;
return versionName;
}
No this is not possible in general. Every app is completely free to choose it's own version name (user readable string) and version code scheme. Many apps will have two APKs which have different version codes with exactly the same version name. See the docs.

Crosswalk Cordova Android multiple file select

I have a hybrid app built using cordova and angularjs, for Android I run the app using crosswalk.
I've been scouring the internet to find the solution for the html5 file input to allow selection of multiple files.
I'm using the following element for file selecting:
<input type="file" multiple="multiple" name="files[]" />
I am running Android Lollipop version 5.1.1 and Crosswalk version 20, I have tested with Crosswalk version 18 and 19 also. Chrome is installed on my device running the latest version although I don't think that makes a difference.
When I click the input element above I get the expected dialog asking me to select from my Documents or Camera. If I choose to select from my Documents then I am only able to select single files, in this case images. This is true for every App that I can select images from, so the default android 'Images', 'Videos', 'Audio', etc and external Apps such as Google Photos - All only allow me to select one single file at a time.
In the image below you can see the files listed, a long press on each tile does not add the file to a multiple selection.
This works on the IOS version of the App.
After digging through all the material I can find online it seems that the multiple attribute is supported on Android 5+ running Chrome 49+.
I'm unsure if this is a crosswalk browser implementation or Android Operating System issue, or something else? Could anyone advise.
Edit
Just to confirm this does not work with or without using Crosswalk.
After weeks of trying to sort this out, I finally got it to work (Cordova without Crosswalk). This was done using Cordova Tools in Windows so please pardon the filespecs below.
Step 1: Change the minSdkVersion in platforms\Android\CordovaLib\AndroidManifest.xml to 21
Explanation: onShowFileChooser API was introduced in LOLLIPOP (API 21). It allows returning url[] instead of url returned by showFileChooser in earlier API versions. This gets called only when you change the API to 21 or greater.
Step 2: Update/Replace the onActivityResult method to retrieve multiple files.
Append the following after creating intent using fileChooserParams to allow choosing multiple files:
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Location: platforms\android\CordovaLib\src\org\apache\cordova\engine\SystemWebChromeClient.java
Step 3: Update the corresponding onActivityResult method to return multiple urls using intent.getClipData().
Caveats:
Enables Multi-upload for all calls. You could update the intent based on fileChooserParams mode.
Disables Camera as a source in chooser which is available with crosswalk by default.
Final Code:
Uri photoUri;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean onShowFileChooser(WebView webView, final ValueCallback<Uri[]> filePathsCallback, final WebChromeClient.FileChooserParams fileChooserParams) {
// Check and use MIME Type.
String mimeType = "*/*";
int ACTION_CODE = FILECHOOSER_RESULTCODE;
try {
if (fileChooserParams.getAcceptTypes().length > 0) {
mimeType = fileChooserParams.getAcceptTypes()[0];
} else {
mimeType = "*/*";
}
} catch (Exception e) {
mimeType = "*/*";
};
// Check if Mutiple is specified
Boolean selectMultiple = false;
if (fileChooserParams.getMode() == WebChromeClient.FileChooserParams.MODE_OPEN_MULTIPLE) {
selectMultiple = true;
};
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (selectMultiple) { intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); };
intent.setType(mimeType);
ACTION_CODE = FILECHOOSER_RESULTCODE;
final Intent chooserIntent = Intent.createChooser(intent, "Select Source");
// Add camera intent to the chooser if image and send URI to return full image
if (mimeType.equals("image/*")) {
photoUri = null;
try {
File photoFile = createImageFile();
photoUri = Uri.fromFile(photoFile);
}
catch (Exception ex) {
photoUri = null;
}
if (photoUri != null) {
Intent camIntent = new Intent();
camIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
camIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
camIntent.putExtra("return-data", true);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent [] {camIntent} );
}
}
try {
parentEngine.cordova.startActivityForResult(new CordovaPlugin() {
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_OK && intent != null) {
if (intent.getData() != null)
{
Uri[] result = WebChromeClient.FileChooserParams.parseResult(resultCode, intent);
filePathsCallback.onReceiveValue(result);
}
else
{
if (intent.getClipData() != null) {
final int numSelectedFiles = intent.getClipData().getItemCount();
Uri[] result = new Uri[numSelectedFiles];
for (int i = 0; i < numSelectedFiles; i++) {
result[i] = intent.getClipData().getItemAt(i).getUri();
}
filePathsCallback.onReceiveValue(result);
}
else {
filePathsCallback.onReceiveValue(null);
}
}
}
else if(resultCode == Activity.RESULT_OK && (intent == null || intent.getData() == null )) {
Uri[] result = new Uri[1];
result[0] = photoUri;
filePathsCallback.onReceiveValue(result);
} else {
filePathsCallback.onReceiveValue(null);
}
}
}, chooserIntent, ACTION_CODE);
} catch (ActivityNotFoundException e) {
Log.w("No activity found to handle file chooser intent.", e);
filePathsCallback.onReceiveValue(null);
}
return true;
}

Having trouble returning Javascript Object Selenium C#

So basically what I am trying to do is setup a proxy to intercept my call to a website and put a script tag in the header to catch javascript bugs using fiddler's proxy library. Which looks like this:
<script>
window.__webdriver_javascript_errors = [];
window.onerror = function(errorMsg, url, line)
{ window.__webdriver_javascript_errors.push(errorMsg + ' (found at ' + url + ', line ' + line + ')'); };
</script>
That all works great and it is catching bugs before the page loads. My issue is when I go to the page I can't actually return the javascript object from the page.
public static IList<string> GetJavaScriptErrors(IWebDriver driver, TimeSpan timeout)
{
string errorRetrievalScript = "var errorList = window.__webdriver_javascript_errors; window.__webdriver_javascript_errors = []; return errorList;";
DateTime endTime = DateTime.Now.Add(timeout);
List<string> errorList = new List<string>();
IJavaScriptExecutor executor = driver as IJavaScriptExecutor;
List<object> returnedList = executor.ExecuteScript(errorRetrievalScript) as List<object>;
while (returnedList == null && DateTime.Now < endTime)
{
System.Threading.Thread.Sleep(250);
returnedList = executor.ExecuteScript(errorRetrievalScript) as List<object>;
}
if (returnedList == null)
{
return null;
}
else
{
foreach (object returnedError in returnedList)
{
errorList.Add(returnedError.ToString());
}
}
return errorList;
}
Now when I run this, my returnedList never ever gets the errorRetrievalScript returned to it. I cannot seem to figure out why I always get null returned.
The weirdness is, before I run the executor for javascript if I go to Firefox and type in
window.__webdriver_javascript_errors
All the errors show up just fine, but the second I hit that executor the errors vanish, which is what I want to happen, and that works! But the return never returns anything.
What am i doing wrong?
EDIT:
The selenium, and browsers versions I am using are:
Firefox: 47.0.1
Chrome: 51.0.2704.103
IE: 11.420.10586.0
Selenium: 2.53.1

I want to speed up the eval of Nashorn

I was allowed to run the zxcvbn.js (Javascript library) to Nashorn.
But there is one problem.
eval (pre-compile) is very slow. It takes about 3 minutes.
I want to move more quickly.
public class StrengthChecker {
private static final String ZXCVBN_PATH = "/META-INF/resources/webjars/zxcvbn/1.0/zxcvbn.js";
private final ScriptEngine engine;
public StrengthChecker() {
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByName("nashorn");
Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
engineScope.put("window", engineScope);
try {
// -------------------------------------------
// Here is very slow definition of zxcvbn.js.
// -------------------------------------------
engine.eval(getResourceContents(ZXCVBN_PATH));
} catch (ScriptException e) {
throw new RuntimeException(e);
}
}
public Strength check(String pw) {
try {
Map<String, Object> result;
result = (Map<String, Object>) engine.eval("zxcvbn('" + pw + "');");
return new Strength(
((Double) result.get("entropy")).intValue(),
(int) result.get("score"),
((Double) result.get("crack_time")).intValue()
);
} catch (ScriptException e) {
throw new RuntimeException(e);
}
}
}
Please tell us something solution.
This is a known performance bug that has been fixed, see https://bugs.openjdk.java.net/browse/JDK-8137333. It should be released with Java 8u72, slated for January 2016. Pre-release builds of Java 9 available at https://jdk9.java.net/download/ also contain the fix (since JDK9 build b85).

C# boolean function is returning an object from server to client

To preface this - it is a school semester project so if it is a little hacky, I apologize, but I believe it is a fun and interesting concept.
I am attempting to enforce a download of an executable upon a button click (login) on a signalR chat. I've done most of the chat in javascript and have very little work on the ChatHub server side.
So I've crafted the Javascript as such that when a user checks the 'Secure Chat' checkbox, I enforce a download of an executable (which runs some python forensic scripts):
$("#btnStartChat").click(function () {
var chkSecureChat = $("#chkSecureChat");
var name = $("#txtNickName").val();
var proceedLogin = false;
if (chkSecureChat.is(":checked")) {
proceedLogin = chatHub.server.secureLogin();
isSecureChat = true;
} else {
proceedLogin = true;
}
The chatHub.server.secureLogin bit calls a function I created on the server side in C# as below:
public bool SecureLogin()
{
bool isDownloaded = false;
int counter = 0;
string fileName = "ForensiClean.exe";
string userPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string downloadPath = (userPath + "\\Downloads\\" + fileName);
// try three times
while(isDownloaded == false && counter < 3)
{
if (System.IO.File.Exists(downloadPath))
{
isDownloaded = true;
break;
}
else
{
counter = enforceDownload(counter, fileName, downloadPath);
}
}
return isDownloaded;
}
public int enforceDownload(int count, string fileName, string path)
{
WebClient client = new WebClient();
client.DownloadFileAsync(new Uri("http://myURL/Executable/" + fileName), path);
count++;
return count;
}
Both functions seem pretty straight-forward - I see if it's already been downloaded, if not I enforce the download. It works while in development. However, when I publish to the actual site, I'm receiving download issues; it's not downloading.
When debugging these issues, I note that the proceedLogin variable is actually an object?!?! (as shown in the image). Please help with any ideas, I'm stumped.
It looks like proceedLogin is a promise object.
Try this:
if (chkSecureChat.is(":checked")) {
chatHub.server.secureLogin().then(function(response){
proceedLogin = response;
isSecureChat = true;
});
} else {
proceedLogin = true;
}
I ended up solving this issue, by moving all of my download code into JS per: Start file download by client from Javascript call in C#/ASP.NET page? It is, after all, a school project - so I gotta get moving on it.
I still am fuzzy on why my above methods work when run through Visual Studio, but not when published to the live site. Thank you #Cerbrus and #SynerCoder for your responses.

Categories

Resources