I have a requirement to develop a tool to backup certain folders and files present in a shared drive (Windows 7) using Client-Side technologies (HTML5, CSS3 and JavaScript) only. Below is the JavaScript function to copy the file.
function copyFile() {
var myObject, f;
myObject = new ActiveXObject("Scripting.FileSystemObject");
f = myObject.GetFile("#\\Network_Name\Home$\User_Folder\Downloads\Folder_Name\Test.pdf");
if(!f)
{
return alert("File Not Found");
}
f.copy("#\\Network_Name\Home$\User_Folder\Downloads\Backup_Folder");
}
Since I'm using ActiveXObject, the above code will work only in IE. But I'm getting the below error in the line #\\Network_Name\Home$\User_Folder\Downloads\Folder_Name\Test.pdf. Please help me to properly access the network folder using JavaScript.
The verbatim identifier (#) is for C# not JavaScript, you need to escape your slashes:
.GetFile("\\\\Network_Name\\Home$\\User_Folder\\Downloads\\Folder_Name\\Test.pdf");
Try to use Ajax request method type "GET" for this purpose.
Related
I have two servers: A and B.
My Classic ASP application is deployed on Server A.
Server B contains a Folder (ScannedDocuments). I have created a Shared Drive on Server A to point to this folder. The Share Drive is named Q:.
On IE 7, when I try to access file using javascript, I am using:
window.open(file://Q:/a.txt)
It opens the file. But on IE 8 and above and all versions of Firefox, it is not opening. Neither an error is generated nor the file is opening.
I guess it is getting blocked by browser's security features.
Please let me know how I can open files on these browser versions.
Is there any other way to open a remote file using javascript or using IIS?
** Edited **
I tried creating a Virtual Directory on IIS and pointing to Shared Drive. But it gives error: resource or directory not found.
I am using IIS 7
#Anant Dabhi is right - create simple Ajax call to server ant return file content.
Client (JS). Use it instead of window.open(file://Q:/a.txt)
function getFile(filename) {
$.ajax({
url: "/YourWeb/File/Get",
data: {
filename: filename
},
success: function (data) {
console.log(data);
}
});
}
Your "backend". Assume that your are using .NET :)
public ActionResult Get()
{
string pathToFolder = "x:\\yyy\\zzz";
// Strip any directories and leave only name of file. Exception is possible ;)
string filename = Path.GetFileName(Request["filename"]);
byte[] ba = File.ReadAllBytes(Path.Combine(pathToFolder, filename));
string s = Encoding.UTF8.GetString(ba);
// Return as text (if you are absolutetlly sure it is text!)
return Content(s);
// Or pack it in JSON object to have status
return Json(new { Status = true, Data = s });
}
You could connect to UNC if you wish https://msdn.microsoft.com/en-us/library/windows/desktop/aa385482%28v=vs.85%29.aspx
I want to identify few properties during my run and form a json object which I would like to write to a ".json"file and save it on the disk.
var target = UIATarget.localTarget();
var properties = new Object();
var jsonObjectToRecord = {"properties":properties}
jsonObjectToRecord.properties.name = "My App"
UIALogger.logMessage("Pretty Print TEST Log"+jsonObjectToRecord.properties.name);
var str = JSON.stringify(jsonObjectToRecord)
UIALogger.logMessage(str);
// -- CODE TO WRITE THIS JSON TO A FILE AND SAVE ON THE DISK --
I tried :
// Sample code to see if it is possible to write data
// onto some file from my automation script
function WriteToFile()
{
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/Volumes/DEV/test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
}
AND
function WriteFile()
{
// Create an instance of StreamWriter to write text to a file.
sw = new StreamWriter("TestFile.txt");
// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
sw.WriteLine("-------------------");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
sw.Close();
}
But still unable to read and write data to file from ui automation instruments
Possible Workaround ??
To redirect to the stdout if we can execute a terminal command from my ui automation script. So can we execute a terminal command from the script ?
Haven't Tried :
1. Assuming we can include the library that have those methods and give it a try .
Your assumptions are good, But the XCode UI Automation script is not a full JavaScript.
I don't think you can simply program a normal browser based JavaScript in the XCode UI Automation script.
set fso = CreateObject("Scripting.FileSystemObject");
Is not a JavaScript, it is VBScript which will only work in Microsoft Platforms and testing tools like QTP.
Scripting.FileSystemObject
Is an ActiveX object which only exists in Microsoft Windows
Only few JavaScript functions like basic Math, Array,...etc..Are provided by the Apple JavaScript library, so you are limited to use only the classes provided here https://developer.apple.com/library/ios/documentation/DeveloperTools/Reference/UIAutomationRef/
If you want to do more scripting then Try Selenium IOS Driver http://ios-driver.github.io/ios-driver/
Hey so this is something that I was looking into for a project but never fully got around to implementing so this answer will be more of a guide of what to do than step by step copy and paste.
First you're going to need to create a bash script that writes to a file. This can be as simple as
!/bin/bash
echo $1 >> ${filename.json}
Then you call this from inside your Xcode Instruments UIAutomation tool with
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout("your/script/path", ["Object description in JSON format"], 5);
Then after your automation ends you can load up the file path on your computer to look at the results.
EDIT: This will enable to write to a file line by line but the actual JSON formatting will be up to you. Looking at some examples I don't think it would be difficult to implement but obviously you'll need to give it some thought at first.
I have created an extension for mozilla firefox. Now, I'm trying to distribute the extension on an simple web site. I generate a sha1 hash code from an online generator. This is the code I have in my web site:
<script type="application/javascript">
function install (aEvent)
{
for (var a = aEvent.target; a.href === undefined;) a = a.parentNode;
var params = {
"Foo": { URL: aEvent.target.href,
Hash: aEvent.target.getAttribute("hash"),
toString: function () { return this.URL; }
}
};
InstallTrigger.install(params);
return false;
}
</script>
<a href="c:/grouAndUsersWorkSpace/MozillaAddon/createtab.xpi"
hash="sha1:a7093a2afe1a53fde114a4a7dcb3e15e57862642"
onclick="return install(event);">Install Extension!</a>
the path of the url is local. And as a result when I start the application I got "The add-on could not be downloaded because of a connection failure on localhost".
I changed the path of the url to be: file://c:/grouAndUsersWorkSpace/MozillaAddon/createtab.xpi and with this nothing happens.
I have two questions:
1. Is that a good way to generate a hash code?
2. What should cause that connection failure?
1) I prefer to use the CHK Checksum Utility to generate checksums.
2) I don't have access at the moment to verify it, but have you tried serving the extension with Apache or similar?
Edit
Since you used a local file, you'll need a 3 slashes instead of 2 : file URI scheme .
Tested it both ways, they both work.
I want to write an App (JS) with SQLite (VS2012). So I can't find a easy beginnerguide for this. When I install the SQLite for Windows Runtime. There is a C++ code (GitHub) to insert in the Projekt.
So, what happens with the JS - Projekt?
How can JS refer to properties and methodes of the DB-Objekt (dll, ocx, whatever from the SQLite-Runtime) just to open DB, execute SQL etc. in a simple way?
In Android-Browser following simple JS code (no more) is korrekt:
var shortName = 'testDb';
var version = '1.0';
var displayName = 'test db';
var maxSize = 1048576; // in bytes
mydb = window.openDatabase(shortName, version, displayName, maxSize);
function(transaction) {
transaction.executeSql('CREATE TABLE IF NOT EXISTS person(id INTEGER ..);', [], NullDataHandler, errorHandler);
}
Is somebody here - can show me the same SIMPLE in VS2012 without an Overhead, advanced settings and error-mangement - I can't follow the code?
1. DB_open : ..
2. Execute SQL : ..
Many Greetings from Bavaria
ralphi
PS: Why isn't it allowed to insert links?
I assume your Javascript is running on a web page. Actually, There is no way to manipulate the Sqlite database from a web page. For security reason, the ability to access local files from a web page is strictly limited. Despite new HTML5-supported browsers allow you to access local files in a limited and safe way, directly using local database is not possible in HTML world.
If you are developing an extension for one of the mozilla applications (e.g. Firefox, Thunderbird, etc.) you define a extension id in the install.rdf.
If for some reason you need to know the extension id e.g. to retrieve the extension dir in local file system (1) or if you want to send it to a webservice (useage statistic) etc. it would be nice to get it from the install.rdf in favour to have it hardcoded in your javascript code.
But how to access the extension id from within my extension?
1) example code:
var extId = "myspecialthunderbirdextid#mydomain.com";
var filename = "install.rdf";
var file = extManager.getInstallLocation(extId).getItemFile(extId, filename);
var fullPathToFile = file.path;
I'm fairly sure the 'hard-coded ID' should never change throughout the lifetime of an extension. That's the entire purpose of the ID: it's unique to that extension, permanently. Just store it as a constant and use that constant in your libraries. There's nothing wrong with that.
What IS bad practice is using the install.rdf, which exists for the sole purpose of... well, installing. Once the extension is developed, the install.rdf file's state is irrelevant and could well be inconsistent.
"An Install Manifest is the file an Add-on Manager-enabled XUL application uses to determine information about an add-on as it is being installed" [1]
To give it an analogy, it's like accessing the memory of a deleted object from an overflow. That object still exists in memory but it's not logically longer relevant and using its data is a really, really bad idea.
[1] https://developer.mozilla.org/en/install_manifests
Like lwburk, I don't think its available through Mozilla's API's, but I have an idea which works, but it seems like a complex hack. The basic steps are:
Set up a custom resource url to point to your extension's base directory
Read the file and parse it into XML
Pull the id out using XPath
Add the following line to your chrome.manifest file
resource packagename-base-dir chrome/../
Then we can grab and parse the file with the following code:
function myId(){
var req = new XMLHttpRequest();
// synchronous request
req.open('GET', "resource://packagename-base-dir/install.rdf", false);
req.send(null);
if( req.status !== 0){
throw("file not found");
}
var data = req.responseText;
// this is so that we can query xpath with namespaces
var nsResolver = function(prefix){
var ns = {
"rdf" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"em" : "http://www.mozilla.org/2004/em-rdf#"
};
return ns[prefix] || null;
};
var parser = CCIN("#mozilla.org/xmlextras/domparser;1", Ci.nsIDOMParser);
var doc = parser.parseFromString(data, "text/xml");
// you might have to change this xpath expression a bit to fit your setup
var myExtId = doc.evaluate("//em:targetApplication//em:id", doc, nsResolver,
Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE, null);
return myExtId.singleNodeValue.textContent;
}
I chose to use a XMLHttpRequest(as opposed to simply reading from a file) to retrieve the contents since in Firefox 4, extensions aren't necessarily unzipped. However, XMLHttpRequest will still work if the extension remains packed (haven't tested this, but have read about it).
Please note that resource URL's are shared by all installed extensions, so if packagename-base-dir isn't unique, you'll run into problems. You might be able to leverage Programmatically adding aliases to solve this problem.
This question prompted me to join StackOverflow tonight, and I'm looking forward participating more... I'll be seeing you guys around!
As Firefox now just uses Chrome's WebExtension API, you can use #serg's answer at How to get my extension's id from JavaScript?:
You can get it like this (no extra permissions required) in two
different ways:
Using runtime api: var myid = chrome.runtime.id;
Using i18n api: var myid = chrome.i18n.getMessage("##extension_id");
I can't prove a negative, but I've done some research and I don't think this is possible. Evidence:
This question, which shows that
the nsIExtensionManager interface
expects you to retrieve extension
information by ID
The full nsIExtensionManager interface
description, which shows no
method that helps
The interface does allow you to retrieve a full list of installed extensions, so it's possible to retrieve information about your extension using something other than the ID. See this code, for example:
var em = Cc['#mozilla.org/extensions/manager;1']
.getService(Ci.nsIExtensionManager);
const nsIUpdateItem = Ci.nsIUpdateItem;
var extension_type = nsIUpdateItem.TYPE_EXTENSION;
items = em.getItemList(extension_type, {});
items.forEach(function(item, index, array) {
alert(item.name + " / " + item.id + " version: " + item.version);
});
But you'd still be relying on hardcoded properties, of which the ID is the only one guaranteed to be unique.
Take a look on this add-on, maybe its author could help you, or yourself can figure out:
[Extension Manager] Extended is very
simple to use. After installing, just
open the extension manager by going to
Tools and the clicking Extensions. You
will now see next to each extension
the id of that extension.
(Not compatible yet with Firefox 4.0)
https://addons.mozilla.org/firefox/addon/2195