Search for file using string plus regex - Javascript - javascript

I've been writing a script that lets the user press a button three times, once the three times are up the button is to be greyed out and unclickable. I've made it so that the button cannot be clicked (using VBScript) but I want to use Javascript to also grey out at that point.
What I want to do is have javascript search for a file on the users local drive "C:/sys/" and if that file exists then grey out the button.
The issue that I having is that the only part of the file name that I know will be correct is the last two characters "-3" the beginning of the file name could be any amount of alphanumeric characters. I thought I could use a regex to find the file but I have no idea how to get the script to search for the file using the directory path + the regex. Example for the code:
function checkfile()
{
var fileLocation = "C:/sys/"
var regex = new RegExp('\w+\-3');
if(fso.FileExists(fileLocation + regex)) {
alert("File found successfully");
} else {
alert("File not found.");
}
}
window.onload = checkfile;
I thought that might work but thinking about it makes me wonder if that script is actually searching for a file called "C:/sys/\w+-3" literally rather than using the regex.
Bare in mind that this is part of a much larger script so "fso" is already defined using Set fso = CreateObject("Scripting.FileSystemObject") in VBScript.
The whole code can be found here
<script language="VBScript">
Set objShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
System = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System\"
DisableTaskMgr
dim currentDir : currentDir = objShell.CurrentDirectory 'Finds the scripts current directory'
'TO DO: Check whether UserName method below can be used over network'
UserName = objShell.ExpandEnvironmentStrings("%USERNAME%") 'Grabs the username of the current user'
pathToConfig = currentDir & "/config.ini"
pathToKeyFile = "C:/sys/"
'Gets the current version number from config file'
If fso.FileExists(pathToConfig) Then 'Makes sure that the config file exists'
Set ConfigFile = fso.GetFile(pathToConfig) 'Config file contains only the version number'
If ConfigFile.Size > 0 Then 'This makes sure that there is a version number set inside the config file'
Set versionFile = fso.OpenTextFile(pathToConfig, 1)
Version = versionFile.ReadAll
Else
EnableTaskMgr
window.close 'If config file cannot be reached then the script will end prematurely and will be shown next time the user logs in once the config file can be reached.'
End If
Else
window.close
End If
On Error Resume Next
versionFile.close
'Searches C:/sys/ for keyfile'
If fso.FileExists(pathToKeyFile & Version) Then
EnableTaskMgr
window.close
Else
End If
sub Postpone
ChkOne = pathToKeyFile & Version & "-1"
ChkTwo = pathToKeyFile & Version & "-2"
ChkThree = pathToKeyFile & Version & "-3"
If fso.FileExists(ChkThree) Then
'Placeholder code'
MsgBox "Maximum number of Postpone attempts used. You must now choose to either Accept or Decline the Policy."
ElseIf fso.FileExists(ChkTwo) Then
'Delete file ChkTwo - Create file ChkThree'
fso.DeleteFile(ChkTwo)
Set objFile = fso.CreateTextFile(ChkThree)
window.close
ElseIf fso.FileExists(ChkOne) Then
'Delete file ChkOne - Create file ChkTwo'
fso.DeleteFile(ChkOne)
Set objFile = fso.CreateTextFile(ChkTwo)
window.close
Else
'Create file ChkOne'
Set objFile = fso.CreateTextFile(ChkOne)
window.close
End If
end sub
sub DisableTaskMgr
objShell.RegWrite System, "REG_SZ"
objShell.RegWrite System & "/DisableTaskMgr", 1, "REG_DWORD"
end sub
sub EnableTaskMgr
objShell.RegWrite System, "REG_SZ"
objShell.RegWrite System & "/DisableTaskMgr", 0, "REG_DWORD"
end sub
sub Logon 'Method only runs when user clicks "I Accept"'
On Error Resume Next
Call EnableTaskMgr
If Not (fso.FileExists(currentDir & "/store/" & LCase(UserName) & ".csv")) Then
On Error Resume Next
Set objFile = fso.CreateTextFile(currentDir & "/store/" & LCase(UserName) & ".csv", True)
objFile.close
Else
End If
Set objCSVFile = fso.OpenTextFile(currentDir & "/store/" & UserName & ".csv", 2, True)
objCSVFile.Write(UserName & "," & Now & "," & Version)
objCSVFile.Close
On Error Resume Next
fso.CreateTextFile("C:/sys/" & Version)
window.close
end sub
sub Logoff 'Method only runs when user clicks "I Decline"'
objShell.Run "shutdown /l"
end sub
</script>
<script type="text/javascript">
function checkfile()
{
var fileLocation = "C:/sys/"
var regex = new RegExp('\w+\-3');
if(fso.FileExists(fileLocation + regex)) {
alert("File found successfully");
} else {
alert("File not found.");
}
}
window.onload = checkfile;
</script>

Related

When downloading a zip file in classic asp, I am getting 'file is being used by another process error'

I am working on classic asp with vbscript application.
Requirement:
Consolidate files in a server folder to a zip file and download it. This should happen in a single button click.
What I have achieved:
I have a button called 'Consolidate Files' that when clicked opens a window pop up with 'Download' and 'Close' button. When clicking on 'Download' button a prompt to save the file is shown and user can open, save or save as the file.
Code I used:
x.asp
<input type="button" value="Consolidate Files" id='btn_consolidated' >
<script type="text/javascript">
$('#btn_consolidated').click(function(){window.open('y.asp?id=<%=id%>&dothis=Consolidate',"DownloadWindow", "width=500,height=300")});
</script>
y.asp
dothis = Request("dothis")
Select Case dothis
Case "Consolidate"
id = Request("id")
Dim userId, Code
Dim filename1,location1,query,rs1,Zip
userId = Session("UserId")
Dim fs, f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set zip = new aspZip
'location1 = "..\doc\Files\["+userId+"]-"+id
location1 = dirdefault+"TempUserFiles\"
if not fs.FolderExists(location1) then
fs.CreateFolder(location1)
end if
query="select Filename,Location, Code from files f where id=" + id + " "
Set rs1 = conn.Execute(query)
Code = rs1("Code")
location1 = location1 + "["+userId+"]-"+rs1("Code")
'on error resume next
if fs.FolderExists(location1) then
fs.DeleteFolder(location1)
end if
fs.CreateFolder(location1)
'If Err.Number <> 0 Then
' Response.Write(location1)
'return
'End if
'All files in dirdefault + rs1("location") path is added to a zip file
zip.OpenArquieve(location1+"\"+Code +".zip")
do while not rs1.Eof
f = fs.GetFile(dirdefault + rs1("location"))
zip.Add(f)
rs1.MoveNext
'f.close
Loop
zip.CloseArquieve()
rs1.close
set zip = nothing
set fs = nothing
set f = nothing
Session("fileLocation") = location1+"\"+Code +".zip"
Response.redirect "Download.asp?id="+id
Case "Download"
Dim userFolder
location1 = Session("fileLocation")
set zip = nothing
set fs = nothing
set f = nothing
Set objUpload = Server.CreateObject("Persits.Upload")
if objUpload.FileExists(location1) then
objUpload.SendBinary location1', true, "application/octet-stream", true ' this is line 483 where error is throwing
'response.write "file exists"
else
Response.redirect "fileNotFound.asp?id=" + idFile
end if
set objUpload.ActiveConnection = Nothing
set objUpload = nothing
Download.asp
id = Request("id")
Dim userId, Code, objUpload
Dim filename1,userFolder, location1,query,rs1,Zip
userId = Session("UserId")
Dim fs, f
query="select top 1 Code from MainTable er where er.id = " + id
Set rs1 = conn.Execute(query)
Code= rs1("Code")
%>
<html>
<head><title>Download document</title>
<link rel="stylesheet" type="text/css" href="../css/styles.css" title="dcsStyle">
<script language="JavaScript" src="../scripts/jquery-1.9.1.min.js"></script>
<script language="JavaScript">
$(document).ready(function(){
$('#btn_back').click(function () { self.close() });
$('#btn_Download').click(function () { location = 'y.asp?id=<%=id%>&dothis=Download'; });
});
</script>
</head>
<body>
<h1> Consolidated files download for <%=Code%></h1>
<br />
<input type ="button" id="btn_Download" value="Download" /> <input type='button' id='btn_back' value='Close' />
Working:
x.asp is my main page where I have the button 'Consolidate Files'. When this button is clicked, the consolidation of files to a single zip file happens in y.asp under case "Consolidate". Here a new folder is created for each unique 'Code' number and all files taken from a server location is added into a zip file and saved in the new folder that was created.
When the user clicks on 'Download' button in the popup window, the case 'Download' in y.asp works where the zip file that was created in the previous step is available to the user to save to their local drive.
Problem:
in y.asp under case "Download", I am getting the following error at
objUpload.SendBinary location1', true, "application/octet-stream", true
The error is inconsistent and does not occur all the time. Sometimes, no matter what I do, the error persists even after multiple trials to download the file. Also, the case "Condolidate" functionality always works smoothly and a fresh file is created each time. Any help would be appreciated.
Error:
Technical Information (for support personnel) •Error Type:
Persits.Upload.1 (0x800A001A) The process cannot access the file
because it is being used by another process. /myapp/pr/y.asp, line
483

Adobe don't run script after PDF is re-opend

Below is my code in Java script for adobe acrobat. How do I set my PDF, so the script will always work during printing process? At the moment when I close the document and re-open the code is not executed unless I re-open javaScript "Set Documents Actions" window..
The code works well and its set to run when "document will print"
I need it to be automated. To always execute when a user tries to print it.
// Add Watermark ON PRINT Var. Watermark "YES"
var docwtrmrk = this.info.Watermark; // get Watermark variable value : this.info.<Any EPDM Variable can be used as ref.>
var docRev = this.info.Revision; // Get Revision variable Value : this.info.<Any EPDM Variable can be used as ref.>
var cMyText = "NOT APPROVED!!! FOR REFERENCE ONLY" + "\n Printed on: " + util.printd("dd.mm.yyyy # HH:MM", new Date) + "\n REVISION NO.: " + docRev;
if (docwtrmrk == "Yes") {
// Yes, adds watermark
this.addWatermarkFromText({
cText: cMyText,
nTextAlign:app.constants.align.center,
cFont: "Helvetica-Bold",
nScale: 1,
aColor: color.red,
nRotation: 45,
nOpacity: 0.5,
bOnScreen: true,
});
app.alert("You are about to print NOT APPROVED Docuement \n Double check with engineering and Document controler \n USE FOR REF. ONLY", 1);
}
else {} // Dont add watermark

In ASP with VB codebehind how do I present the user a yes/no dialog from VB

I have the following case where a user has selected a product, the product record has been retrieved and the backorder flag is set. I want to ask the user if the want to include it in the order anyway. I can't seem to find an exaample anywhere that demonstrates it in an IF statement.
My VB Code Snippet:
Dim backorder = myDataTable.Rows(0)("backorder").ToString()
If backorder = "True" And <somehow ask user it they want to order anyway> Then
'do something
End If
My Javascript in aspx file:
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Selected item is on temporary back order. Do yuou want to include it on this order?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
I can read the variable being added, by javascript, to the page from VB, but can't figure how to call the javascript in order to prompt the user.
For some reason I can't get my head around this. Please advise with example.
Use the RegisterStartupScript method:
Sub ProcessOrder()
'Your code to process the selected products here...
Dim orderAnyway As string = hdnConfirmResponse.Value.Trim()
If selectedItem.BackOrdered Then
If orderAnyway = "" Then
Dim cs As ClientScriptManager = Page.ClientScript
' Define the name and type of the client scripts on the page.
Dim csname1 As String = "ConfirmScript"
Dim cstype As Type = Me.GetType()
' Check to see if the startup script is already registered.
If (Not cs.IsStartupScriptRegistered(cstype, csname1)) Then
Dim cstext1 As String = "Confirm();"
cs.RegisterStartupScript(cstype, csname1, cstext1, True)
End If
Else
If orderAnyway = "yes" Then
'ADD THE BACKORDERED ITEM SINCE THEY CONFIRMED
End If
End If
End If
End Sub
I hate answering my own question but this what finally worked. Mixture of mjw's answer and more research on my javasvript attempt. Rather than have JS create the hidden field, I added it to the HTML
<asp:HiddenField runat="server" id ="confirm_value"/>
New VB:
If myDataTableFrame.Rows.Count > 0 Then
Dim backorder = myDataTableFrame.Rows(0)("backorder").ToString()
If backorder = "True" And confirm_value.Value <> "Yes" Then
Dim cs As ClientScriptManager = Page.ClientScript
' Check to see if the startup script is already registered.
If (Not cs.IsStartupScriptRegistered(Me.GetType(), "ConfirmScript")) Then
Dim cstext1 As String = "Confirm();"
cs.RegisterStartupScript(Me.GetType(), "ConfirmScript", "Confirm();", True)
End If
Return
Else
confirm_value.Value = "No"
...
New Javascript:
See ASP.NET set hiddenfield a value in Javascript Also added a reclick of the button if they answered "OK"
<script type = "text/javascript">
function Confirm() {
if (confirm("Selected item is on temporary back order. If you want to include it on this order click OK, then resubmit it?")) {
//had to resort to this to find hidden field rather than document.getElementById('confirm_value')
var x = document.getElementById('<%= confirm_value.ClientID%>');
x.value = 'Yes';
//re-click the button
document.getElementById('<%=bttnadd.ClientID%>').click();
} else {
var x = document.getElementById('<%= confirm_value.ClientID%>');
x.value = 'No';
}
}
</script>

Error in editing a local xml file from a static HTML page using javascript

I am having a static html page on local storage(hard disk drive). I am not using any kind of server here. Along with this I have an xml file named testng.xml which I need to edit from html on button click using javascript.
I need to replace the <include> tag with <exclude> tag or vice versa based on user selection through a checkbox on web page. And then execute the testng xml by a button click.
The function is called from the html button as below
<input type="submit" onclick="editTestNG()" value="Execute Selected Tests">
Given below is my code for editing the xml.
<script type="text/javascript">
function editTestNG()
{
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "testng.xml", false);
xmlHttp.send();
xmlDoc = xmlHttp.responseXML;
txt = "";
x = document.getElementsByName("check");
document.write(x.length + "<br>"); // x.length is number of checkboxes on html page
z = xmlDoc.getElementsByTagName("run")[1];
y = z.children;
document.write(y.length + "<br>"); // y.length is the number of xml child nodes
document.write(x.length + "<br>"); // x.length is number of checkboxes on html page
for(i=0;i<x.length;i++)
{
document.write("abc");
if(x[i].type == 'checkbox')
{
document.writeln("def");
if(x[i].checked == "true" && y[i].nodeName == "exclude")
{
document.writeln("ghi");
txt = y[i].getAttribute("name");
newTag = xmlDoc.createElement("include");
newTag.setAttribute("name",txt);
p = z.replaceChild(newTag, y[i]);
document.write(p.nodeName+"<br>")
document.write(newTag.nodeName + "::"+ newTag.getAttribute("name")+"<br>");
}
if(x[i].checked == "false" && y[i].nodeName == "include")
{
document.writeln("jkl");
txt = y[i].getAttribute("name");
newTag = xmlDoc.createElement("exclude");
newTag.setAttribute("name",txt);
p = z.replaceChild(newTag, y[i]);
document.write(p.nodeName+"<br>")
document.write(newTag.nodeName + "::"+ newTag.getAttribute("name")+"<br>");
}
}
}
y = z.children;
for(i=0;i<y.length;i++)
{
document.writeln("<br>"+y[i].nodeName + " ## "+ y[i].getAttribute("name")+"<br>");
}
}
</script>
The output on html page after clicking the button is as below
140
7
0
exclude ## Group_CCMS_Login
exclude ## Group_CCR_Create_New
exclude ## Group_CCR_Create_New_EngType_M
exclude ## Group_CCR_Create_New_EngType_P
exclude ## Group_Full_ID_Search
include ## Group_Run_Query
exclude ## Group_Dup_Undup
I am able to retrieve the xml file and elements in the z and y variables. Also in the 2nd for loop, the output containing xml node names and attributes is printed. But after getting xml data in y variable, I am not able to get or use any html page elements such as checkboxes.
The value of x.length is 140 initially and y.length is 7, but then x.length becomes 0 and my 1st for loop does not execute.
I am unable to understand why I can't access html elements after getting xml data.
I never tried but as per my understanding you can create a bash file and then exucute that bash file using jsp code. Add that jsp code in the HTML.
Refer:-
executing a bash script from a jsp page
Now as you said "I need to prepare a user interface in HTML with checkboxes to select or deselect the tests to run and execute them with click of a button"
For that may you need to create different testng suite and accordingly you need to create a more bash respectively.
Refer:-
http://grokbase.com/t/gg/selenium-users/139r0nszp3/how-to-run-multiple-xml-files-with-testng

Error: The value of the property 'warn_redirect' is null or undefined, not a Function object

I have a page in one of my ASP.NET applications (VB) that relies on a 3rd party service being live, and I'm using jQuery to display an overlay if this service is found to be down. I've been using the same approach for other warnings in the app - the difference with this one is that it needs to redirect after the user clicks the button on the warning popup to remove the overlay. For some reason I'm getting the error "Error: The value of the property 'warn_redirect' is null or undefined, not a Function object."
Any assistance is greatly appreciated! My code follows:
jQuery
function warn_redirect(msg, title, nextpage) {
// show modal div
//alert(obj.id);
$("html").css("overflow", "hidden");
$("body").append("<div id='popup_overlay'></div><div id='popup_window'></div>");
$("#popup_overlay").addClass("popup_overlayBG");
$("#popup_overlay").fadeIn("slow");
// build warning box
$("#popup_window").append("<h1>" + title + "</h1>");
$("#popup_window").append("<p id='popup_message'><center>" + msg + "</center></p>");
$("#popup_window").append("<div class='buttons'><center><button id='continue' class='positive' type='submit'>OK</button></center></div>");
// attach action to button
$("#continue").click(popup_remove_redirect(nextpage));
// display warning window
popup_position(400, 300);
$("#popup_window").css({ display: "block" }); //for safari using css instead of show
$("#continue").focus();
$("#continue").blur();
}
function popup_remove_redirect(nextpage) {
$("#popup_window").fadeOut("fast", function () { $('#popup_window,#popup_overlay').trigger("unload").unbind().remove(); });
$("body", "html").css({ height: "auto", width: "auto" });
$("html").css("overflow", "");
window.location.href = nextpage;
}
Here is the VB.NET calling code:
If Status = "DOWN" Then
Dim clsUtility As New Utility
clsUtility.Emailer("email#company.com", "email#company.com", "", "", "The Service Is Down!", "Please investigate")
Dim ScriptString As String = "<script language='javascript'>"
ScriptString += "warn_redirect('Some warning message.', 'Warning', 'AnotherPage.aspx');"
ScriptString += "</script>"
ClientScript.RegisterStartupScript(Me.GetType, "warnscript", ScriptString)
'Response.Redirect("AnotherPage.aspx?ID=" & Session("SelKey") & "&UN=" & Header1.UserNumber) //this didn't work either
End If
Try this,
If Status = "DOWN" Then
Dim clsUtility As New Utility
clsUtility.Emailer("email#company.com", "email#company.com", "", "", "The Service Is Down!", "Please investigate")
Dim ScriptString As String = "<script language='javascript'>"
ScriptString += "window.onload = function(){warn_redirect('Some warning message.', 'Warning', 'AnotherPage.aspx');};"
ScriptString += "</script>"
ClientScript.RegisterStartupScript(Me.GetType, "warnscript", ScriptString)
'Response.Redirect("AnotherPage.aspx?ID=" & Session("SelKey") & "&UN=" & Header1.UserNumber) //this didn't work either
End If
As JQuery is already included, you can also use the below statement instead.
ScriptString += "$(function(){warn_redirect('Some warning message.', 'Warning', 'AnotherPage.aspx');});"
This is because the definition of your script is loaded after the StartupScript is invoked.
You have to include your .js file before the StartupScripts in your page. Look at the "source code" in your browser, and you'll see a bunch of script tags like this:
<script src="/ScriptResource.axd?d=eoXLgy ... 847d" type="text/javascript"></script>
These tags are the scripts inserted as StartUp scripts. Make sure your script is inserted before this in your .aspx (or .master). Perhaps you'll have to include them in the head tag.
By the way, creating a global function, like you warn_redirect, it's not a good practice. You should, at least, namespace it like this:
window.MyFunctions = {
warn_redirect = function (msg, title, nextpage) { /* your code */ }
}
And call it like this: MyFunctions.warn_redirect.
In this way, you have it better organized, and avoid possible collisions with other functions with the same name.

Categories