Execute bat file on client machine through Javascript - javascript

We have a web page which lists our own custom zipped files(stored at cloud).
We want those files to be unzipped the moment user downloads it.
For unzipping process we have provided a console app to user which will be stored at a known location(say C:/ProgramFiles/Company/UnZip.exe) on client machine.
We will also be saving a batch file on the client machine to execute that console app with arguments to unzip the file.
We are aware this can be done on IE using ActiveXObject, but we need a cross browser solution.
Any help/alternative will be appreciated.

try {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); //this line is optional, you can pass extra information to the app with this code
startActivityForResult(intent, 0);
} catch (Exception e) {
Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
startActivity(marketIntent);
}
There are a variety of approaches that can be taken to solve the same problem How To Start A New Application From Another Application? Examples. The remaining options will be discussed further down.
Intent i = new Intent(MainActivity.this, MakeKey.class);
startActivity(i);
finish();
As we have seen, the issue with the How To Start A New Application From Another Application? Examples variable was resolved by making use of a variety of distinct instances.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.30-Jul-2019
Step 2 − Add the following code to res/layout/activity_main. xml.30-Jul-2019
Sorry for copy paste, there are some ideas how to do it in android studio.

Related

Unsuccessful in trying to start Selenium IDE recording from C# code

I'm working with Selenium WebDriver (3 latest, Chrome driver, 83 latest) in C# (windows10, .net fw 4.6.2). I'm trying to start the IDE recording from within the code of a running automation test, on the open web page, (my intention is to record all the actions being done within the automation test), but with no success.
I'm trying to do it using the IDE extension API (I don't want that the IDE will be actually open during the test, nor do I want it to reopen the page for recording, since it is already open by the automation test)
My final intention is to use the outcome of the IDE recording for something I need.
Here is my C# code:
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace IDE
{
class Program
{
static void Main(string[] args)
{
ChromeOptions options = new ChromeOptions();
// Load IDE extension to chrome
options.AddExtension(#"C:\Users\<my user name>\Downloads\extension_3_17_0_0.crx");
IWebDriver driver = new ChromeDriver(options);
// Start IDE recording
((IJavaScriptExecutor)driver).ExecuteScript("chrome.runtime.sendMessage(\"mooikfkahbdckldjjndioackbalphokd\", {uri: \"/record/session\", verb: \"post\", payload: {url: 'https://www.google.com'}});");
driver.Navigate().GoToUrl("https://www.google.com");
driver.Manage().Window.Maximize();
// Do some more actions
// ......
// Stop the IDE recording
((IJavaScriptExecutor)driver).ExecuteScript("chrome.runtime.sendMessage(\"mooikfkahbdckldjjndioackbalphokd\", {uri: \"/record/session\", verb: \"delete\"});");
driver.Quit();
}
}
}
I can see that the IDE extension is loaded, but the "chrome.runtime.sendMessage" is always throwing an exception (no matter what I supply as a value to its parameters) : "Cannot read property 'sendMessage' of undefined". The code I pasted here is just an example. I tried many other variations of "chrome.runtime.sendMessage". All of them threw the same exception.
I've seen a few discussions over the net about that exception in relation to my issue, but they all mention some java script files that have to be changed (manifest, content, etc.), which I'm not sure how to combine their suggestions with my code as it is in C#.
What am I missing here?
Any help will be much appreciated.
Thanks!!!
I am still waiting for anyone who could help. My question is very detailed and well explained. So is the code, that can be easily pasted, as is, to the editor (Just have the relevant refereces and the CRX file in your machine). If I can narrow it to one sentence, it would be: "How do I use the Selenium IDE API from the web driver in C# code?"

Babylon JS - SceneLoader from Local File

New Babylon JS user, looking to get up to speed with this fantastic framework. Have had a play with the Sandbox and online Editor, worked up my own coded model from scratch using the standard components - Box, Sphere etc. My question relates to how to get more complex custom geometry loaded. Very comfortable with 3D CAD - STL/OBJ files, got some exports going from Blender to .Babylon format which import great into Babylon's online Sandbox & Editors. However, I can't seem to get the SceneLoader going to read a file from local C:/ drive. Code extract below:
// Create new Babylon Scene
var scene = new BABYLON.Scene(engine);
// Change scene background color
scene.clearColor = new BABYLON.Color3(1, 1, 1);
// Create and positions a free camera
var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 10, 0), scene);
// Target the camera to scene origin
camera.setTarget(BABYLON.Vector3.Zero());
// Attach camera to the canvas
camera.attachControl(canvas, true);
// Define built-in 'box' shape.
var box = BABYLON.Mesh.CreateBox("sphere1", 1, scene);
// Define 'ground' plane
var ground = BABYLON.Mesh.CreateGround("ground1", 100, 100, 100, scene);
ground.position.y = 0;
//Load local .babylon file from root Dir
BABYLON.SceneLoader.Load("", "Test.babylon", engine, scene);
My model has a standard box for geometry with ground plane. All renders great in Babylon - until I add the SceneLoader line. When I add this I get stuck on the Babylon Loading intro splash screen (rotating Babylon logo). If I comment out the last line of code above the model renders fine with the box.
Have had a look at various forum pages on this and wrecked my brain to point of being stuck e.g: http://www.html5gamedevs.com/topic/20924-stlobj-file-loader/ & https://www.eternalcoding.com/?p=313
I believe Google Chrome may be locking out local file links for security, have tried running in -Allow-Local-File-Access mode, still stuck on loading page. Do I need a web server (I wouldn't know where to start!) or can I run Babylon scenes locally?
First issue posed by OP: Browser is not loading mesh from file system.
Solution: Use a web server such as Simple HTTP Server (Python). The way to do this is slightly different depending on your Python version. To check Python version on Windows, open command prompt and type python --version. Remember the version number for later :)
Setting up simple web server with Python with command prompt:
Navigate to the directory with your index.html file in File Explorer
Left click on to a blank space inside the path box (where it says This PC > Documents, etc...)
Type cmd and it will open Command Prompt in the current directory
Enter the appropriate command...
python -m SimpleHTTPServer [optional port number] if you are using Python 2
python -m http.server [optional port number] if you are using Python 3
I usually leave out the port number and simply type python -m http.server.
Now open your preferred browser and enter localhost:8000 into your address bar. (8000 is the default port number. If you specified a port, use the number which you specified.) It should load your mesh if the code has no errors.
Second issue posed by OP: SceneLoader.Load method overrides previously loaded meshes.
Solution:
If you only need to import a few meshes, use either BABYLON.SceneLoader.Append(...) or BABYLON.SceneLoader.ImportMesh(...). However, this method is inconvenient for managing many assets.
Alternatively, use BABYLON.AssetsManager(...). Since Babylon.js loads models in asynchronously, the asset manager allows ease of use through callback functions. In other words, you can find your assets by name by using scene.getMeshByName("yourMesh") if you type inside the callback function. Here is a simple demo.
I know this question is a few years old, but in case anyone still has issues with this I hope this answer helps.
So I’m not 100% sure about this answer, but hopefully it will help. I followed this tutorial (Skip down to the section where the scene gets loaded). One issue is definitely the cross origin thing, the other how you call the SceneLoader.Load method.
When I try the code from the tutorial with regular Chrome I see three warnings in my web console. Two errors about Test.babylon.manifest (using your example file naming) and one about Test.babylon. You can ignore the ones regarding manifests afaik. The important one is the error about Test.babylon itself. So by default Cross origin requests are not allowed and the babylon file does not load (as expected).
Now, when I close Chrome and reopen it by running open -a "Google Chrome" --args --allow-file-access-from-files in the terminal (I’m on OSX Yosemite), and then load the page, the object loads fine. I still see two errors about manifests in the web console, but they can be ignored.
Note how the BABYLON.SceneLoader.Load function is being called. The import process is asynchronous, and the last parameter looks to be a callback function for what to do once the object has successfully loaded, so I don't think you can just pass scene as in your original code. Check out the function docs.
Ok - porgress.
I got it going using SceneLoader.ImportMesh but I had to setup a simple HTTP Server using Python (v3). This link helped a lot: http://www.linuxjournal.com/content/tech-tip-really-simple-http-server-python
So you run the Python HTTP server from the directory that the Babylon index.html is based in, and it runs as if HTTP bypassing local file access constraints in Chrome.
So my problem is all but answered. I now have my mesh geometry from the Test.Baylon file into my main scene. Still having issues using SceneLoader.Load as the new scene coming in supercedes my original scene and the original geometry disappears. David - I think you're right on the function being needed, although I thought this was optional. As I said, the Tutorial example creates a newScene and renders within the function, in my case I don't know what to do in the function... maybe just 'return'?

How to force client reload after deployment?

I'm using the MEAN stack (mongo, express, angular and node). I'm deploying relatively frequently to production...every couple of days. My concern is that I'm changing the client side code and the API at times and I would rather not have to ensure backwards compatibility of the API with previous versions of the client code.
In such a scenario, what is the most effective way of ensuring that all clients reload when I push to production? I have seen that Evernote for example has a pop-up that says something along the lines of please reload your browser for the latest version of Evernote. I would like to do something similiar...do I need to go down the path of socket.io or sock.js or am I missing something simple and there is a simpler way to achieve this?
Update:
AppCache was deprecated summer 2015 so the below is no longer the best solution. The new recommendation is to use Service Workers instead. However, Service Workers are currently still experimental with sketchy (read: probably no) support in IE and Safari.
Alternatively, many build tools now seamlessly incorporate cache-busting and file "versioning" techniques to address OPs question. WebPack is arguably the current leader in this space.
This might be a good use case for using HTML5's AppCache
You'd probably want to automate some of these steps into your deployment scripts, but here is some code you might find useful to get you started.
First, create your appcache manifest file. This will also allow you to cache resources in the client's browser until you explicitly modify the appcache manifest file's date.
/app.appcache:
CACHE MANIFEST
#v20150327.114142
CACHE:
/appcache.js
/an/image.jpg
/a/javascript/file.js
http://some.resource.com/a/css/file.css
NETWORK:
*
/
In app.appcache, the comment on line #v20150327.114142 is how we indicate to the browser that the manifest has changed and resources should be reloaded. It can be anything, really, as long as the file will look different to the browser from the previous version. During deployment of new code in your application, this line should be modified. Could also use a build ID instead.
Second, on any pages you want to use the appcache, modify the header tag as such:
<html manifest="/app.appcache"></html>
Finally, you'll need to add some Javascript to check the appcache for any changes, and if there are, do something about it. Here's an Angular module. For this answer, here's a vanilla example:
appcache.js:
window.applicationCache.addEventListener('updateready', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
// Browser downloaded a new app cache.
// Swap it in and reload the page to get the latest hotness.
window.applicationCache.swapCache();
if (confirm('A new version of the application is available. Would you like to load it?')) {
window.location.reload();
}
}
else {
// Manifest didn't changed. Don't do anything.
}
}, false);
Alternatively, if AppCache won't work for your situation, a more ghetto solution would be to create a simple API endpoint that returns the current build ID or last deployment date-time. Your Angular application occasionally hits this endpoint and compares the result to it's internal version, and if different, reloads itself.
Or, you may consider a live-reload script (example), but, while very helpful in development, I'm not sure how good of an idea it is to use live/in-place-reloading of assets in production.
I will tell you my problem first then I will recommend a tentative solution. I wanted to force my user to log out and then log in when a production build is been deployed. At any point in time, there will be two versions of software deployed on production. A version which software which FE knows and a version which Backend knows. Most of the time they would be the same. At any point in time if they go out of sync then we need to reload the client to let the client know that a new production build has been pushed.
I am assuming 99.99% of the time the backend would have the knowledge of the latest version of the deployed software on production.
following are the two approaches which I would love to recommend:-
The backend API should always return the latest version of the software in the response header. On the frontend, we should have a common piece of code that would check if the versions returned by the API and that present on the FE are the same. if not then reload.
Whenever a user logs in. the BE should encode the latest software version in the JWT. And the FE should keep sending this as a bearer token along with every API request. The BE should also write a common interceptor for every API request. which would compare the software version in the JWT received from the API request and the
Maybe you can add hash to your client code file name. eg app-abcd23.js.
So the browser will reload the file instead of get it from cache. or you can just add the hash to url.eg app.js?hash=abcd23 but some browser may still use the cached version.
i know rails has assets-pipline to handle it, but i am not familiar with MEAN stack. there should be some package in npm for that purpose.
And i dont think it is really necessary to use socket.io if you want to notify the user their client code is out of date. you can define your version in both html meta tag and js file,if mismatch, show a popup and tell the user to refresh.
Try to limit your js/files to expire within smaller periodic time, ie: 1 days.
But in case you want something that pop-out and tell your user to reload (ctrl+f5) their browser, then simply make a script that popup that news if you just changed some of your files, mark the ip/session who have just reload/told to reload, so they will not be annoyed with multiple popup.
I was facing the same problem recently. I fixed this by appending my app's build number with my js/css files. All my script and style tags were included by a script in a common include files so it was trivial to add a 'build number' at the end of the js/css file path like this
/foo/bar/main.js?123
This 123 is a number that I keep track of in my same header file. I increment it whenever I want the client to force download all the js files of the app. This gives me control over when new versions are downloaded but still allows the browser to leverage cache for every request after the first one. That is until I push another update by increment the build number.
This also means I can have a cache expiry header of however long I want.
Set a unique key to local storage during the build process
I am using react static and loading up my own data file, in there i set the ID each time my content changes
Then the frontend client reads the key with from local storage
(if the key does not exist it must be the first visit of the browser)
if the key from local storage does not match it means the content has changed
fire line below to force reload
window.replace(window.location.href + '?' + key)
in my case i had to run this same line again a second latter
like
setTimeout( (window.replace(window.location.href + '?' + key))=> {} , 1000)
full code below:
const reloadIfFilesChanged = (cnt: number = 0, manifest: IManifest) => {
try {
// will fail if window does not exist
if (cnt > 10) {
return;
}
const id = localStorage.getItem('id');
if (!id) {
localStorage.setItem('id', manifest.id);
} else {
if (id !== manifest.id) {
// manifest has changed fire reload
// and set new id
localStorage.setItem('id', manifest.id);
location.replace(window.location.href + '?' + manifest.id);
setTimeout(() => {
location.replace(window.location.href + '?' + manifest.id + '1');
}, 1000);
}
}
} catch (e) {
// tslint:disable-next-line:no-parameter-reassignment
cnt++;
setTimeout(() => reloadIfFilesChanged(cnt, manifest), 1000);
}
};

Use javascript to launch local file on user's machine?

I have an Excel macro that runs in a workbook that our company uses. I've made cells look like hyperlinks, so when someone double-clicks on the link it opens IBM mainframe and loads up some data. I'm writing another app for us that's web based, and I'm wondering if this same functionality is possible. I haven't seen anything on the internet that would lead me to believe I could do this, but I thought I'd ask anyway....
Public SODD As String
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Target.Column = 2 And (Target.Row >= 1) Then
SODD = Target.Value
Call SOLookup
End If
End Sub
Sub SOLookup()
Dim autECLPS As Object
Dim s As New AutSess
AppActivate "3270 Terminal"
s.SetConnectionByName ("A")
s.autECLPS.StartCommunication
s.autECLPS.SendKeys "[Clear]"
s.autECLOIA.WaitForInputReady (500)
s.autECLPS.SetText "SODD " & SODD
s.autECLOIA.WaitForInputReady (500)
s.autECLPS.SendKeys "[ENTER]"
s.autECLOIA.WaitForInputReady (500)
End Sub
This loads the IBM mainframe and types in the sales order number into their screen and hits Enter.
Would I be able to accomplish this same feat using something like Javascript?
Javascript may not execute files on the user's local environment. However, a server side language may do what you require. For instance, you can use AJAX(javascript) to make a call to a PHP script which can execute, say, a batch file (.bat) which can then run your macro. The PHP file could have code as simple as
system("cmd /c C:[path to your macro/.bat file]");
Again, this all depends on your configuration and environment. So to recap: Web Browser->AJAX->PHP->Macro.
Neither Javascript nor any other script that runs inside the browser is allowed to execute any file locally on a user's computer. And this is a good tihng. Imagine what would happen if any website could randomly execute programs on your computer...
Internet ressources are not trusted, therefore they are not allowed to do anything on your local computer.
If the website is running in your company's intranet, there might be a way using proprietary MS technology and the Internet Explorer with properly configured trusted sites - but I wouldn't bother with it.

Download a File Based From Add-On

I'm building an add-on which launches an executable to enable advanced and intelligent proxy. I've been able to launch the executable perfectly but the exe is of decent size and I need a different one for each OS.
I don't want to package them all into the add-on because that would result in a unnecessarily large file size. I would like the add-on to download the correct file for the client's OS after it's installed.
I found nsIDownloader but the only method it has is init() which takes an observer and a download location. I have no idea how I would give it the web server location. It seems like a significant amount of documentation on it is missing.
nsIDownloader may sound like it is a good place to start, but it really is just a low-level helper API, and discouraged these days because it does synchronous I/O on the main/UI thread.
I'd instead use the relatively new, and asynchronous Downloads.fetch() high-level helper.
E.g. the following will work in a Scratchpad. It would work in any add-on as well, if the execution environment has console (e.g. overlays, or Console.jsm), or the debug console.log calls where removed.
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/Downloads.jsm");
Task.spawn(function() {
var file = Services.dirsvc.get("TmpD", Ci.nsIFile);
file.append("test.download");
try {
yield Downloads.fetch("http://example.org/", file);
console.log(file.path);
console.log(file.exists());
console.log(file.fileSize);
}
catch (ex) {
console.log("Download Failed", ex);
}
});

Categories

Resources