How to run an EXE file through URL on .Net shared hosting - javascript

I try to run a simple ETL process on a schedule to populate a SQL Server database table on a .Net shared hosting. The EXE file will be hosted with the website and when it runs it will make some API calls and get data to update the website's SQL table.
My hosting company allows such thing (to call an exe file on schedule) with an extra fee, but they require me to have it wrapped and be called using URL. They don't mind any technology to use as long as I provide a URL. I did few attempt to get this setup working with no luck. For example I tried two ways below: Note, I just started to learn JavaScript, I use C# but this is my first time attempt to do something like that and I might be completely off. Any help will be appreciated.
<html>
<head>
<title>Open PMETL</title>
<script type="text/javascript">
function runProgram()
{
try {
var shell = new ActiveXObject("WScript.Shell");
var myPMETL="http://trudat.live/RefreshData.exe";
shell.Run(myPMETL);
}
catch (e) {
alert(e.message);
}
}
function runProgram02() {
if (window.ActiveXObject) {
try {
var excelApp = new ActiveXObject ("Excel.Application");
excelApp.Visible = true;
}
catch (e) {
alert (e.message);
}
}
else {
alert ("Your browser does not support this example.");
}
}
</script>
</head>
<body>
Run program
Run program02
</body>
</html>

I was able to achieve that by adding a new page to my ASP.NET application and port the console application into the code-behind C# and invoke the code through the Page_Load() method. This allowed my to give the hosting company a URL like http://mydomain/ExePage.aspx without impacting my original application since this new page is not reachable from the application's menu. it was a convenient way to give me what I needed.
I assume this is not a typical solution since I had the advantage to have the source code of the EXE program, but nevertheless it is a very effective, and this might help someone in the future.

Related

"ScriptError: Authorisation is required to perform that action." when running google.script.run from Library

Regards,
I have found several questions regarding this error :
"ScriptError: Authorisation is required to perform that action." but I can't find one that is about my issue.
What I am trying to do is call a function .gs file from .html file using google.script.run where both of the file is in Library. Referring to this answer, this answer and this bug report, I have created the "wrapper function" in the script that is using the library, but still failed to finish the execution.
Here's what I did :
.html in Library :
<html>
<head>
<script>
function onFailure(error) {
console.log("ERROR: " + error);
}
function myfunc() {
console.log("HERE");
google.script.run.withFailureHandler(onFailure).callLibraryFunction('LibraryName.test', ['test123']);
}
</script>
</head>
<body>
<button onclick="myfunc()">CLICK</button>
</body>
</html>
.gs in Library
function test(x){
Logger.log(x);
}
.gs in script that is using the Library:
function callLibraryFunction(func, args) {
var arr = func.split(".");
var libName = arr[0];
var libFunc = arr[1];
args = args || [];
return this[libName][libFunc].apply(this, args);
}
The console logs HERE but then it logs ERROR: ScriptError: Authorisation is required to perform that action. instead of the expected output, test123.
NOTE: The HTML is for custom modeless dialog box in Sheets and not for Web App.
I really hope someone can help me in this. Thank you in advance.
You need to grant access of the library "LibraryName" as an authorized app in your Gmail account the same way how you grant access to the calling script. I guess you have called the method HtmlService.createHtmlOutputFromFile(...) in your library. This requires more authorization. You need to grant this. What you can do is create a temporary function in the library that has HtmlService.createHtmlOutputFromFile(..). Run it from the script editor and the authorization requirement window appears. Proceed in granting access...

Android Calling JavaScript functions in Button

I've an Android Activity and I've got a Button that button need to access some Javascript function. Simply my app get the user info(ID,pass) then go to web page(this operation doing backgrun with asynctask class) write these two info as ID and pass then user click the Log In button in my app button has to use some js function
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
this is the func. i need to use
My post and get request for connection the site are
POST//
URL url = new URL(params[0]); //http://login.cu.edu.tr/Login.aspx? site=https://derskayit.cu.edu.tr&ReturnUrl=%2f
connection=(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
these codes for the put the ID and pass
GET //
reader= new BufferedReader((new InputStreamReader(connection.getInputStream())));
StringBuilder builder = new StringBuilder();
String line;
while((line= reader.readLine())!=null){
builder.append(line + "\n");
}
text=builder.toString();
there is any help or suggestion for me i am very confused about that situation and i feel really bad myself thanks for helps anyway. Have a nice day
For using Javascript without a webView to make requests!
The question has already an answer here in this question
The javax.script package is not part of the Android SDK. You can execute JavaScript in a WebView, as described here. You perhaps can use Rhino, as described here. You might also take a look at the Scripting Layer for Android project.
Also a similar question was asked here
You can execute JavaScript without a WebView. You can use AndroidJSCore. Here is a quick example how you might do it:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://your_website_here/file.js");
HttpResponse response = client.execute(request);
String js = EntityUtils.toString(response.getEntity());
JSContext context = new JSContext();
context.evaluateScript(js);
context.evaluateScript("question.vote(0);");
However, this most likely won't work outside of a WebView, because I presume you are not only relying on JavaScript, but AJAX, which is not part of pure JavaScript. It requires a browser implementation.
Is there a reason you don't use a hidden WebView and simply inject your code?
// Create a WebView and load a page that includes your JS file
webView.evaluateJavascript("question.vote(0);", null);
Otherwise:
Yes you can make HTTP POST and HTTP GET requests without using WebView. But if you want to use a webView remember Javascript in a webview is disabled by default (for security purposes). So before calling any javascript functions make sure you enable javascript in your webview like this
webView.getSettings().setJavaScriptEnabled( true );
And after that javascript will be enabled in your webView.
But in case you do not want to use a webview and javascript to make http requests. There is a lot of alternative methods you can define a Button in your activity's layout in xml. And respond with a http request on button Clicked listener!
Also remember making http Request using Android/Java default classes is a huge task and error prone and requires you to care about using async tasks to avoid blocking the UI thread.
Alternatively
In android we use ready-made library to make http requests. Google has a good library called Volley. it is easy to customize,respond to errors and it automatically making request out of the main thread.See more explanation here!. If there is still some problems comment below!

Search for injected script code on the Windows Server for my ASP.NET site

My site was probably hacked. I am finding script.js from bigcatsolutions.com in my page. It triggers a popup of an affiliate program. The script isn't on the page by default and I want to know how can I find where it was injected. The script sometimes injects other ad sites.
In chrome I see this:
The injected script code:
function addEvent(obj, eventName, func) {
if (obj.attachEvent) {
obj.attachEvent("on" + eventName, func);
} else if (obj.addEventListener) {
obj.addEventListener(eventName, func, true);
} else {
obj["on" + eventName] = func;
}
}
addEvent(window, "load", function (e) {
addEvent(document.body, "click", function (e) {
if (document.cookie.indexOf("booknow") == -1) {
params = 'width=800';
params += ', height=600';
params += ', top=50, left=50,scrollbars=yes';
var w = window.open("http://booknowhalong.com/discount-news", 'window', params).blur();
document.cookie = "booknow";
window.focus();
}
});
})
My site is moved from my hosting company to Amazon EC2 Windows 2013 Server and still have the issues, so it means that the code still resides on the server somewhere. My site was build using ASP.ENT / C#.
Things I did:
tried to search the original aspx and aspx.cs code files
Have you checked the IIS logs to see if they are hitting a specific page and injecting it there?
Do you load any data from a database? You could check in the tables and see if anything out of the ordinary appears there.
It is unlikely that the .aspx pages have actually been physically modified and even more unlikely that the DLL have been as .aspx.cs files are compiled in to your BIN folder as DLL's. The more likely scenario is that you have an unsecure page that a malicious site is injecting its script into. The other possible attack vector is that you have had malicious code via SQL injection and are loading it each time.
After deep searching and I missed it in the first run, I found that the script was injected into the ASP.NET masterpage.
I ran a search to search for a specific string in all the files and that's how I found it. It seems that the server itself was breached and the hacker put the code into several websites.
So for those of you who have this type of problem, I recommend running a text search and try to find the URL that is tights to the running script.
Hope that helps and thanks for your time.

Detect between a mobile browser or a PhoneGap application

Is it possible to detect if the user is accessing through the browser or application using JavaScript?
I'm developing a hybrid application to several mobile OS through a web page and a PhoneGap application and the goal would be to:
Use the same code independently of the deployment target
Add PhoneGap.js file only when the user agent is an application
You could check if the current URL contains http protocol.
var app = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1;
if ( app ) {
// PhoneGap application
} else {
// Web page
}
Quick solution comes to mind is,
onDeviceReady
shall help you. As this JS call is invoked only by the Native bridge (objC or Java), the safari mobile browser will fail to detect this. So your on device app(phone gap) source base will initiate from onDeviceReady.
And if any of the Phonegap's JS calls like Device.platform or Device.name is NaN or null then its obviously a mobile web call.
Please check and let me know the results.
I figured out a way to do this and not rely on deviceready events thus, keeping the web codebase intact...
The current problem with using the built in deviceready event, is that when the page is loaded, you have no way of telling the app: "Hey this is NOT running on an mobile device, there's no need to wait for the device to be ready to start".
1.- In the native portion of the code, for example for iOS, in MainViewController.m there's a method viewDidLoad, I am sending a javascript variable that I later check for in the web code, if that variable is around, I will wait to start the code for my page until everything is ready (for example, navigator geolocation)
Under MainViewController.m:
- (void) viewDidLoad
{
[super viewDidLoad];
NSString* jsString = [NSString stringWithFormat:#"isAppNative = true;"];
[self.webView stringByEvaluatingJavaScriptFromString:jsString];
}
2.- index.html the code goes like this:
function onBodyLoad()
{
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady(){;
myApp.run();
}
try{
if(isAppNative!=undefined);
}catch(err){
$(document).ready(function(){
myApp.run();
});
}
PhoneGap has window.PhoneGap (or in Cordova, it's window.cordova or window.Cordova) object set. Check whether that object exists and do the magic.
Inside the native call where the url for the phonegap app is loaded you add a parameter target with value phonegap. So the call for android becomes something like this.
super.loadUrl("file:///android_asset/www/index.html?target=phonegap");
Your website using this code won't be called with the extra parameter, so we now have something different between the two deploying platforms.
Inside the javascript we check if the parameter exists and if so we add the script tag for phonegap/cordova.
var urlVars = window.location.href.split('?');
if(urlVars.length > 1 && urlVars[1].search('target=phonegap') != -1){
//phonegap was used for the call
$('head').append('<script src="cordova.js"></script>');
}
A small caveat: this method requires to change the call to index.html in phonegap for each different targeted mobile platform. I am unfamiliar where to do this for most platforms.
what if you try following :
if(window._cordovaNative) {
alert("loading cordova");
requirejs(["...path/to/cordova.js"], function () {
alert("Finished loading cordova");
});
}
I am using the same code for both phonegap app and our web client. Here is the code that I use to detect if phonegap is available:
window.phonegap = false;
$.getScript("cordova-1.7.0.js", function(){
window.phonegap = true;
});
Keep in mind that phonegap js file is loaded asynchronously. You can load it synchronously by setting the correct option of a nifty jquery $.getScript function.
Note that approach does make an extra GET request to grab phonegap js file even in your webclient. In my case, it did not affect the performance of my webclient; so it ended up being a nice/clean way to do this.Well at least until someone else finds a quick one-line solution :)
It sounds like you are loading another webpage once the webview starts in the Phonegap app, is that correct? If that's true then you could add a param to the request url based on configuration.
For example, assuming PHP,
App.Config = {
target: "phonegap"
};
<body onload="onbodyload()">
var onbodyload = function () {
var target = App.Config.target;
document.location = "/home?target=" + target;
};
Then on the server side, include the phonegap js if the target is phonegap.
There is no way to detect the difference using the user agent.
The way I'm doing it with is using a global variable that is overwritten by a browser-only version of cordova.js. In your main html file (usually index.html) I have the following scripts that are order-dependent:
<script>
var __cordovaRunningOnBrowser__ = false
</script>
<script src="cordova.js"></script> <!-- must be included after __cordovaRunningOnBrowser__ is initialized -->
<script src="index.js"></script> <!-- must be included after cordova.js so that __cordovaRunningOnBrowser__ is set correctly -->
And inside cordova.js I have simply:
__cordovaRunningOnBrowser__ = true
When building for a mobile device, the cordova.js will not be used (and instead the platform-specific cordova.js file will be used), so this method has the benefit of being 100% correct regardless of protocols, userAgents, or library variables (which may change). There may be other things I should include in cordova.js, but I don't know what they are yet.
Ive ben struggling with this aswell, and i know this is an old thread, but i havent seen my approach anywhere, so thought id share incase itll help someone.
i set a custom useragent after the actual useragent :
String useragent = settings.getUserAgentString();
settings.setUserAgentString(useragent + ";phonegap");
that just adds the phonegap string so other sites relying on detecting your mobile useragent still works.
Then you can load phonegap like this:
if( /phonegap/i.test(navigator.userAgent) )
{
//you are on a phonegap app, $getScript etc
} else {
alert("not phonegap");
}
To my mind you try to make issue for self. You didn't mentioned your development platform but most of them have different deployment configuration. You can define two configurations. And set variable that indicates in which way code was deployed.
In this case you don't need to care about devices where you deployed your app.
Short and effective:
if (document.location.protocol == 'file:') { //Phonegap is present }
Similar to B T's solution, but simpler:
I have an empty cordova.js in my www folder, which gets overwritten by Cordova when building. Don't forget to include cordova.js before your app script file (it took my one hour to find out that I had them in wrong order...).
You can then check for the Cordova object:
document.addEventListener('DOMContentLoaded', function(){
if (window.Cordova) {
document.addEventListener('DeviceReady', bootstrap);
} else {
bootstrap();
}
});
function bootstrap() {
do_something()
}
New solution:
var isPhoneGapWebView = location.href.match(/^file:/); // returns true for PhoneGap app
Old solution:
Use jQuery, run like this
$(document).ready(function(){
alert(window.innerHeight);
});
Take iPhone as example for your mobile application,
When using PhoneGap or Cordova, you'll get 460px of WebView, but in safari, you'll lose some height because of browser's default header and footer.
If window.innerHeight is equal to 460, you can load phonegap.js, and call onDeviceReady function
Nobody mentioned this yet, but it seems Cordova now supports adding the browser as a platform:
cordova platforms add browser
This will automatically add cordova.js during run-time, which features the onDeviceReady event, so that you do not need to fake it. Also, many plugins have browser support, so no more browser hacks in your code.
To use your app in the browser, you should use cordova run browser. If you want to deploy it, you can do so using the same commands as the other platforms.
EDIT: forgot to mention my source.
Solution: Patch index.html in Cordova and add cordova-platform="android" to <html> tag, so that cordova-platform attribute will be only present in Cordova build and missing from original index.html used for web outside of Cordova.
Pros: Not rely on user agent, url schema or cordova API. Does not need to wait for deviceready event. Can be extended in various ways, for example cordova-platform="browser" may be included or not, in order to distinguish between web app outside of Cordova with Cordova's browser platform build.
Merge with config.xml
<platform name="android">
<hook src="scripts/patch-android-index.js" type="after_prepare" />
</platform>
Add file scripts/patch-android-index.js
module.exports = function(ctx) {
var fs = ctx.requireCordovaModule('fs');
var path = ctx.requireCordovaModule('path');
var platformRoot = path.join(ctx.opts.projectRoot, 'platforms/android');
var indexPath = platformRoot + '/app/src/main/assets/www/index.html';
var indexSource = fs.readFileSync(indexPath, 'utf-8');
indexSource = indexSource.replace('<html', '<html cordova-platform="android"');
fs.writeFileSync(indexPath, indexSource, 'utf-8');
}
Notes: For other than android, the paths platforms/android and /app/src/main/assets/www/index.html should be adjusted.
App can check for cordova-platform with
if (! document.documentElement.getAttribute('cordova-platform')) {
// Not in Cordova
}
or
if (document.documentElement.getAttribute('cordova-platform') === 'android') {
// Cordova, Android
}

How do I store static content of a web page in a javascript variable?

This is what I am trying to accomplish:
Get the static content of an 'external' url and check it for certain keywords for example, "User Guide" or "page not found".
I tried to use Ajax, dojo.xhr etc., but they don't support cross domain. In my case it is an external url. Also, I cannot use jQuery.
I also looked at dojo.io.iframe but I couldn't find useful example to accomplish this.
A dojo.io.iframe example would be really helpful.
Please help.
Thanks!
Modern browsers restrict the use of cross-domain scripting. If you're the maintainer of the server, read Access-Control-Allow-Origin to get knowledge on how to enable cross-site scripting on your website.
EDIT: To check whether an external site is down or not, you could use this method. That external site is required to have an image file. Most sites have a file called favicon.ico at their root directory.
Example, testing whether http://www.google.com/ is online or not.
var test = new Image();
//If you're sure that the element is not a JavaScript file
//var test = document.createElement("script");
//If you're sure that the external website is reliable, you can use:
//var test = document.createElement("iframe");
function rmtmp(){if(tmp.parentNode)tmp.parentNode.removeChild(tmp);}
function online(){
//The website is likely to be up and running.
rmtmp();
}
function offline(){
//The file is not a valid image file, or the website is down.
rmtmp();
alert("Something bad happened.");
}
if (window.addEventListener){
test.addEventListener("load", online, true);
test.addEventListener("error", offline, true);
} else if(window.attachEvent){
test.attachEvent("onload", online);
test.attachEvent("onerror", offline);
} else {
test.onload = online;
test.onerror = offline;
}
test.src = "http://www.google.com/favicon.ico?"+(new Date).getTime();
/* "+ (new Date).getTime()" is needed to ensure that every new attempt
doesn't get a cached version of the image */
if(/^iframe|script$/i.test(test.tagName)){
test.style.display = "none";
document.body.appendChild(test);
}
This will only work with image resources. Read the comments to see how to use other sources.
Try this:
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js.uncompressed.js" type="text/javascript" djConfig="parseOnLoad:true"></script>
<script>
dojo.require("dojo.io.script");
</script>
<script>
dojo.addOnLoad(function(){
dojo.io.script.get({
url: "http://badlink.google.com/",
//url: "http://www.google.com/",
load: function(response, ioArgs) {
//if no (http) error, it means the link works
alert("yes, the url works!")
}
});
});
</script>

Categories

Resources