I want calculate md5 of images that loaded in webdriver in java.
webdriver is Firefox.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.JavascriptExecutor;
String script = "var imgElement = document.querySelector('div.mtl:nth-child(2) > div:nth-child(1) > img:nth-child(1))'; *** return md5 of image *** ";
String url = "http://www.facebook.com";
WebDriver webDriver = new FirefoxDriver();
driver.get(url);
JavascriptExecutor js = (JavascriptExecutor) driver;
Stgin md5 = (String) js.executeScript(script);
in this code, what must replace with :
*** return md5 of image ***
You can use fetch with force-cache to get the content from cache. Then digest the arrayBuffer from the response. Unfortunately, MD5 is too old and the browser doesn't support it anymore. See more details about Crypto here. You can choose SHA-1, SHA-256, SHA-384, and SHA-512. See an example to digest SHA-256 below.
public void getImageSHA256(){
driver.get("https://www.blognone.com/");
WebElement img = driver.findElement(By.cssSelector("img"));
String imgUrl = img.getAttribute("src").trim();
String script = "function hex(buffer) { var hexCodes = []; var view = new DataView(buffer); for (var i = 0; i < view.byteLength; i += 4) { var value = view.getUint32(i); var stringValue = value.toString(16); var padding = '00000000'; var paddedValue = (padding + stringValue).slice(-padding.length); hexCodes.push(paddedValue); } return hexCodes.join(\"\");}" +
"var callback = arguments[arguments.length - 1];" +
"fetch(arguments[0],{cache:'force-cache'}).then((response)=> {" +
"return response.arrayBuffer(); }).then((buffer)=>{" +
" return crypto.subtle.digest('SHA-256', buffer); }).then((hashArray)=>{" +
" callback(hex(hashArray));"+
"});";
driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);
Object response = ((JavascriptExecutor) driver).executeAsyncScript(script, imgUrl);
System.out.println(response);
}
Screenshot below show comparison between SHA-256 from my code and SHA-256 from an online tool.
public void getImageMD5(){
driver.get("https://www.blognone.com/");
WebElement img = driver.findElement(By.cssSelector("img"));
String imgUrl = img.getAttribute("src").trim();
String script = "var callback = arguments[arguments.length - 1];"
+ "function _arrayBufferToBase64( buffer ) {"
+ " var binary = '';"
+ " var bytes = new Uint8Array( buffer );"
+ " var len = bytes.byteLength;"
+ " for (var i = 0; i < len; i++) {"
+ " binary += String.fromCharCode( bytes[ i ] );"
+ " }"
+ " return window.btoa( binary );"
+ "}"
+ " fetch(' " + imgUrl + " ',{cache:'force-cache'})."
+ "then((response)=>{return response.arrayBuffer()})."
+ "then((response)=>{return _arrayBufferToBase64(response)})."
+ "then((response)=>{callback(response)});";
driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);
Object response = ((JavascriptExecutor) driver).executeAsyncScript(script, imgUrl);
byte[] data = Base64.getDecoder().decode((String) response);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(data);
StringBuilder sb = new StringBuilder(2 * hash.length);
for (byte b : hash) {
sb.append(String.format("%02x", b & 0xff));
}
String digest = sb.toString();
System.out.println("MD5 of Image : " + digest);
}
Related
I tried the bellow code to create RSA-OAEP and A128GCM JWE generator and validator. it works with node js , ie, encrypt claims and generate the jwe and decrypt the same gives me the claims. but it is not working with the other clients , like nimbusds jose, jose4j. So for a sure I am missing something.
I am doing this by reading https://www.rfc-editor.org/rfc/rfc7516
index.js
var crypto = require('crypto');
var randomstring = require("randomstring");
var ursa = require("ursa");
var fs = require("fs");
var base64url = require('base64url');
var ascii = require("./ASCII");
var claims = {
firstName: "vimal"
};
var header = {
"enc": "A128GCM",
"alg": "RSA-OAEP"
};
var headerBase64Url = base64url.encode(JSON.stringify(header));
console.log("headerBase64Url : " + headerBase64Url);
console.log("headerBase64Url to UTF8 : " + base64url.decode(headerBase64Url));
var cek = randomstring.generate(16);
console.log("cek : " + cek);
var publicKey = ursa.createPublicKey(fs.readFileSync('./pubkey.pem'));
var encryptedKey = publicKey.encrypt(cek, 'utf8', 'base64');
console.log("encryptedKey : " + encryptedKey);
// var privateKey = ursa.createPrivateKey(fs.readFileSync('./privkey.pkc8.pem'));
// var decryptedKey = privateKey.decrypt(encryptedKey, "hex", "utf8");
// console.log("decryptedKey : " + decryptedKey);
var iv = randomstring.generate(12);
console.log("IV : " + iv);
var cipher = crypto.createCipheriv('aes-128-gcm', cek, iv);
cipher.setAAD(Buffer.from(ascii.toASCII(headerBase64Url)));
var chipherText = cipher.update(JSON.stringify(claims), "utf8", "base64");
chipherText += cipher.final('base64');
console.log("chipherText : " + chipherText);
var chipherTextAuthTag = cipher.getAuthTag().toString("base64");
console.log("chipherText Auth Tag : " + chipherTextAuthTag);
var jweToken = headerBase64Url + "." + base64url.encode(encryptedKey, "base64") + "." + base64url.encode(iv, "base64") + "." + base64url.encode(chipherText, "base64") +
"." + base64url.encode(chipherTextAuthTag, "base64");
console.log("jweToken : " + jweToken);
// decrypt
var jweTokenParts = jweToken.split(".");
var headerHex = base64url.decode(jweTokenParts[0]);
console.log(headerHex);
var encryptedKeyHex = base64url.decode(jweTokenParts[1], "base64");
console.log(encryptedKeyHex);
var ivHex = base64url.decode(jweTokenParts[2], "base64");
console.log(ivHex);
var chipperTextHex = base64url.decode(jweTokenParts[3], "base64");
console.log(chipperTextHex);
var chipherTextAuthTagHex = base64url.decode(jweTokenParts[4], "base64");
console.log(chipherTextAuthTagHex);
var privateKey = ursa.createPrivateKey(fs.readFileSync('./privkey.pkc8.pem'));
var decryptedKeyHex = privateKey.decrypt(encryptedKeyHex, "base64", "utf8");
console.log("decryptedKeyHex : " + decryptedKeyHex);
var dcipher = crypto.createDecipheriv('aes-128-gcm', decryptedKeyHex, iv);
dcipher.setAAD(Buffer.from(ascii.toASCII(jweTokenParts[0])));
dcipher.setAuthTag(Buffer.from(chipherTextAuthTagHex, "base64"));
var planText = dcipher.update(chipperTextHex, "base64", "utf8");
planText += dcipher.final('utf8');
console.log(planText);
ASCII.js
function toASCII(text) {
var ascii = "";
for (var f in text) {
ascii = ascii + text.charCodeAt(f);
}
return ascii;
}
module.exports = {
toASCII: toASCII
};
Generated public and private key using the below command
openssl genrsa -out ./privkey.pem 2048
openssl pkcs8 -topk8 -inform pem -in ./privkey.pem -outform pem -nocrypt -out ./privkey.pkc8.pem
openssl rsa -in ./privkey.pkc8.pem -pubout -out ./pubkey.pem
Please help me to fix this code.
This is my public key
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyT0HZHrlk8nN8HfTDq5t
dv6UCKHf7+RF1bICxaR4h2vzGCqcYUlzyW7Sp33BZAHDeO3d5tX26m7z2EOPaOPn
SSe6psgvBmE4Ivyc3+uyIYJm+Eo9bXiqqfvuDRidXsHj23w41l6GMERKbpOBVvp+
dmWt/cWU8FESvKUqNw/Au2R9mE1sQ5irMQj42hhUrVA1azs2AYpysKNZABm11YMb
/vd/xSPLsNqcDefuCs7j3CcT9xNLrMV6K63QjCAP+h0IMuA+ayi3WRUbl04D6cAC
AC97/cKMC0YLRumbf5x5/KjUBwNlzgRA3/n9KE+YjJ9Rs9dtiGnlg+c70Kgx4hm9
9QIDAQAB
-----END PUBLIC KEY-----
Generated JWE
eyJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.A_KMJqfr6FZSoejRGWPsZKMCNZmPyaWoNvpG6KMRpqyv7Alb8Ui5ELWLjpcaemjNM8EFU8d4-Yzz8jRRZ5TpK2pEEc4NXfDLcnj2b0-38_-P-0HbW1YyMkkGMVXIpJDYMo8vKgVHIBj0pNlzgF7xmxLFWZlJlXmYzXi4QZcig5HezHg7AAQB7U2HYry25cQDYam60747gRCH372NaSm_dfRCNvH8copVXqiJGNs6xhslxMt_LopnZt9iIcAC9o7m0FPdnu_0Ui_w0jp5OUam8i0v8k6SSajBvXSedtUENxcehPGRSFYzi8KqZ53u4CpRygir84wNFRTi7zmLV6TlVw.84xgyx6TTI8I.4zTt1fI1XCbvxW2L-pH8_Mfp_ySF.EPmpEHiMYAvA2nqz9M0v5Q
It looks like the IV is not correctly encoded using Base64 Url.
On my computer, when I execute the following line of code:
console.log(iv);
console.log(base64url.encode(iv, "base64"));
Then the two lines are identical.
When I modify your code:
var jweToken = headerBase64Url + "." + base64url.encode(encryptedKey, "base64") + "." + base64url.encode(iv, "base64") + "." + base64url.encode(chipherText, "base64") +
"." + base64url.encode(chipherTextAuthTag, "base64");
lnto these lines:
var bufferedIV = new Buffer(iv);
var jweToken = headerBase64Url + "." + base64url.encode(encryptedKey, "base64") + "." + base64url.encode(bufferedIV, "base64") + "." + base64url.encode(chipherText, "base64") +
"." + base64url.encode(chipherTextAuthTag, "base64");
Then it works fine ; I can load the resulting JWE using my PHP library.
From my understanding, the error comes from the base64url dependency that does not correctly encode the IV.
I am attempting to do a small PoC with PDFs and have run into an issue. I am looking to post a message to a PDF and have the PDF post a message to the browser.
The deets:
I am viewing the PDF in an "object" element in IE9. I am using itextsharp to prefill a pdf template on the server, inject some app level javascript (post message and on message stuff) and then serve that up to the browser via a filestreamresult. I am using Reader 10 to view the PDF in IE9.
What works:
So far, everything works except for the PDF posting a message to the browser. I can post a message to the PDF, from the browser, no problem and all of the fields are prefilled as desired.
What doesn't work:
When I try using this.hostContainer.postMessage(["something","somethingmore"]) I get an Acrobat Escript window that says "hostContainer is not defined". I have also tried using "event.target.hostContainer" but I get "event.target is not defined". I am at a loss of what to do and any insight would be super helpful.
Reference links:
Acrobat Javascript API
Stackoverflow How-To on this topic
Original guide I used
The code:
My form view:
<object id="pdfFrame" style="width:100%;height: 100%;" data="#Url.Action("LoadForm")">No luck :(</object>
My custom javascript string method:
private static string GetCustomJavascript(string existingJavaScript)
{
const string newJs =
"this.disclosed = true; " +
"if (this.external && this.hostContainer) { " +
"function onMessageFunc( stringArray ) { " +
// "var name = this.myDoc.getField(personal.name); " +
// "var login = this.myDoc.getField(personal.loginname); " +
"try{" +
"app.alert(doc.xfa);" +
"console.println('Doc xfa value = ' + doc.xfa);" +
// "event.target.hostContainer.postMessage(['hello from pdf!']);" +
// "this.hostContainer.postMessage(['hello from pdf!']);"+
// "name.value = stringArray[0]; " +
// "login.value = stringArray[1]; " +
"} catch(e){ onErrorFunc(e); } " +
"} " +
"function onErrorFunc( e ) { " +
"console.show(); " +
"console.println(e.toString()); " +
"} " +
"try {" +
"if(!this.hostContainer.messageHandler) { " +
"this.hostContainer.messageHandler = new Object(); " +
"this.hostContainer.messageHandler.myDoc = this; " +
"this.hostContainer.messageHandler.onMessage = onMessageFunc; " +
"this.hostContainer.messageHandler.onError = onErrorFunc; " +
"this.hostContainer.messageHandler.onDisclose = function(){ return true; }; " +
"}" +
"} catch(e){onErrorFunc(e);}" +
"}";
var jsToReturn = existingJavaScript + newJs;
return jsToReturn;
}
My method for filling and sending the form to the browser:
public MemoryStream GetFilledRequestForm(string fileDirectory, User user, FormView formView)
{
var pdfStream = new MemoryStream();
var templateFilePath = GetRequestTypeTemplateFilePath(fileDirectory, _requestModule.FormTemplateFileName);
var pdfReader = new PdfReader(templateFilePath);
// pdfReader.RemoveUsageRights();
var stamper = new PdfStamper(pdfReader, pdfStream);
var formFields = GetFormFields(user, formView, pdfReader);
foreach (var field in formFields.Where(f => f.Value != null))
{
stamper.AcroFields.SetField(field.Name, field.Value);
}
stamper.FormFlattening = false;
var newJs = GetCustomJavascript(stamper.Reader.JavaScript);
stamper.AddJavaScript("newJs", newJs);
stamper.Close();
byte[] byteInfo = pdfStream.ToArray();
var outputStream = new MemoryStream();
outputStream.Write(byteInfo, 0, byteInfo.Length);
outputStream.Position = 0;
return outputStream;
}
Ok, so I have resolved it, with some help of course. I found the key at this stack overflow post. I needed to wait for the object to load before assigning the message handler. Additionally, I needed a global variable in the pdf javascript to be able to post the message.
Html/Javascript: (the key here is the loadListener() function)
#model WebModel.FormView
<object id="pdfFrame" style="width:100%;height: 100%;" data="#Url.Action("LoadForm")">No luck :(</object>
<input id="buttonPost" type="button" value="post to pdf"/>
<script type="text/javascript">
var PDFObject = document.getElementById("pdfFrame");
function loadListener() {
if (typeof PDFObject.readyState === 'undefined') { // ready state only works for IE, which is good because we only need to do this for IE because IE sucks in the first place
debugger;
PDFObject.messageHandler = { onMessage: messageFunc };
return;
}
if (PDFObject.readyState == 4) {
debugger;
PDFObject.messageHandler = { onMessage: messageFunc };
} else {
setTimeout(loadListener, 500);
}
}
function messageFunc(data) {
debugger;
var messagedata = data;
alert('finally!!');
}
function sendToPdf() {
if(PDFObject!= null){
PDFObject.postMessage(
["a", "b"]);
}
}
$('#pdfFrame').ready(function() {
loadListener();
$('#buttonPost').on('click', function() {
sendToPdf();
});
});
</script>
My new function to create the javascript: (the key here is var appHostContainer)
private static string GetCustomJavascript(string existingJavaScript)
{
const string newJs =
"this.disclosed = true; " +
"var appHostContainer = this.hostContainer;" +
"if (this.external && this.hostContainer) { " +
"function onMessageFunc( stringArray ) { " +
// "var name = this.myDoc.getField(personal.name); " +
// "var login = this.myDoc.getField(personal.loginname); " +
"try{" +
"app.alert(stringArray);" +
"appHostContainer.postMessage(['hello from pdf!']);" +
// "name.value = stringArray[0]; " +
// "login.value = stringArray[1]; " +
"} catch(e){ onErrorFunc(e); } " +
"} " +
"function onErrorFunc( e ) { " +
"console.show(); " +
"console.println(e.toString()); " +
"} " +
"try {" +
"if(!this.hostContainer.messageHandler) { " +
"this.hostContainer.messageHandler = new Object(); " +
"this.hostContainer.messageHandler.myDoc = this; " +
"this.hostContainer.messageHandler.onMessage = onMessageFunc; " +
"this.hostContainer.messageHandler.onError = onErrorFunc; " +
"this.hostContainer.messageHandler.onDisclose = function(){ return true; }; " +
"}" +
"} catch(e){onErrorFunc(e);}" +
"}";
var jsToReturn = existingJavaScript + newJs;
return jsToReturn;
}
I am trying to compress and decompress the string using Zlib. Here is the JS file I'm using to compress and decompress.
Compression code:
compress_string = function () {
var string = document.getElementById("input_value").value;
var deflate = new Zlib.Deflate(string);
var compressed = deflate.compress();
var b64encoded = btoa(String.fromCharCode.apply(null, compressed));
var elem = document.getElementById("input_value");
elem.value = b64encoded;
var elemLabel = document.getElementById("zlsize");
elemLabel.value = ("Size of sample is: " + string.length) + " " + ("Compressed Value: " + b64encoded + " Size: " + b64encoded.length);
}
After compressing I'm setting the compressed value back to the input_value text field.
Decompression Code:
decompress_string = function () {
var string = document.getElementById("input_value").value;
var compressData = new Uint8Array(atob(string).split("").map(function(c) { return c.charCodeAt(0); }))
var inflate = new Zlib.Inflate(compressData);
var plain = inflate.decompress();
var elem = document.getElementById("input_value");
elem.value = btoa(plain);
var elemLabel = document.getElementById("zlsize");
elemLabel.value = ("Size of compressed string is: " + string.length) + " " + ("Decompressed Value: " + plain + " Size: " + plain.length);
}
I'm trying to compress below sample string:
<xml><username>myusername</username><password>mypassword</password></xml>
Size of sample is: 73
Compressed Value: eJxNibEJAAAMg/7/OjoEdCjGAoAnmqg6fF8T7QMfCxxR
Size: 44
When trying to decompress the above compressed string, I'm getting an object of Uint8Array as below:
Size of compressed string is: 44
Decompressed Value: [object Uint8Array]
Size: 70
While trying to convert the object Uint8Array to string using btoa(), the output is like below:
W29iamVjdCBVaW50OEFycmF5XQ==
Question: How to get the original string?
Your problem is text encoding.
Uint8Array is a binary representation of something, and strings can be written in many formats. You need to stick to one, and convert using that.
I've chosen UTF-8 in this example, using this library
function compress(input){
var binaryconverter = new TextEncoder('utf-8');
var binary = binaryconverter.encode(input);
var deflate = new Zlib.Deflate(binary);
var compressed = deflate.compress();
return btoa(String.fromCharCode.apply(null, compressed));
}
function decompress(b64encoded){
var compressed = new Uint8Array(atob(b64encoded).split("").map(function(c){return c.charCodeAt(0);}));
var inflate = new Zlib.Inflate(compressed);
var binary = inflate.decompress();
var binaryconverter = new TextDecoder('utf-8');
return binaryconverter.decode(binary);
}
var input = '<xml><username>myusername</username><password>mypassword</password></xml>';
var b64encoded = compress(input);
var output = decompress(b64encoded);
alert(output);
So, when encoding, I first convert the string to the binary representation of the text in UTF-8 format, then I'm using ZLib to compress, and then again this is converted to a base64 string for ease of transfer.
To decompress, you do the inverse thing: first decode the base64 string, then ZLib to inflate and finally again we convert binary to string using UTF-8
Documentation zlib.js appear to suggest plain (input) of type Array.<number> or Uint8Array
// plain = Array.<number> or Uint8Array
var deflate = new Zlib.Deflate(plain);
var compressed = deflate.compress();
at OP , var string appear to be type string , see
var string = document.getElementById("input_value").value;
var deflate = new Zlib.Deflate(string);
To retrieve the text value from compressed , base64 formatted string , below ; first , map var string to .charCodeAt() number , returning array of numbers representing text characters ; second , push .charCodeAt() numbers to map array ; third, call window.btoa(encodeURIComponent(escape(compressed[i]))) on each item within array of charCodeAt() values , pushed to same map array; fourth , decode base64encoded string in for loop , calling String.fromCharCode(plain[i]) on decompressed Uint8Array , returning original input string.
Try
var elem = document.getElementById("input_value")
, elemLabel = document.getElementById("zlsize")
, compress = document.getElementById("compress")
, decompress = document.getElementById("decompress")
, b64map = []
, _b64encoded
, b64encoded
, _string
, string
, _plain
, compressData;
function compress_string () {
string = elem.value;
_string = [].slice.call(string).map(function (value, key) {
return value.charCodeAt(0)
});
var deflate = new Zlib.Deflate(_string);
var compressed = deflate.compress();
for (var i = 0; i < compressed.length; i++) {
b64map.push([compressed[i]
, window.btoa(encodeURIComponent(escape(compressed[i])))])
};
_b64encoded = b64map.map(function (value, key) {
return value[1]
});
b64encoded = _b64encoded.join("");
elem.value = b64encoded;
elemLabel.innerText = ("Size of sample is: "
+ string.length) + " " + ("Compressed Value: "
+ b64encoded + " Size: " + b64encoded.length)
};
function decompress_string () {
string = elem.value;
elem.value = "";
compressData = _b64encoded.map(function (value, key) {
return new RegExp(value).test(string) ? b64map[key][0] : null
});
compressData = new Uint8Array(compressData);
var inflate = new Zlib.Inflate(compressData);
var plain = inflate.decompress();
b64map = b64encoded = [];
_plain = "";
for (var i = 0; i < plain.length; i++) {
_plain += String.fromCharCode(plain[i])
};
elem.value = _plain;
elemLabel.innerText = ("Size of compressed string is: "
+ elem.value.length) + " "
+ ("Decompressed Value: " + _plain + " Size: "
+ _plain.length);
};
compress.addEventListener("click", compress_string);
decompress.addEventListener("click", decompress_string);
jsfiddle http://jsfiddle.net/guest271314/ov6nwLak/
$.getScript("https://raw.githubusercontent.com/imaya/zlib.js/master/bin/zlib.min.js")
var elem = document.getElementById("input_value")
, elemLabel = document.getElementById("zlsize")
, compress = document.getElementById("compress")
, decompress = document.getElementById("decompress")
, b64map = []
, _b64encoded
, b64encoded
, _string
, string
, _plain
, compressData;
elem.value = "<xml><username>myusername</username><password>mypassword</password></xml>";
function compress_string () {
string = elem.value;
_string = [].slice.call(string).map(function (value, key) {
return value.charCodeAt(0)
});
var deflate = new Zlib.Deflate(_string);
var compressed = deflate.compress();
for (var i = 0; i < compressed.length; i++) {
b64map.push([compressed[i]
, window.btoa(encodeURIComponent(escape(compressed[i])))])
};
_b64encoded = b64map.map(function (value, key) {
return value[1]
});
b64encoded = _b64encoded.join("");
elem.value = b64encoded;
elemLabel.innerText = ("Size of sample is: "
+ string.length) + " " + ("Compressed Value: "
+ b64encoded + " Size: " + b64encoded.length)
};
function decompress_string () {
string = elem.value;
elem.value = "";
compressData = _b64encoded.map(function (value, key) {
return new RegExp(value).test(string) ? b64map[key][0] : null
});
compressData = new Uint8Array(compressData);
var inflate = new Zlib.Inflate(compressData);
var plain = inflate.decompress();
b64map = b64encoded = [];
_plain = "";
for (var i = 0; i < plain.length; i++) {
_plain += String.fromCharCode(plain[i])
};
elem.value = _plain;
elemLabel.innerText = ("Size of compressed string is: "
+ elem.value.length) + " "
+ ("Decompressed Value: " + _plain + " Size: " +
_plain.length);
};
compress.addEventListener("click", compress_string);
decompress.addEventListener("click", decompress_string);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="input_value" />
<button id="compress">compress</button>
<button id="decompress">decompress</button>
<br />
<label id="zlsize"></label>
I'm using the below code in javascript for downloading or uploading a file from network.
$(document).ready(function DirectoryCopy(sourceDirName, destDirName, copySubDirs, test) {
debugger;
try {
var dir = new System.IO.DirectoryInfo.ctor(sourceDirName);
var directory_stop = dir.get_Name();
var dirs = dir.GetDirectories();
if (!dir.get_Exists()) {
throw $CreateException(new System.IO.DirectoryNotFoundException.ctor$$String("Source directory does not exist or could not be found: " + sourceDirName), new Error());
}
if (!System.IO.Directory.Exists(destDirName)) {
System.IO.Directory.CreateDirectory$$String(destDirName);
}
if (test == true) {
System.IO.Directory.CreateDirectory$$String(destDirName + "\\" + "Complete");
}
var files = dir.GetFiles();
for (var $i2 = 0, $l2 = files.length, file = files[$i2]; $i2 < $l2; $i2++, file = files[$i2]) {
var temppath = System.IO.Path.Combine$$String$$String(destDirName, file.get_Name());
file.CopyTo$$String$$Boolean(temppath, true);
}
if (copySubDirs) {
for (var $i3 = 0, $l3 = dirs.length, subdir = dirs[$i3]; $i3 < $l3; $i3++, subdir = dirs[$i3]) {
var temppath = System.IO.Path.Combine$$String$$String(destDirName, subdir.get_Name());
DirectoryCopy(subdir.get_FullName(), temppath, copySubDirs, false);
}
return dirs.length;
}
return files.length;
}
catch (ex) {
var path = "d:\\tempnew\\MyTest.txt";
var sw = System.IO.File.CreateText(path);
try {
sw.WriteLine$$String(ex.toString());
}
finally {
sw.Dispose();
}
return 0;
}
});
But I am getting an error on
var dir = new System.IO.DirectoryInfo.ctor(sourceDirName);
as "System is not defined"
I'm passing values from code behind as shown below.
TextBox1.Text = #"\" + "\\10.66.3.82" + #"\" + "ipadqc" + #"\" + "IPAD Titles" + #"\" + JobName.Text + #"\" + Issue.Text;
string Macid = (string)(Session["Name"]);
string path = "D:" + #"\" + "Ipad Download" + #"\" + Macid + #"\" + Process.Text + #"\" + JobName.Text + #"\" + Issue.Text;
string a;
ClientScript.RegisterStartupScript(typeof(Page), "script", a = "DirectoryCopy('" + TextBox1.Text + "','"+path+"', true, true);", true);
please correct me if i'm wrong or please let me know if there is any better option to do it.
System.IO is a .Net thing, not a javascript thing.
For downloading files using JS, there are plenty or questions like this on Stack Overlow already. like this one
As far as uploading goes, the top answer on this question pretty much sums it up.
Using Adobe PhotoShop CS4 scripting, JavaScript provides the File and Folder classes, but I do not see how I can use these classes from VBScript.
Currently I use the DoJavaScript function like this:
Set appRef = CreateObject("Photoshop.Application")
jsCode = Array(_
"var inFolder = Folder.selectDialog('Select a folder to process');",_
"if(inFolder != null){",_
" var fileList = inFolder.getFiles(/\.(jpg|jpeg|tif|)$/i);",_
" var outFolder = new Folder(decodeURI(inFolder) + '/Edited');",_
" if (outFolder.exists == false) outFolder.create();",_
" for(var i = 0 ;i < fileList.length; i++){",_
" var doc = open(fileList[i]);",_
" doc.flatten();",_
" var docName = fileList[i].name.slice(0,-4);",_
" var saveFile = new File(decodeURI(outFolder) + '/' + docName + '.png');",_
" SavePNG(saveFile);",_
" activeDocument.close(SaveOptions.DONOTSAVECHANGES);",_
" }",_
"}",_
"function SavePNG(saveFile){",_
" pngSaveOptions = new PNGSaveOptions();",_
" pngSaveOptions.embedColorProfile = true;",_
" pngSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;",_
" pngSaveOptions.matte = MatteType.NONE;",_
" pngSaveOptions.quality = 1;",_
" pngSaveOptions.PNG8 = false;",_
" pngSaveOptions.transparency = true;",_
" activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);",_
"}")
appRef.DoJavaScript(Join(jsCode, vbNewLine))
My question is: Can I use the Folder and File classes directly from my VB script?
Something like:
Set psFolder = appRef.Folder
inputFolder = psFolder.selectDialog("Select a folder to process")
When I try this, appRef.Folder returns this error:
Object doesn't support this property or method
In VBscript, you can access folder with the FileSystemObject:
'1.a - user browse for folder
Set objShell = CreateObject( "Shell.Application" )
Set objFolder = objShell.BrowseForFolder( 0, "Select Folder", 0, myStartFolder )
'1.b - or use a fixed one
sFolder = "C:\foo\anyFolder\"
Set fs = CreateObject("Scripting.FileSystemObject")
Set objFolder = fs.GetFolder(sFolder)
'parse the content of the folder
Set oChildren = objFolder.SubFolders
ReDim aList(oChildren.Count)
For i = 1 To oChildren.Count
aList(i) = oChildren.Item(i).Name
Next