Server.Execute Duplicates Dynamic Content - loops

I created a page in ASP that loads dynamic content with code similar to this:
<%
var1 = int(rnd * 5) + 1
var2 = int(rnd * 10) + 1
%>
<html>
<body>
what variable 1 is: <%=var1%>
what variable 2 is: <%=var2%>
</body>
</html>
Then I have another page that uses Server.Execute to execute the previous file mentioned 2+ times using a loop. The code looks like this:
<% filename = request.querystring("page") %>
<table class="domtable">
<% for j = 1 to 2%> <%qnumb = qnumb + 1%>
<tr>
<td align="left">
<%server.execute (filename)%>
<% If qnumb < 2 then%>
<br/><hr><br/>
<%end if%>
</td></tr>
<%next%>
</table>
So for the last couple of months this has been working perfectly for me, loading different numbers for both variables on the two separate executions. Then today, I duplicated a folder on my server, renamed it and now magically, the variables are the same number about 9 out of 10 times the browser is refreshed.
This happened to me with the same files on my second server a month ago, and I had to delete all the files off of the second server, and download them from my first server (the one duplicating now), then upload them back and that fixed it. Unfortunately, I didn't download the entire server contents of my first server so I'm unable to reverse the process. So I'm not sure if this issue is server-side, or if it's related with the code I'm writing? I just don't know why it would work for so long then just stop working out of nowhere.
I've tried using meta no-cache controls. I deleted the new folder I duplicated earlier from the server and that didn't work. I also tried deleting files from the last couple days that have been uploaded and that didn't work either. I've tried loading 'filename' as an array such as:
filename(1) = request.querystring("page")
filename(2) = request.querystring("page")
for j = 1 to 2
Server.Execute(filename(j))
next
I really hope someone knows what I'm doing wrong here.
-EDIT-
I'm also doing this and getting the same results.
<%
'rnd.asp'
pStr = "private, no-cache, must-revalidate"
Response.ExpiresAbsolute = #2000-01-01#
Response.AddHeader "pragma", "no-cache"
Response.AddHeader "cache-control", pStr
server.execute ("rndj.asp")
response.write ("<hr>")
randomize(3)
server.execute ("rndj.asp")
%>
<%
'rndj.asp'
pStr = "private, no-cache, must-revalidate"
Response.ExpiresAbsolute = #2000-01-01#
Response.AddHeader "pragma", "no-cache"
Response.AddHeader "cache-control", pStr
randomize
response.write rnd
response.write "<br>"
response.write rnd
%>
I started to use this code below which looks at the specified file as plain text and removes the asp tags from it then uses Execute to run it within the original file. The problem with this is all my pages that i call use in them for other resources and the replace script wont let me add asp tags around the include lines.
<%
Dim sTargetFile, sTargetFileContents
Dim oFSO, sContents
Function GetFileContentsForExecution(sTargetFile)
'Obtain a reference to the FileSystemObject
Set oFSO = Server.CreateObject("Scripting.FileSystemObject")
'Obtain the file contents
sContents = oFSO.OpenTextFile(Server.MapPath(".") & "\" & sTargetFile).ReadAll
Set oFSO = Nothing 'reference to the FileSystemObject
'Remove the ASP scripting tags
rand = int(rnd * 2)
sContents = Replace (sContents, "<" & "%", "")
sContents = Replace (sContents, "%" & ">", "")
GetFileContentsForExecution = sContents
End Function
sTargetFile = "rndj.asp"
for j = 1 to 6
'Get the contents of the file to execute
sTargetFileContents = GetFileContentsForExecution(sTargetFile)
Execute sTargetFileContents
next
if j < 3 then
response.write ("<br/><hr><br/>")
end if
%>

Link to working solution
<%
'rnd.asp'
randomize
application("randomseed") = rnd
server.execute ("rndj.asp")
application("randomseed") = rnd
server.execute ("rndj.asp")
%>
<%
'rndj.asp'
randomize application("randomseed")
response.write rnd
response.write("<br />")
response.write rnd
response.write("<br />")
response.write("<br />")
%>

Related

VBA Access parsing JSON nested array

I am using VBA Access to get data from Google Books for a library database. The code is based on that given in this stackoverflow question.
I am struggling for the right code to allow for a varying number of authors as the information is in a nested array. I would like all of the author names to appear in one TextBox.
I tried:
Form_AddAmendItems.AuthorTextBox.Value = Join(subitem("authors"), ",")
from the link above but that fails to find any result.
I think I need to use UBound and LBound to count the number of authors and then loop through and add each one. But I haven't been able to find an example of how to do that.
Currently as a workaround I can populate the AuthorTextBox with the names of up to 3 authors, which is enough for my needs. But if there are less than 3 authors the error handler message pops up because it hasn't been able to find the requested data.
I am using the VBA-JSON Converter from here.
This is the JSON I would like to parse (from here)
{
"kind": "books#volumes",
"totalItems": 1,
"items": [
{
"kind": "books#volume",
"id": "BT2CAz-EjvcC",
"etag": "6Z7JqyUtyJU",
"selfLink": "https://www.googleapis.com/books/v1/volumes/BT2CAz-EjvcC",
"volumeInfo": {
"title": "Collins Gem German Dictionary",
"subtitle": "German-English, English-German",
"authors": [
"Veronika Calderwood-Schnorr",
"Ute Nicol",
"Peter Terrell"
]
And this is my VBA code:
Private Sub FindBookDetailsButton_Click()
'Error handle for Null Strings
If IsNull(Me.ISBNTextBox) = True Then
MsgBox "Item ID not specified.", vbExclamation + vbOKOnly, "Error"
Exit Sub
End If
'Error message if there is no match
On Error GoTo ErrMsg
Dim http As Object, JSON As Object, i As Integer, subitem As Object
Dim ISBN As String
ISBN = CStr(Me.ISBNTextBox.Value)
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://www.googleapis.com/books/v1/volumes?q=isbn:" & ISBN, False
http.send
Set JSON = ParseJSON(http.responseText)
For Each item In JSON("items")
Set subitem = item("volumeInfo")
Form_AddAmendItems.TitleTextBox.Value = subitem("title")
Form_AddAmendItems.AuthorTextBox.Value = subitem("authors")(1)
Form_AddAmendItems.PublisherTextBox.Value = subitem("publisher")
'For multiple authors
Set subitem = item("volumeInfo")
If subitem.Exists("authors") Then
For Each item2 In subitem("authors")
Form_AddAmendItems.AuthorTextBox.Value = subitem("authors")(1) & ", " & subitem("authors")(2)
Next
For Each item3 In subitem("authors")
Form_AddAmendItems.AuthorTextBox.Value = subitem("authors")(1) & ", " & subitem("authors")(2) & ", " & subitem("authors")(3)
Next
End If
Next
'To end with success
MsgBox ("Process complete"), vbInformation
Exit Sub
'To end with an error message
ErrMsg:
MsgBox ("No match obtained"), vbCritical
End Sub
An array or collection or dictionary can be looped without knowing that object's limits. So if subitem("authors") is one of those object types, your code could be something like (essentially the code shown in accepted answer for the SO link in your question):
Set subitem = item("volumeInfo")
Form_AddAmendItems.TitleTextBox.Value = subitem("title")
Form_AddAmendItems.PublisherTextBox.Value = subitem("publisher")
If subitem.Exists("authors") Then
For Each item2 In subitem("authors")
sA = sA & item2 & ","
Next
sA = Left(sA, Len(sA) - 1) 'remove trailing comma
If sA <> "" Then Form_AddAmendItems.AuthorTextBox.Value = sA
End If
I discovered that elements in the ISBN download aren't always the same. As an example, with ISBN 0-575-05577-4 the publisher is not provided even though publishedDate is. Might use an If Then condition for each element you want to explicitly address. As a side note, found it interesting that the co-author for that book was not included.

Replace Number Strings in Text File

I need a code in VBScript or batch to replace 5 Caracters (the bold numbers below) in a line of a text file to change ports numbers.
change_port.vbs:
prefsFile = "%userprofile%\Desktop\teste.msrcincident"
prefsFile = CreateObject("WScript.Shell").ExpandEnvironmentStrings(prefsFile)
newPrefs = "5500"
Set fso = CreateObject("Scripting.FileSystemObject")
json = fso.OpenTextFile(prefsFile).ReadAll
Set re = New RegExp
re.Pattern = "":*?",*,"
json = re.Replace(json, ": & newPrefs & ",*,")
fso.OpenTextFile(prefsFile, 2).Write(json)
Original text file:
RCTICKET="65538,1,10.0.0.1:54593,*,ucIdnri2n4QPf/bv92mtx4w2qliCNdyDgBpHPr7nJFdxYL2/dR+iel9Mh4zgD6QR,*,*,Fbjf5rcIrdrlnibnisrzRcO8tsY=" PassStub="HG)7HbhIZPTiKy" RCTICKETENCRYPTED="1" DtStart="1457700115" DtLength="142560" L="0"/></UPLOADINFO>
Expected result text file:
RCTICKET="65538,1,10.0.0.1:5500,*,ucIdnri2n4QPf/bv92mtx4w2qliCNdyDgBpHPr7nJFdxYL2/dR+iel9Mh4zgD6QR,*,*,Fbjf5rcIrdrlnibnisrzRcO8tsY=" PassStub="HG)7HbhIZPTiKy" RCTICKETENCRYPTED="1" DtStart="1457700115" DtLength="142560" L="0"/></UPLOADINFO>
Can anyone help me?
Your search and replacement expressions are messed up. You're looking for a colon (:) followed by one or more digits (\d+ or [0-9]+) followed by a comma (,), and want to replace that with a colon followed by the new port number and a comma.
Change this:
re.Pattern = "":*?",*,"
json = re.Replace(json, ": & newPrefs & ",*,")
into this.
re.Pattern = ":\d+,"
json = re.Replace(json, ":" & newPrefs & ",")
Always keep your expressions as simple as possible.

Recursively search files for information contained in excel cell and return path

Okedoke... I have an Excel spreadsheet with a filename in column A. The filenames listed in column A appear in one or more text files in one or more source directories.
I need Excel to search the text files recursively and return the path(s) of the file(s) that contain the filename specified in column A into column B. If more than one file go to column C etc.
The Excel sheet would be
__________________________________
__|______A___________|______B_____|
1 | filename.avi | |
2 | another_file.flv | |
The text files to search would be in multiple directories under C:\WebDocs\ and are DokuWiki pages some are quite short, such as this page that would need to be returned
===== Problem Description =====
Reopen a closed bank reconciliation.
===== Solution =====
Demonstration of the tool box routine that allows reposting of the bank rec.
{{videos:bank_rec_reopen1006031511.flv|}}
===== Additional Information -cm =====
You may have noticed that in the video there is a number to the right of the bank account number. In this case it was a 0. That indicates department 0 which is all departments. You get the department 0 if you have all departments combined using the option in the bank set up called "One Bank for All Departments". If this setting is not checked then when you create your starting bank rec for each department you will get a 1 to the right of the bank rec for department 1 and so on. You should normally only have a 0, or have numbers 1 or greater. If you have both, then the method was changed after the initial bank rec was made. You just have to be aware of this as you move forward. As always backup before you make any changes.
There are some other pages though that are quite long that do not contain videos but would be in the directories being searched. Format is the same, plain text, ==== are place holders for headings may contain links to other pages/sites.
I did find an existing VBA script that sort of does what I need it to. It does not recurse and returns too much information, date/time stamp for instance, where all I need is the path.
Private Sub CommandButton1_Click()
Dim sh As Worksheet, rng As Range, lr As Long, fPath As String
Set sh = Sheets(1) 'Change to actual
lstRw = sh.Cells.Find(What:="*", After:=sh.Range("A1"), LookAt:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row
Set rng = sh.Range("A2:A" & lstRw)
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
fPath = .SelectedItems(1)
End With
If Right(fPath, 1) <> "\" Then
fPath = fPath & "\"
End If
fwb = Dir(fPath & "*.*")
x = 2
Do While fwb <> ""
For Each c In rng
If InStr(LCase(fwb), LCase(c.Value)) > 0 Then
Worksheets("Sheet2").Range("C" & x) = fwb
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(fwb)
Worksheets("Sheet2").Range("D" & x) = f.DateLastModified
Worksheets("Sheet2").Range("B" & x) = f.Path
Worksheets("sheet2").Range("A" & x) = c.Value
Columns("A:D").AutoFit
Set fs = Nothing
Set f = Nothing
x = x + 1
End If
Next
fwb = Dir
Loop
Set sh = Nothing
Set rng = Nothing
Sheets(2).Activate
End Sub
My attempts at moification so far have generally resulted in a broken script and have thus led me here asking for help.
Thanks,
Simon
Downlaoded the win32 port of the GNU tool grep from http://gnuwin32.sourceforge.net/
Saved the list of video files into a plain text file instead of using a spreadsheet.
grep --file=C:\file_containing video_file_names.txt -R --include=*.txt C:\Path\To\Files >grep_output.txt
The information written to the grep_output.txt file looked like
C:\wiki_files\wiki\pages/my_bank_rec_page.txt:{{videos:bank_rec_reopen1006031511.flv|}}
So there was the path to the file containing the video name and the video name on one line.
Imported the grep_output.txt file into a new Excel workbook.
Used regular formulae to do the following
Split Column A at the "/" to give the path in Column A and the page and video information in Column B
Split the data in in Column B at the ":{{" characters leaving page name in Column B and video information in Column C
Stripped the :{{ and |}} from the front and rear of the string in Column C
From my limited experience, it seems you'd want to perform 4 tasks.
1) Loop through Directories
2) Loop through files per directory (Good idea to keep the filename in a variable)
3) Test the text file for values. Would suggest clear a "scribble sheet", import the file, run a check. e.g.
Sheets("YourScratchPatch").Select
Application.CutCopyMode = False
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & yourpath & yourfile.txt, Destination:=Range("A1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 2
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
4) if values are found, write the file name variable to the index sheet.
I'm sure there should be better (arrays?) ways to do the comparison check as well, but it depends on what's inside the text file (i.e. just one file name?)
More info on the text file structure would be useful. Hope this helps.

VB Script writing to MultiString reg key

I'm writing a script that looks at the current home page of IE. if it is something other than our intranet I grab that value and merge it in to the secondary pages reg key.
Now I have figured out how merge it in to an array(assuming that there are some secondary pages... if there are no big deal). What I am running in to is that there seems to be an extra line when I finally merge it. It's driving me nuts. Any thoughts? Here is the function. There is more tot he script but this is the part that is painful. Thanks
Function AppendSecondary(StrComputer)
objReg.GetstringValue HKEY_CURRENT_USER, strKeyPath, ValueName, strValueMain
objReg.SetStringValue HKEY_CURRENT_USER, strKeyPath, ValueName, strValueMyMTD
set ws = WScript.CreateObject("Wscript.Shell")
strKeyPath=WS.RegRead(strKeyPathPath & ValueNameSecondary)
if vartype(strKeyPath)= vbArray + vbVariant then
arStrings = strKeyPath
else
arStrings = split(strKeyPath,chr(0))
redim preserve arStrings(ubound(arStrings)-3)
end If
redim preserve arStrings(ubound(arStrings)+1)
arstrings(ubound(arStrings))= strvaluemain
arstrings1 = join(arStrings,VBCRLF)
arstringsnew = Array(arstrings1)
objReg.SetMultiStringValue HKEY_CURRENT_USER, strKeyPath, ValueNameSecondary, arstringsnew
End Function
Check the last element of each array to make sure it's not a null string ("") or a non-printing character like Chr(10) or Chr(13) or vbCR, vbLF or vbCRLF.
Interesting question.
Just out of curiosity, why do you merge an array, then rebuild it as an array later on?
arstrings1 = join(arStrings,VBCRLF) 'merge
arstringsnew = Array(arstrings1) 'reassemble
Regardless, I think your split on "chr(0)" is creating this issue and a simple revision too the join command will suffice.
arstrings1 = trim(join(arstrings,vbcrlf))
of if not the case, a quick loop'd'loop
dim nArray() : Redim nArray(0)
for each str in arstrings
if len(str)>0 then
nArray(ubound(nArray)) = str
redim preserve nArray(ubound(nArray)+1)
end if
next
arrstringsnew = nArray

Visual FoxPro 9 dynamic Arrays

I'm trying to get Dynamic Arrays from my ActiveX component trough Visual FoxPro 9, but with no luck. (Edited and Working example)
LOCAL objMain, objAdapt
#define CrLf CHR(13) + CHR(10)
stMsg = ""
objMain = CREATEOBJECT('nnetsdk.oMain')
objMain.UnlockComponent("xxx-xxxxx-xxxxx-xx")
objAdapt = CREATEOBJECT('nnetsdk.oNetworkAdapter')
objAdapt.GetNetworkAdapters && Collects Network Adapter information
vrAdapters = objAdapt.cName && cName holds collected Network Adapter names
FOR EACH vrAdapter IN vrAdapters
stMsg = stMsg + vrAdapter + CrLf
ENDFOR
MESSAGEBOX(stMsg,64,"List Network Adapters")
RELEASE objAdapt
RELEASE objMain
Can someone explain me what is wrong with this code?
I don't know what your "nnetcom.oMain" ActiveX control is, but you can get directly from VFP via
lcComputerName = "."
loWMIService = GETOBJECT("winmgmts:\\" + lcComputerName + "\root\cimv2")
loItems = loWMIService.ExecQuery("Select * from Win32_NetworkAdapter",,48)
FOR EACH loItem IN loItems
lcMACAddress = loItem.MACAddress
IF !ISNULL(lcMACAddress)
*/ then, you can look at the object properties, such as
lcDescription = loItem.Description
lcMacAddress = loItem.MACAddress
lcNetConnectionID = NVL( loItem.NetConnectionID, "" )
ENDIF
ENDFOR
the For Each loop cycles through class instances of the [Win32_NetworkAdapter] class structure. You can get almost anything you want from that list.
1

Resources