Load Excel File To Powerbuilder - excel

I have this code for buttonclicked event to load excel and text file to powerbuilder and the excel data is not copied i.e ll_return_xls <= 0 and thus when i want to load it to db i will get error since it has no value or data in it...The problem here is i get the data from text file but not from the excel file...Any help will be appreciated
long ll_return
long ll_return_xls
OLEObject excel
IF rb_file.checked then
IF dwo.Name = "b_browse_meters" THEN // Browse Button Clicked for Text
ll_return = GetFileOpenName ( "Select Meter File", is_fullname, is_filename, "TXT", &
"Text Files (*.txt), *.txt" )
if ll_return < 1 then
gnv_msg.f_mensaje("EX28", "", "", OK!)
return
end if
END IF // Browse Button Clicked
END IF
IF dwo.Name ="b_browse_meters_xls" THEN // Browse Button Clicked for Excel
ll_return_xls = GetFileOpenName ( "Select Meter File", is_fullname, is_filename, "XLS", &
"Excel Files (*.xls), *.xls" )
if ll_return_xls < 1 then
gnv_msg.f_mensaje("EX28", "", "", OK!)
return
end if
excel = create oleobject
excel.ConnectToNewObject( "excel.application" )
excel.visible = false
excel.workbooks.open( is_fullname)
excel.Range("A1:A2").Select
excel.ActiveCell.CurrentRegion.Select()
ClipBoard('')
excel.Selection.Copy()
ClipBoard('')
excel.ActiveWorkbook.Close
excel.Disconnectobject()
Destroy excel
END IF // Browse Button Clicked
And Function to load it the text and excel data
long ll_return, ll_arr_len, ll_loop, ll_indx, ll_pass = 0
integer li_rc, li_file_nbr, li_fr_rc //File Read Return Code
string ls_file, ls_line, ls_msg
string lsa_meters[], lsa_meter_pass[]
string ls_meters
long ll_total_valid, ll_total_aparatos
SetPointer(HourGlass!)
if IsValid(w_progbar) then Close(w_progbar)
openwithparm(w_progbar,"Uploading file data ...")
w_progbar.uo_progress_bar.set_position(10)
li_rc = SUCCESS
ll_total_aparatos = 0
ll_total_valid = 0
// Open file
if li_rc = SUCCESS then
ls_file = is_fullname
li_file_nbr = FileOpen(ls_file, LineMode!)
if IsNull(li_file_nbr) or li_file_nbr < 1 then
li_rc = NO_ACTION
end if
end if
// Read file, store serial numbers into array lsa_meters[]
if li_rc = SUCCESS then // File Opened
ll_indx = 0
do while ll_indx > -1 and li_rc = SUCCESS
li_fr_rc = FileRead(li_file_nbr, ls_line)
choose case li_fr_rc
case is > 0
ll_indx ++
lsa_meters[ll_indx] = ls_line
case 0, -100
ll_indx = -1
case -1
li_rc = FAILURE
gnv_msg.f_mensaje("EX21", "", "", OK!)
end choose
loop
if li_rc = SUCCESS then // File Read OK
ll_arr_len = UpperBound(lsa_meters)
if ll_arr_len > 0 then // Data found in file
for ll_loop = 1 to ll_arr_len step 1
if ib_meter then
ll_return = wf_luhn_check(lsa_meters[ll_loop])
ll_total_valid ++
else
if Len(lsa_meters[ll_loop]) >= 9 then
ll_return = 1
ll_total_valid ++
else
ll_return = -1
end if
end if
if ll_return = 1 then
if wf_aparatos_check(lsa_meters[ll_loop]) <= 0 then
ll_return = 1
else
ll_return = -1
ll_total_aparatos ++
end if
end if
if ll_return = 1 then
ll_pass++
lsa_meter_pass[ll_pass] = lsa_meters[ll_loop]
ls_meters = ls_meters + lsa_meters[ll_loop] + isk_TAB_PB
end if
w_progbar.uo_progress_bar.set_position(50 + ((ll_loop / ll_arr_len) * 40))
next
ll_arr_len = UpperBound(lsa_meter_pass)
if ll_arr_len > 0 then
dw_datos_ingreso.Object.num_ini[1] = lsa_meter_pass[1]
dw_datos_ingreso.Object.num_fin[1] = lsa_meter_pass[ll_arr_len]
is_meters_passed = ls_meters // Concatenated string of meter serial no.
il_apa_filemeters_count = ll_arr_len // Number of meters
else
li_rc = FAILURE
if ib_meter then
gnv_msg.f_mensaje("EX27", "", "", OK!)
else
gnv_msg.f_mensaje("EX22", "", "", OK!)
end if
if ll_total_valid = ll_total_aparatos then
gnv_msg.f_mensaje("EX23", "", "", OK!)
end if
end if
else
li_rc = FAILURE
gnv_msg.f_mensaje("EX24", "", "", OK!)
end if // Data found in file
end if // File Read OK
end if // File Opened
w_progbar.uo_progress_bar.set_position(100)
Close(w_progbar)
//Clean up
if li_file_nbr > 0 then
if FileClose(li_file_nbr) = FAILURE then
li_rc = FAILURE
gnv_msg.f_mensaje("EX25", "", "", OK!)
end if
end if
if ll_total_aparatos > 0 then
gnv_msg.f_mensaje("EW140", String(ll_total_aparatos) , "", OK!)
end if
if li_rc = FAILURE then
gnv_msg.f_mensaje("EX26", "", "", OK!)
RETURN FALSE
end if
RETURN TRUE

You can use the ODBC driver directly to the Excel file, and then build a Pipeline object that moves the data from the spreadsheet directly into the database. Don't write code you don't need to.

Related

Roku (Brightscript) - Playing DRM Protected Video Content

These is a self answering question.
Problem:
Can not play videos which are protected by PlayReady DRM.
Here is the working sample
if m.VideoPlayer = invalid
m.VideoPlayer = m.top.createChild("Video")
m.VideoPlayer.id = "VideoPlayer"
m.VideoPlayer.observeField("state", "OnVideoStateChange")
end if
drmParams = {}
videoContent = createObject("RoSGNode", "ContentNode")
videoContent.Live = remoteContent.IsLive
videoContent.Url = remoteContent.Path
if remoteContent.CodecType = "DashWideVineDrm" then
videoContent.StreamFormat = "dash"
drmparams.licenseServerURL = remoteContent.DrmRightsUrl
drmParams.KeySystem = "widevine"
else if remoteContent.CodecType = "PlayReadyDrm" then
videoContent.StreamFormat = "ism"
drmParams.KeySystem = "playready"
drmParams.encodingType = "PlayReadyLicenseAcquisitionUrl"
drmParams.encodingKey = remoteContent.DrmRightsUrl
else
videoContent.StreamFormat = "mp4"
end if
videoContent.drmParams = drmParams
device = CreateObject("roDeviceInfo")
httpAgent = CreateObject("roHttpAgent")
if httpAgent <> invalid then
httpAgent.SetCertificatesFile("common:/certs/ca-bundle.crt")
httpAgent.InitClientCertificates()
httpAgent.EnableCookies()
httpAgent.AddHeader("X-Roku-Reserved-Dev-Id", "")
if remoteContent.MYCUSTOMHEADER1 <> invalid and remoteContent.MYCUSTOMHEADER1 <> "" then
httpAgent.AddHeader("MY-CUSTOM-HEADER2", remoteContent.MYCUSTOMHEADER1)
end if
if remoteContent.MYCUSTOMHEADER2 <> invalid and remoteContent.MYCUSTOMHEADER2 <> "" then
httpAgent.AddHeader("MY-CUSTOM-HEADER2", remoteContent.MYCUSTOMHEADER2)
end if
m.VideoPlayer.setHttpAgent(httpAgent)
else
headers = []
headers.push("X-Roku-Reserved-Dev-Id:")
if remoteContent.MYCUSTOMHEADER1 <> invalid and remoteContent.MYCUSTOMHEADER1 <> "" then headers.push("MY-CUSTOM-HEADER1:" + remoteContent.MYCUSTOMHEADER1)
if remoteContent.MYCUSTOMHEADER2 <> invalid and remoteContent.MYCUSTOMHEADER2 <> "" then headers.push("MY-CUSTOM-HEADER2:" + remoteContent.MYCUSTOMHEADER2)
videoContent.HttpHeaders = headers
videoContent.HttpSendClientCertificates = true
videoContent.HttpCertificatesFile = "common:/certs/ca-bundle.crt"
m.VideoPlayer.EnableCookies()
m.VideoPlayer.SetCertificatesFile("common:/certs/ca-bundle.crt")
m.VideoPlayer.InitClientCertificates()
end if
m.VideoPlayer.content = videoContent
m.VideoPlayer.control = "play"
NOTE:
If you use PlayReady DO NOT FILL drmParams.licenseServerURL, because it will fail to play with DRM Error (-6).

Multiple records taken in a Data Driven SoapUI test case with Groovy

I am trying to copy multiple rows from an excel sheet with a Groovy Script, but somehow I am hitting the java.lang.NullPointerException error. The code I am using is the following:
import com.eviware.soapui.support.XmlHolder
import jxl.*
import jxl.write.*
def numofapps = context.expand('${Data_AppNM#NumberOfApplicants}')
def apps2 = ["2","3","4","5","6"]
def myTestCase = context.testCase
def counter,next,previous,size
Workbook workbook1 = Workbook.getWorkbook(new File("C://Path//Multiple records.xls"))
Sheet sheet1 = workbook1.getSheet(0)
size= sheet1.getRows().toInteger()
propTestStep = myTestCase.getTestStepByName("Data")
propTestStep.setPropertyValue("Total", size.toString())
counter = propTestStep.getPropertyValue("Count").toString()
counter = counter.toInteger()
next = (counter > size-2? 0: counter+1)
Cell u1_1 = sheet1.getCell(0,counter)
Cell u2_1 = sheet1.getCell(1,counter)
Cell u3_1 = sheet1.getCell(2,counter)
workbook1.close()
1value1 = u1_1.getContents()
2value1 = u2_1.getContents()
3value1 = u3_1.getContents()
propTestStep.setPropertyValue("A1.1Value", 1value1 )
propTestStep.setPropertyValue("A1.2Value", 2value1 )
propTestStep.setPropertyValue("A1.3Value", 3value1 )
propTestStep.setPropertyValue("Count", next.toString())
next++ //increase next value
propTestStep.setPropertyValue("Next", next.toString())
if (apps2.contains(numofapps)){ //setting values for Applicant 2 if requested
counter = propTestStep.getPropertyValue("Count").toString()
counter = counter.toInteger()
next = (counter > size-2? 0: counter+1)
// Extracting the Data from the Excel sheet
Cell u1_2 = sheet1.getCell(0,counter)
Cell u2_2 = sheet1.getCell(1,counter)
Cell u3_2 = sheet1.getCell(2,counter)
workbook1.close()
1value2 = u1_2.getContents()
2value2 = u2_2.getContents()
3value2 = u3_2.getContents()
propTestStep.setPropertyValue("A2.1Value", 1value2 )
propTestStep.setPropertyValue("A2.2Value", 2value2 )
propTestStep.setPropertyValue("A2.3Value", 3value2 )
propTestStep.setPropertyValue("Count", next.toString())
next++ //increase next value
propTestStep.setPropertyValue("Next", next.toString())
}
I am hitting the NullPointerException error on the Cell u1_2 = sheet1.getCell(0,counter) step.
Can you please tell me why I am hitting these and is there any other way that I can use a shorter code?
Thank you :)

I keep getting a expected then error when I have the the in the string

I keep getting the then expected error on line 61 and I cant find the problem any ideas?
I tried working it out and rearranging it im using computer craft periherals mag card reader and trying to mag a card door
os.loadAPI("SHA")
os.pullEvent = os.pullEventRaw
redstone.setBundledOutput("left",colors.white)
math.randomseed(os.time())
term.clear()
term.setCursorPos(1,1)
print("DKM.inc Doors")
print("thank you")
modem = peripheral.wrap("top")
if moden == nil then
error("Modem not on top")
end
if moden.isPresentRemote("mag card reader_0") then
reader = peripheral.wrap("mag card reader_0")
print("Card reader connected")
else
error("Mag-card reader not found")
end
if modem.isPresentRemote("monitor_0") then
monitor = peripheral.wrap("monitor_0")
print("monitor connected")
else
error("monitor not found")
end
hashedPw = "0706490"
cardsFilePath = "cards"
cards = {""}
chars = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
newpass = ""
cardNum = 0
if fs.exists(cardsFilePath) then
cardsFile = fs.open(cardsFilePath, "r")
cards = textutils.unserialize(cardsFile.readAll())
cardsFile.close()
end
while true do
admin = false
monitor.clear()
monitor.setCursorPos(1,1)
monitor.write("Please insert card")
reader.setInsertCardLight(true)
event, p1,p2,p3 = os.pullEvent()
if event == " mag_swipe" then
if SHA.SHA1_2(p1) == hashePw then
admin = true
end
for x = 1, #cards do
if SHA,SHA1_2(p1) == cards[x] then --line 61 is right here
reader.setInsertCardLight(false)
redstone.setBundledOutput("left", 0)
os.sleep(3)
redstone.setBundledOutput("left", colors.white)
reader.setInsertCardLight(true)
break
end
end
end
if admin == true then
reader.setInsertCardLight(false)
monitor.clear()
monitor.setCursorPos(1,1)
monitor.write("Admin granted insert blank card")
for z = 1,15 do
case math.random(1,2)
a = math.random(1,#chars)
if case == 1 then
x=string.upper(chars[a])
elseif case == 2 then
x=string.lower(chars[a])
end
newpass = newpass..x
end
reader.setInsertCardLight(true)
cardNum = #cards
print(reader.beginWrite(newpass, cardNum..""))
table.insert(cards, SHA,SHA1_2(newpass))
while reader.isWaiting() do
end
reader.setInsertCardLight(false)
monitor.clear()
monitor.setCursorPos(1,1)
monitor.write("new card created")
newpass = ""
end
os.sleep(1)
cardsFile = fs.open(cardsFilePath, "w")
cardsFile.write(textutils.serialize(cards))
cardsFile.close()
end
You miss spelled "modem" with moden on 2 lines.
if moden == nil then
and also..
if moden.isPresentRemote("mag card reader_0") then
As for the error.
if SHA,SHA1_2(p1) == cards[x] then --line 61 is right here
i believe.. should be this..
if SHA.SHA1_2(p1) == cards[x] then --line 61 is right here
swapping the , for a . should do the trick.

Writing to Excel sheet based on image difference using matlab

I have some folders named test* from test 1 to test 100 for example, I need to print names of folders as header in first row.
Then I need to check my test image image2 with each image inside these folders if the diff bigger than 0.05 between my test image2 and every images from each folder test* will write 1 otherwise write 0. till to testn.
My code is as follow :
srcFolders = dir('D:\test*');
for folder = 1:length(srcFolders)
path = strcat('D:\',srcFolders(folder).name);
sear = strcat(path, '\*.bmp');
srcFiles = dir(sear);
for i = 1 : length(srcFiles)
filename = strcat(path,'\',srcFiles(i).name);
Image1= imread(filename);
Image2 = imread('D:\2','jpeg'); % Image 2
x = diff( Image2 , Image1)
% any suggestion here to get my output for printing in excel
if (x >= 0.05)
xlswrite(xlsfile, srcFiles(i), ‘0’, ‘A1’);
else
xlswrite(xlsfile, srcFiles(i), ‘1’, ‘A1’);
end
end
end
thanks
%On every 'folder loop', increment the column range so you have 1 column by folder
%On every 'file loop', increment the row range so you have 1 row by file
xls_filename = 'foo.xls'; %The name of your xls file
xls_sheet = 'sheet_name'; % Put here the name of the sheet you want to write in
column_range = 'A' % Initialisation of the column range
srcFolders = dir('D:\test*');
for folder = 1:length(srcFolders)
path = strcat('D:\',srcFolders(folder).name);
folder_range = strcat(column_range, '1');
xlswrite(xls_filename, {srcFolders(folder).name}, xls_sheet, folder_range); %Writing the name of the folder in the first row
sear = strcat(path, '\*.bmp');
srcFiles = dir(sear);
row_range = '2';
for i = 1 : length(srcFiles)
filename = strcat(path,'\',srcFiles(i).name);
Image1= imread(filename);
Image2 = imread('D:\2','jpeg');
x = diff( Image2 , Image1);
file_range = strcat(column_range, row_range);
if (x >= 0.05)
xlswrite(xls_filename, {'0'}, xls_sheet, file_range ); %Writing '0' in the second row
else
xlswrite(xls_filename, {'1'}, xls_sheet, file_range ); %Writing '1' in the second row
end
row_range = char(row_range + 1); %Moving to the next row
end
column_range = char(column_range + 1); %Moving to the next column
end

Windows native script to change text file based on line and column number

A simulation program I'm using requires a text based input file. I need to run the simulation in different configurations by changing the values in the text file. I am looking for a way to do this automatically with any script that does not require third party compilers. It has to run natively on a Windows XP machine. I only have a little bit of coding experience in MATLAB and FORTRAN.
I will describe my idea of what the script should do in some pseudo-code:
% speed.txt - a txt file with 10 different speed values
% coeff.txt - a txt file with 10 different coefficients
% dist.txt - a txt file with 5 different distance values
% input.txt - the txt file containing the input parameters. This file has to be changed.
% output.txt- the output of the simulation
% sp - the i-th speed value
% co - the i-th coeff value
% di - the j-th distance value
% D:\FO - Final Output folder
Read input.txt
for i = 1:10
Display i on screen % so I know how much of the batch is done
Go to line 37, overwrite 1st four characters with i-th value from speed.txt
Go to line 68, overwrite 1st eight characters with i-th value from coeff.txt
for j = 1:5
Display j on screen % so I know how much of the batch is done
Go to line 67, overwrite 1st five characters with j-th value from dist.txt
Run simulation.exe
When simulation is done, get output.txt, rename it to "output_sp_co_di.txt"
and move the file to D:\FO
end
end
I hope that this is possible with a .bat or .vbs script (or anything else that will run natively). All help is greatly appreciated.
EDIT: after some advice I started a vbs script. I have never used that language before but pulled the thing here under together from scraps on the internet:
Option Explicit
Dim objFSO, strTextFile, strData, strLine, arrLines
Dim filesys, filetxt, path
Dim speed(10), ct(10), dist(4), text(73), d(4)
Dim i, j, k
i = 0
j = 0
k = 0
speed(0) = 3.0
speed(1) = 5.0
speed(2) = 7.0
speed(3) = 9.0
speed(4) = 11.0
speed(5) = 13.0
speed(6) = 15.0
speed(7) = 17.0
speed(8) = 19.0
speed(9)= 21.0
speed(10)= 22.0
ct(0) = 0.987433
ct(1) = 0.816257
ct(2) = 0.816361
ct(3) = 0.720357
ct(4) = 0.418192
ct(5) = 0.239146
ct(6) = 0.154534
ct(7) = 0.107608
ct(8) = 0.079057
ct(9)= 0.060437
ct(10)= 0.053465
dist(0) = 173.48
dist(1) = 260.22
dist(2) = 346.96
dist(3) = 433.7
dist(4) = 520.44
d(0) = 2
d(1) = 3
d(2) = 4
d(3) = 5
d(4) = 6
CONST ForReading = 1
'name of the text file
strTextFile = "TurbSim.inp"
'Create a File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Open the text file - strData now contains the whole file
strData = objFSO.OpenTextFile(strTextFile,ForReading).ReadAll
'Split the text file into lines
arrLines = Split(strData,vbCrLf)
'Step through the lines
For Each strLine in arrLines
text(i) = strLine
i = i + 1
Next
'Open text file to write to
path = objFSO.GetAbsolutePathName("D:\Sandbox\TurbSim.inp")
For i = 0 To 10
If i = 0 Then
text(37) = Replace(text(37),"UUUU",speed(i))
text(68) = Replace(text(68),"CCCCCCCC",ct(i))
Else
text(37) = Replace(text(37),speed(i-1),speed(i))
text(68) = Replace(text(68),ct(i-1),ct(i))
End If
For j = 0 To 4
If j = 0 Then
text(67) = Replace(text(67),"DDDDD",dist(j))
Else
text(67) = Replace(text(67),dist(j-1),dist(j))
End If
Set filetxt = objFSO.opentextfile("D:\Sandbox\TurbSim.inp", 2, True)
For k = 0 To 73
if k = 73 Then
filetxt.write text(k)
Else
filetxt.write text(k) & vbCr & vbLf
End If
objFSO.CopyFile "D:\Sandbox\TurbSim.inp", _
"D:\Sandbox\input\TurbSim_" & speed(i) & "_" & d(j) &"D.inp"
Next
filetxt.close
Next
Next
' wscript.echo text(37)
' wscript.echo text(68)
' wscript.echo text(67)
filetxt.Close
'Cleanup
' Set filesys = Nothing
Set objFSO = Nothing
Problem is now that the distance part (the j-loop) is not working properly. From the output generated (TurbSim_speed_dD.inp) I see that only the last distance (520.44) is used. I don't really understand why, I'll look into that later. If anyone has a suggestion for improvement, then you're ideas are always welcome.
The Batch file below is a .bat version of your vbs script:
#echo off
SetLocal EnableDelayedExpansion
REM Auxiliary macro for easier replacements
set Replace=for /F "tokens=1,2 delims==" %%x in
:: speed - vector with 11 different speed values
Set i=0
For %%s in (3.0 5.0 7.0 9.0 11.0 13.0 15.0 17.0 19.0 21.0 22.0) do (
Set speed[!i!]=%%s
Set /A i+=1
)
:: ct - vector with 11 different coefficients
Set i=0
For %%c in (0.987433 0.816257 0.816361 0.720357 0.418192 0.239146 0.154534 0.107608 0.079057 0.060437 0.053465) do (
Set ct[!i!]=%%c
Set /A i+=1
)
:: dist - vector with 5 different distance values
Set i=0
For %%d in (173.48 260.22 346.96 433.7 520.44) do (
Set dist[!i!]=%%d
Set /A i+=1
)
REM d does not need to be a vector because d(i) = i+2
:: Split the text file into lines, and Step through the lines
Set i=0
For /F "delims=" %%l in (TurbSim.inp) do (
Set "text[!i!]=%%l"
Set /A i=i+1
)
For /L %%i in (0,1,10) do (
If %%i == 0 (
%Replace% ("UUUU=!speed[%%i]!") do set "text[37]=!text[37]:%%x=%%y!"
%Replace% ("CCCCCCCC=!ct[%%i]!") do set "text[68]=!text[68]:%%x=%%y!"
) Else (
set /A iM1=i-1
%Replace% ("!iM1!") do set speed_iM1=!speed[%%x]!& set ct_iM1=!ct[%%x]!
%Replace% ("!speed_iM1!=!speed[%%i]!") do set "text[37]=!text[37]:%%x=%%y!"
%Replace% ("!ct_iM1!=!ct[%%i]!") do set "text[68]=!text[68]:%%x=%%y!"
)
For /L %%j in (0,1,4) do (
If %%j == 0 (
%Replace% ("DDDDD=!dist[%%j]!") do set "text[67]=!text[67]:%%x=%%y!"
) Else (
set /A jM1=j-1
%Replace% ("!jM1!") do set dist_jM1=!dist[%%x]!
%Replace% ("!dist_jM1!=!dist[%%j]!") do set "text[67]=!text[67]:%%x=%%y!"
)
set /A d=j+2
(For /L %%k in (0,1,73) do (
if %%k == 73 (
set /P =!text[%%k]!< NUL
) Else (
echo !text[%%k]!
)
)) > "D:\Sandbox\input\TurbSim_!speed[%%i]!_!d!D.inp"
)
)
echo %text[37]%
echo %text[68]%
echo %text[67]%
Notes:
1- This is a first attempt Batch file based on your vbs script; I really don't understand what you tried to do and just did a direct translation. It seems that the requirements you state in the question are not the same of the vbs script. Any problem may be solved if you give me specific details.
2- Previous Batch file remove any empty line from the input file. This may be solved if needed.
3- The text replacement in Batch is textual, NOT by numeric value. Any number must be written exactly the same as the array values in order to be replaced. I think the same behaviour apply to vbs.
4- Input file must not contain certain special Batch characters, like ! ^ and others. This may be fixed in certain cases only.
I have managed to pull together a .vbs script from various internet references that does what I want. The script does the following:
Reads in original input file
Stores the data line by line in the text array
Reads in speed, coefficient and distance data from text file
Stores this data in separate speed, coefficient and distance arrays line by line.
Takes first entry of speed and coeff. array and writes it at appropriate places in the
text array
Loops through distance array and writes the text array line by line back to an .inp file
Runs the simulation with the edited input file
Waits until simulation is terminated.
Copy output files from current directory to output folder, renaming them in the process.
Wait 10 seconds to make sure copying is finished
10.Repeat steps 6-10 with all other entries of speed and coeff. array
Requirements for this script to work:
A. An input folder with an .inp file that has "UUUU", "DDDDD", "CCCCCCCC" written at places where respectively the velocity, distance and coefficient should be written.
B. An output folder
C. The files speed.txt, ct.txt and distance.txt containing the speed, coefficient and distance values to be used.
D. You should run this script from an admin account. Otherwise you don't have the permission to check if the simulation is still running with the "Win32_process".
Option Explicit
Dim objFSO, strTextFile, strTData, strLine, arrTLines
Dim strVelFile, strCtFile, strDistFile
Dim strVData, strCData, strDData
Dim arrVLines, arrCLines, arrDLines
Dim strLineV, strLineC, strLineD
Dim strComputer, oWMI, colEvents, oEvent
Dim filesys, filetxt, path, curPath
Dim speed(), ct(), dist(), text(73)
Dim oShell
Dim i, j, k
i = 0
j = 0
k = 0
' Subroutine to start an executable
Sub Run(ByVal sFile)
Dim shell
Set shell = CreateObject("WScript.Shell")
shell.Run Chr(34) & sFile & Chr(34), 1, false
Set shell = Nothing
End Sub
CONST ForReading = 1
' Create a File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Create Shell object. Needed to change directories
Set oShell = CreateObject("WScript.Shell")
'Change current directory to \input folder
oShell.CurrentDirectory = ".\input"
' The name of the original input file
' with the UUUU, DDDDD, CCCCCCC in the correct places
strTextFile = "TurbSim.inp"
' Open the text file and read it all into strTData
strTData = objFSO.OpenTextFile(strTextFile,ForReading).ReadAll
' Go back to parent folder as there all the other .txt files reside
Set oShell = CreateObject("WScript.Shell")
oShell.CurrentDirectory = ".\.."
' name of other input text files
strVelFile = "speed.txt"
strCtFile = "ct.txt"
strDistFile = "dist.txt"
' Open the text file - str*Data now contains the whole file
strVData = objFSO.OpenTextFile(strVelFile,ForReading).ReadAll
strCData = objFSO.OpenTextFile(strCtFile,ForReading).ReadAll
strDData = objFSO.OpenTextFile(strDistFile,ForReading).ReadAll
' Split the text files into lines
arrTLines = Split(strTData,vbCrLf)
arrVLines = Split(strVData,vbCrLf)
arrCLines = Split(strCData,vbCrLf)
arrDLines = Split(strDData,vbCrLf)
' Give the speed, ct and dist arrays their dimension
ReDim speed(UBound(arrVLines))
ReDim ct(UBound(arrCLines))
ReDim dist(UBound(arrDLines))
' Add data to arrays text, speed, ct and dist line by line
For Each strLine in arrTLines
text(i) = strLine
i = i + 1
Next
'Reset counter
i = 0
' Step through the lines speed
For Each strLineV in arrVLines
speed(i) = strLineV
i = i + 1
Next
i = 0
' Step through the lines ct
For Each strLineC in arrCLines
ct(i) = strLineC
i = i + 1
Next
i = 0
' Step through the lines dist
For Each strLineD in arrDLines
dist(i) = strLineD
i = i + 1
Next
i = 0
' Get the current path. Needed to point to the executable.
curPath = objFSO.GetAbsolutePathName(".")
For i = 0 To UBound(speed)
If i = 0 Then
' Replace the UUUU and CCCCCCCC values
' Only the first run.
text(37) = Replace(text(37),"UUUU",speed(i))
text(68) = Replace(text(68),"CCCCCCCC",ct(i))
Else ' Replace the previous speed and coeff. values with the current one
text(37) = Replace(text(37),speed(i-1),speed(i))
text(68) = Replace(text(68),ct(i-1),ct(i))
End If
For j = 0 To UBound(dist)
If j = 0 And i = 0 Then
' Replace the DDDDD value (only at first run)
text(67) = Replace(text(67),"DDDDD",dist(j))
ElseIf j = 0 And i > 0 Then
' Replace the distance value of the previous speed/coeff. case
' with the current one
text(67) = Replace(text(67), dist(UBound(dist)), dist(j))
Else ' Replace the previous distance value with the current one
text(67) = Replace(text(67),dist(j-1),dist(j))
End If
Set filetxt = objFSO.opentextfile(curPath & "\TurbSim.inp", 2, True)
For k = 0 To 73 ' Write to an .inp file line by line
if k = 73 Then ' Prevent adding a new line at the end
filetxt.write text(k)
Else
filetxt.write text(k) & vbCr & vbLf
End If
Next
filetxt.close
' Execute the simulation
Run curPath &"\TurbSimGW.exe"
strComputer = "."
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
'# Create an event query to be notified within 3 seconds when TurbSimGW is closed
Set colEvents = oWMI.ExecNotificationQuery _
("SELECT * FROM __InstanceDeletionEvent WITHIN 3 " _
& "WHERE TargetInstance ISA 'Win32_Process' " _
& "AND TargetInstance.Name = 'TurbSimGW.exe'")
'# Wait until TurbSimGW is closed
Set oEvent = colEvents.NextEvent
' Copy and rename output files
objFSO.CopyFile curPath & "\TurbSim.wnd", _
curPath & "\output\TurbSim_" & speed(i) & "_" & j+2 &"D.wnd"
wscript.sleep 10000 ' time to allow copying the files
Next
Next
'' ' wscript.echo text(37)
'' ' wscript.echo text(68)
'' ' wscript.echo text(67)
filetxt.Close
' Cleanup
' Set filesys = Nothing
Set objFSO = Nothing
Now it works flawlessly. However A solution to requirement D would be nice. My work-around is instead of checking if the program is terminated I just set a sleep value. For this value of sleep I know for sure the simulation is done and the output files are ready to copy.

Resources