Saturday, April 30, 2016

remote domain ldap computer scan, program installation, group listing

Hello,

In a domain
When logged as admin of the domain
You can use WMI (windows management interface) to do a lot of things

Force execution of a local program on the remote computer
(cannot remotly execute a program that will execute a remote program, that would spread viruses)
List all computer of the domaine root
List and query the computer for some information

I use this script to remote install visual c redistribuable 2010
(must be copied on the c drive of the computer first)
Then install an ODBC mysql connector
(must be copied on the c drive of the computer first)
Then i copy on the computer a script to do an inventory in a mysql database
Then i remote execute the script to get the computer data in the inventory
(must be copied on the c drive of the computer first)

But here, i only list the program to list computers, list groups or remote execute a local program on a computer (with 3 different syntax)

example:

process01 = "c:\windows\system32\cscript.exe"
'argument01 = """\\hyntssr5\apps$\Apps\windows 7 sp1 fra pro unattend\sources\$oem$\$1\_util\inventaire\audit_v0804_v4 hyd.vbs"""
argument01 = """C:\_util\inventaire\audit_v0804_v4 hyd.vbs"""

'process01 = "cmd.exe /c"
'argument01 = """c:\_util\MysqlOdbcConnector\vcredist_x86.exe /q /norestart"""

'process01 = "msiexec.exe"
'argument01 = "/i c:\_util\MysqlOdbcConnector\mysql-connector-odbc-5.3.4-win32.msi /quiet"

================ ldap.vbs ==================================

'=== Ultimate dynamic web interface 2.0

'=== this script:
'=== generate dynamically a web interface to manage virtually anything
'=== control (left frame), input (middle frame), and output (bottom frame) from vbs/wsh (windows host scripts)

'=== the first version was a simple interface made by a programmer
'=== the second version have more explanations
'=== more dynamism than ever
'=== more functions to clean up main loop code
'=== easier array display coding to add stuff more easily
'=== MDB (access type database) management (creation, edition, search/edit)
'=== futur: mdb import, mdb export, sql sync, excel export

'=== by: SergeFournier(at)hotmail.com

'=== tested on windows vista 64, internet explorer 7

Set objFSO    = CreateObject("Scripting.FileSystemObject")
Set objshe    = CreateObject("WScript.Shell")
Set objNet    = CreateObject("WScript.Network")

Const hkcr = &H80000000 'HKEY_CLASSES_ROOT
Const HKCU = &H80000001 'HKEY_CURRENT_USER
Const hklm = &H80000002 'HKEY_LOCAL_MACHINE
Const hku  = &H80000003 'HKEY_USERS
Const hkcc = &H80000005 'HKEY_CURRENT_CONFIG

dim allara(10,10)
dim alltab(10)
DIM ordcol(10,10)

'=== for ldap
dim strInputPath, strOutputPath, strStatus
dim objFSO, objTextIn, objTextOut


'=== actual drive, actual directory, and "\"
thepath=WScript.ScriptFullName
p = instrRev(thepath,"\")
basedir  = left(thepath,p)
filnam = right(thepath,len(thepath)-p)

'=== windows dir
WinDir = objfso.GetSpecialFolder(0)

'=== restart the script in 32 bits if we are on a 64 bits system
'=== (databases drivers issues)
a64 = windir & "\syswow64\wscript.exe"

if objFSO.fileEXISTS(a64) and instr(lcase(wscript.fullname),"syswow64")=0 then
   '=== 64 bits system
   a = """" & a64 & """ """ & basedir & filnam & """"
   objshe.Run a,0, false
   wscript.quit
end if

'=== log everything in a file
logall = 0

'=== edit mode 0=off 1=on
'=== if edtmod = 1 every results will be in editable html boxes
edtmod = 0
totrec = 0
offset = 0
'=== no second search in the lower frame (fbot)
'=== this mean the search button is removed when table is generated
secseatag=0

dim tabnam,aratit,ara01,edtmod,offset,maxoff,myarray,component, strsearch, tab,sel,whe,objcon,tabnam2,ooper,wwild


priara = array(_
"<input type=""button"" onClick=""javascript:print()"" value=""Print""/><br><br>")
lefara = array(_
"<body background=""" & basedir & "images_interface\fond_gauche.jpg"">")
midara = array(_
"<body background=""" & basedir & "images_interface\fond_gris.jpg"">")
botara = array(_
"<body background=""" & basedir & "images_interface\fond_gris.jpg"">")

if logall=1 then
   '=== debug log
   file02 = basedir & "zzz_troubleshooting.txt"
   on error resume next
   Set Fil02 = objFSo.OpenTextFile(file02, 2, true)
   on error goto 0
end if





'============================================== main loop =============================================

'=== name of the user logged in window (network or not)
usenam=lcase(objnet.username)

'=== maximum row in the grid when more than the max
'=== we display only this number and a button "precedent" and "next" to swtich page
maxoff=15 '=== since 0 is included, 24 = 25 record

'=== menu items on left side (control side, frame: flef)

'= arabutnam: name of button, purely programmation name, used later to execute functions in main loop
'= arabutdes: description of button, text inside it actually
'= aradepnam: departement name, each departement (Section) is separated by a space
'= aradepcol: color of departement, blue = computer, brown = accounting, etc will follow a standard on internet (vague)
 
'=== button at the start for control frame (flef object)
'=== you can add as many buttons as you want, it's all dynamic (extendable)
if logall=1 then
   fil02.WriteLine date & " " & time & " START"
end if

x=0
ReDim Preserve arabutnam(x): ReDim Preserve arabutdes(x): ReDim Preserve aradepnam(x): ReDim Preserve aradepcol(x)
arabutnam(x)="doinventory"
arabutdes(x)="New owner and majinventory"
aradepnam(x)="Inventory"
aradepcol(x)="cccccc"

x=x+1
ReDim Preserve arabutnam(x): ReDim Preserve arabutdes(x): ReDim Preserve aradepnam(x): ReDim Preserve aradepcol(x)
arabutnam(x)="scan"
arabutdes(x)="scan domain computers"
aradepnam(x)="TEST"
aradepcol(x)="cccccc"

x=x+1
ReDim Preserve arabutnam(x): ReDim Preserve arabutdes(x): ReDim Preserve aradepnam(x): ReDim Preserve aradepcol(x)
arabutnam(x)="scangroups"
arabutdes(x)="scan groups and list members"
aradepnam(x)="TEST"
aradepcol(x)="cccccc"

x=x+1
ReDim Preserve arabutnam(x): ReDim Preserve arabutdes(x): ReDim Preserve aradepnam(x): ReDim Preserve aradepcol(x)
arabutnam(x)="clrframes"
arabutdes(x)="Clear Frames"
aradepnam(x)="OTHER"
aradepcol(x)="cccccc"

x=x+1
ReDim Preserve arabutnam(x): ReDim Preserve arabutdes(x): ReDim Preserve aradepnam(x): ReDim Preserve aradepcol(x)
arabutnam(x)="info"
arabutdes(x)="Information/Help"
aradepnam(x)="OTHER"
aradepcol(x)="cccccc"

x=x+1
ReDim Preserve arabutnam(x): ReDim Preserve arabutdes(x): ReDim Preserve aradepnam(x): ReDim Preserve aradepcol(x)
arabutnam(x)="quit01"
arabutdes(x)="Quitter"
aradepnam(x)="All"
aradepcol(x)="cccccc"

'=== old code for ref
'arabut=array("stristas", "striunig", "desarchive", "infocomp", "cretasks", "renamecomputer", "test", "clrframes", "quit01")
'arabutdes=array("Crée Structure i: Stas", "Crée Structure i: Unigec", "Désarchivage", "Info computer", "Create tasks", "Rename computer", "test divers",  "Clear Frames",    "Quitter")
'aradep=array("All", "All", "Informatique", "Informatique", "Informatique", "Informatique", "Other", "All")
'aradepcol=array("cccccc", "cccccc", "6699ff", "6699ff", "6699ff", "6699ff", "6699ff", "cccccc")

'=== i dont remember this one
lasdep=""
 
'=== web interface, internet explorer

'=== set the objects before calling functions, so they are global objects/variables, accessibles in all the program
set oIE = wscript.CreateObject("InternetExplorer.Application", "IE_")
dim flef, fmid, fbot

'=== title of internet explorer window
doctit = "titre de la page"

'=== title to display inside the left frame (control frame, flef object)
maitit = "Troubleshooting interface<br><br>STAS 45834"'=== title inside the left frame
maitit="<br><br><br><br>"

'=== create the main web interface with 3 frames, objects: flef, fmid, fbot
a = crewebmai(oie, doctit, maitit, arabutnam, arabutdes, aradepnam, aradepcol)

'=== defaut menu option for certain name logged
'=== example: a certain user will use always the same function
'=== so the interface will start, by executing this function at first, not an empty frame
'=== simply enter the name of the button that should be pressed for this user when interface start

if usenam="wildboy" or usenam="fournier.serge" then
'=== defaut choice when program start
'resbutlefstr = "stristas"
end if

'=== sub to call for each button
'=== here we define a sub to be called when a button in the web page is pressed
Do While (oIE.Busy)
wscript.sleep 50
loop
do while oie.readystate<>4
wscript.sleep 50
loop

'=== set up a return value on click of each button on the left frame
'=== the returned value is the name (programmable name) of each button (arabutnam)
'=== later any action will be taken according to this value
'=== i use this method because i dont want to call a sub when a button is pressed
'=== to remain in a loop for the main program, that is standard procedure in programming (to have a main loop)

for i=0 to ubound(arabutnam)
   flef.forms(0).elements(arabutnam(i)).onclick = getref("buttonlef")
next

'=== we also chek the key presse in each frame
'=== we do this cause we want "enter" key to be used instead of pressing "ok" button with the mouse
set flef.onkeypress = GetRef("Checklef")
set fmid.onkeypress = GetRef("Checkmid")
set fbot.onkeypress = GetRef("Checkbot")

'=== if bready = true, it mean they closed internet explorer, see the sub on internet explorer closing later in this code
'=== we have to chek this value often to stop the wscript.exe from interpreting this code, when internet explorer is closed
bReady=false
resbutlefstr = ""
resbutmidstr = ""
resbutbotstr = ""
reskeylef = 0
reskeymid = 0
reskeybot = 0

WScript.sleep(50) ' .1 seconds

'=== main loop, infinite
'=== unless someone press QUIT button
'=== or close internet explorer (bready = true)

SET cmd = CREATEOBJECT("ADODB.Command")
SET cn = CREATEOBJECT("ADODB.Connection")
SET rs = CREATEOBJECT("ADODB.Recordset")

do


if resbutlefstr="doinventory" then

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' change owner name and force inventory
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

'=== this was a test with multiple button value (one for each line)
a = clefra(array("fmid","fbot"))

x=0
redim preserve distmp(x) :redim preserve namtmp(x) :redim preserve deftmp(x) :redim preserve typtmp(x) :redim preserve errtmp(x)
distmp(x)="New owner name"      '===== description displayed in front of the field
namtmp(x)="text01"                  '===== name of variable for programming purpose
deftmp(x)="dc2 firm db"           '===== default value inside the form (the form will be 20 char long if no value here, but you can enter more)
typtmp(x)="textbox"               '===== type of data: textbox password (futur: more to come)
errtmp(x)="owner name" '===== text to display after the form "facultatif" blue text "error" red text are special keywords

x=x+1
redim preserve distmp(x) :redim preserve namtmp(x) :redim preserve deftmp(x) :redim preserve typtmp(x) :redim preserve errtmp(x)
distmp(x)="Computer name"      '===== description displayed in front of the field
namtmp(x)="text02"                  '===== name of variable for programming purpose
deftmp(x)="hyntssr2"           '===== default value inside the form (the form will be 20 char long if no value here, but you can enter more)
typtmp(x)="textbox"               '===== type of data: textbox password (futur: more to come)
errtmp(x)="computer name" '===== text to display after the form "facultatif" blue text "error" red text are special keywords

buttmp=array("ok","cancel")       '===== at the end, there will be an "ok" button and a "cancel" button

a = dynforgen (distmp,namtmp,deftmp,typtmp,errtmp,buttmp,tit)

do
'=== flag to tell if the input is not valid
err01=0
'=== flag to say input is done, since there might be a defaut value, we must validate if user was finished
inpdon=0
'=== "ok" button or "enter" key are the same
'=== and nothing was pressed on left frame (control frame)

if resbutlefstr="" and (resbutmidstr="ok" or reskeymid=13) then
'=== User has clicked the OK button, retrieve the values
text01=fmid.form01.text01.Value '=== namtmp is the variable name used earlier,before we call the dynamic form generation for input
text02=fmid.form01.text02.Value '=== namtmp is the variable name used earlier,before we call the dynamic form generation for input

if len(text01) < 1 then
err01=1
'=== error message for the first form (if the keyword "error" is in this string, its displayed in RED)
if len(text01) < 1 then
errtmp(0)="error - must be 1 char long at least"
else
errtmp(0)="ok"
end if

'=== if the value was not good, we generate the dynamic input for again, with an error message after the form in red
a = dynforgen(distmp,namtmp,deftmp,typtmp,errtmp,buttmp,tit)
'=== there was an invalid input so we reset the key or button pressed to nothing so the loop can continue
reskeymid=0
resbutmidstr=""
else
'=== the input was validated, we flag err01 to none, and flag inpdon to exit the loop
inpdon=1
err01=0
end if
end if
wscript.sleep 100

'=== while we wait for input value, user can press "escape" key, "cancel" button or close internet explorer
if resbutmidstr="cancel" or reskeymid=27 or bready=true or resbutlefstr<>"" then
'=== if user pressed escape or cancel, we clear the frames
if resbutmidstr="cancel" or reskeymid=27 then
a = clefra(array("fmid","fbot"))
resbutmidstr="cancel"
end if
exit do
end if
'=== if there was an input error and no one used left control frame to exit, we keep asking for input
loop while err01<>0 or inpdon=0
   
'=== if internet explorer was not closed (bready), a button was not pressed on left frame, and no excape or cancel in middle frame
if bready=false and resbutlefstr="" and reskeymid<>27 and resbutmidstr<>"cancel" then
a = clefra(array("fmid","fbot"))

strComputer = text02
value01 = text01

fmid.WriteLn("New owner name: " & value01 & "<br>")
fmid.WriteLn("Computer to scan: " & strComputer & "<br>")

'=== WMI

fbot.WriteLn("Getting acces to WMI on the computer...<br>")
err01 = 0: err02 = ""
on error resume next
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
err01 = err
err02 = err.description
on error goto 0

if err01 = 0 then
'=== last logon name on this computer
Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)
fbot.WriteLn("Read owner name...<br>")
For Each objItem in colItems
'net_domain = objItem.Domain
net_user_name = objItem.UserName
system_part_of_domain = objItem.PartOfDomain
system_primary_owner_name = objItem.PrimaryOwnerName

Next

fbot.WriteLn("Owner name before: " & system_primary_owner_name & "<br>")
before01 = net_user_name & vbcrlf & system_primary_owner_name

fbot.WriteLn("Getting remote register base access on: " & strComputer & "...<br>")
err01 = 0: err02 = ""
on error resume next
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv") '=== base de registre access
err01 = err
err02 = err.description
on error goto 0

if err01 <>0 then
fbot.WriteLn("ERROR cannot get remote register base access on: " & strComputer & "<br>")
end if

fbot.WriteLn("Write owner name in remote register base: " & value01 & "...<br>")
d = regwri("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\RegisteredOwner", value01, "REG_SZ")

'=== last logon name on this computer
Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)
For Each objItem in colItems
'net_domain = objItem.Domain
net_user_name = objItem.UserName
system_part_of_domain = objItem.PartOfDomain
system_primary_owner_name = objItem.PrimaryOwnerName

Next

fbot.WriteLn("Owner name after: " & system_primary_owner_name & "<br>")

'=== execute process on remote computer
'a = doprocess(file01,"")
'a = doprocess(sysdir & "\cscript.exe",ser & "\users\audit_v0804_v4.vbs")

process01 = "c:\windows\system32\cscript.exe"
'argument01 = """\\hyntssr5\apps$\Apps\windows 7 sp1 fra pro unattend\sources\$oem$\$1\_util\inventaire\audit_v0804_v4 hyd.vbs"""
argument01 = """C:\_util\inventaire\audit_v0804_v4 hyd.vbs"""

'process01 = "cmd.exe /c"
'argument01 = """c:\_util\MysqlOdbcConnector\vcredist_x86.exe /q /norestart"""

'process01 = "msiexec.exe"
'argument01 = "/i c:\_util\MysqlOdbcConnector\mysql-connector-odbc-5.3.4-win32.msi /quiet"

fbot.WriteLn("<br> Remote executing process and argument:<br>" & process01 & "<br>" & argument01 & "<br>")

a = doprocess(process01, argument01)

fbot.WriteLn("<br>Code returned after remote execution: " & a & "<br>")
'msgbox("before:" & before01 & vbcrlf & "after: " & net_user_name & vbcrlf & system_primary_owner_name)

else

fmid.WriteLn("<br>ERROR opening WMI on target computer<br>")

end if


fbot.WriteLn("<br>FIN<br>")
fmid.WriteLn("<br>FIN<br>")

h = ""
h = h & "</table>"

'fbot.WriteLn(h)

end if

reskeymid=0
resbutmidstr=""

end if

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' scan groups
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
if resbutlefstr="scangroups" then

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' scan users and groups
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

'=== this was a test with multiple button value (one for each line)
a = clefra(array("fmid","fbot"))

x=0
redim preserve distmp(x) :redim preserve namtmp(x) :redim preserve deftmp(x) :redim preserve typtmp(x) :redim preserve errtmp(x)
distmp(x)="what do you want to display"      '===== description displayed in front of the field
namtmp(x)="text01"                  '===== name of variable for programming purpose
deftmp(x)="hello world"           '===== default value inside the form (the form will be 20 char long if no value here, but you can enter more)
typtmp(x)="textbox"               '===== type of data: textbox password (futur: more to come)
errtmp(x)="computer name" '===== text to display after the form "facultatif" blue text "error" red text are special keywords

buttmp=array("ok","cancel")       '===== at the end, there will be an "ok" button and a "cancel" button

a = dynforgen (distmp,namtmp,deftmp,typtmp,errtmp,buttmp,tit)

do
'=== flag to tell if the input is not valid
err01=0
'=== flag to say input is done, since there might be a defaut value, we must validate if user was finished
inpdon=0
'=== "ok" button or "enter" key are the same
'=== and nothing was pressed on left frame (control frame)

if resbutlefstr="" and (resbutmidstr="ok" or reskeymid=13) then
'=== User has clicked the OK button, retrieve the values
text=fmid.form01.text01.Value '=== namtmp is the variable name used earlier,before we call the dynamic form generation for input

if len(text) < 1 then
err01=1
'=== error message for the first form (if the keyword "error" is in this string, its displayed in RED)
if len(text) < 1 then
errtmp(0)="error - must be 1 char long at least"
else
errtmp(0)="ok"
end if

'=== if the value was not good, we generate the dynamic input for again, with an error message after the form in red
a = dynforgen(distmp,namtmp,deftmp,typtmp,errtmp,buttmp,tit)
'=== there was an invalid input so we reset the key or button pressed to nothing so the loop can continue
reskeymid=0
resbutmidstr=""
else
'=== the input was validated, we flag err01 to none, and flag inpdon to exit the loop
inpdon=1
err01=0
end if
end if
wscript.sleep 100

'=== while we wait for input value, user can press "escape" key, "cancel" button or close internet explorer
if resbutmidstr="cancel" or reskeymid=27 or bready=true or resbutlefstr<>"" then
'=== if user pressed escape or cancel, we clear the frames
if resbutmidstr="cancel" or reskeymid=27 then
a = clefra(array("fmid","fbot"))
resbutmidstr="cancel"
end if
exit do
end if
'=== if there was an input error and no one used left control frame to exit, we keep asking for input
loop while err01<>0 or inpdon=0
   

'=== if internet explorer was not closed (bready), a button was not pressed on left frame, and no excape or cancel in middle frame
if bready=false and resbutlefstr="" and reskeymid<>27 and resbutmidstr<>"cancel" then
a = clefra(array("fmid","fbot"))

cn.open "Provider=ADsDSOObject;"
cmd.activeconnection = cn

fbot.WriteLn("<br>Scanning domain computers")
'fbot.WriteLn("<br>directory where xml file is saved: " & basedir)

'strInputPath = basedir & "\serverlist.txt" '- location of input
'strOutputPath = basedir & "\output.csv" '- location of output

'set objFSO = CreateObject("Scripting.FileSystemObject")
'set objTextIn = objFSO.OpenTextFile( strInputPath,1 )
'set objTextOut = objFSO.CreateTextFile( strOutputPath )
'objTextOut.WriteLine("computer,status")

h = "<table width=""100%"" BORDERCOLOR=""black"" class=MsoTableGrid border=1 CELLSPACING=0 cellpadding=2 style='border-collapse:collapse;border:none'>"

'=== domain root
fbot.WriteLn("<br>Getting domain root...")
SET objRoot = GETOBJECT("LDAP://RootDSE")
'for each propName in objRoot.Properties.PropertyNames

'=== DC=quebecormedia,DC=com

defaultNamingContext01 = objRoot.GET("defaultNamingContext")

fbot.WriteLn("<br>" & objRoot.GET("defaultNamingContext"))

defaultNamingContext01 = defaultNamingContext01 & ",OU=gemel"

'=== Query for all computers in the domain
'description Computer description (in AD)
'distinguishedName DN: OU location of the computer account can be read from here. No wildcard matching possible!
'dNSHostName FQDN
'location Location field
'memberOf Groups the computer account is a member of. No wildcard matching possible!
'name Netbios computer name
'operatingSystem e.g. Windows Server 2003
'operatingSystemServicePack e.g. Service Pack 1
'operatingSystemVersion e.g. 5.2 (3790)
'primaryGroupID 515: Computers
'516: Domain Controllers
'sAMAccountName Computer account name (name$)
'sAMAccountType always 805306369 (computer account)
'servicePrincipalName list of registered SPNs

'=== nice doc on ldap queries
'http://ldapwiki.willeke.com/wiki/Active%20Directory%20Computer%20Related%20LDAP%20Query#section-Active+Directory+Computer+Related+LDAP+Query-FindAllWorkstations

cmd.commandtext = "<LDAP://" & objRoot.GET("defaultNamingContext") & ">;(objectCategory=Group);dnsHostName,distinguishedName,description"
'**** Bypass 1000 record limitation ****
cmd.properties("page size")=1000
fbot.WriteLn("<br>Getting computers...")
SET rs = cmd.EXECUTE

fbot.WriteLn("<br>Looping through computers...")
fbot.WriteLn("<br>")

'=== check all columns in the recordset (debug separator was , not ; )
test=0
if test=1 then
compucnt01 = 0
rs.movefirst
WHILE rs.eof<>true AND rs.bof<>true and compucnt01<1
for each field01 in rs.fields
fbot.WriteLn("<br>Field: " & field01.name)
next
rs.movenext
compucnt01 = compucnt01 + 1
wend
end if

'=== want to see progress live, make talbe now in html frame
fbot.WriteLn(h)

compucnt01 = 0
compucnt02 = 0
rs.movefirst
WHILE rs.eof <> true AND rs.bof <> true
'=== WRTIE A DOT EVERY 20 RECORDS
IF compucnt02/10 = INT(compucnt02/10) THEN fbot.WriteLn(".")

distinguishedName01 = lcase(rs("distinguishedName"))
dnsHostName01 = rs("dnsHostName")
description01 = rs("description")

'fbot.WriteLn("<br>Description is vartype: " & vartype(description01))

'=== is the computer from bloobuzz?
if instr(distinguishedName01, "ou=gemel groupes")<>0 then
'=== bloobuzz total
compucnt01 = compucnt01 + 1

h = ""
h = h & "<tr>" '=== line 1
h = h & "<td>" & compucnt01 & "</td>"
'h = h & "<td>" & dnsHostName01 & "</td>"
h = h & "<td>" & distinguishedName01 & "</td>"
if vartype(description01) = 8204 then
for each des02 in description01
h = h & "<td>" & des02 & "</td>"
next
else
h = h & "<td>" & description01 & "</td>"
end if

'=== go inside each group to list members
strContainer = "cn=TicPriv"

strContainer = left(distinguishedName01,instr(distinguishedName01,",")-1)

wanted01 = strContainer & ", ou=gemel groupes, " & objRoot.GET("defaultNamingContext")
fmid.WriteLn("<br>" &  wanted01)

Set objGroup = GetObject("LDAP://" & wanted01 )
objGroup.getInfo

on error resume next
err01 = 0 : err02 = ""
arrMemberOf = objGroup.GetEx("member")
err01 = err
err02 = err.description
on error goto 0

if err01 = 0 then
h = h & "<td>"
for each member01 in arrmemberof
h = h & member01 & "<br>"
next
h = left(h,len(h)-4) '=== remove <br>
h = h & "</td>"

end if
'=== testing
test=0
if test =1 then
cmd.commandtext = "<LDAP://" & objRoot.GET("defaultNamingContext") & ">;(objectCategory=User);dnsHostName,distinguishedName,description"
'**** Bypass 1000 record limitation ****
cmd.properties("page size")=1000
fmid.WriteLn("<br>Getting users...")
SET rs2 = cmd.EXECUTE
if  rs2.eof <> true AND rs2.bof <> true then
rs2.movefirst
WHILE rs2.eof <> true AND rs2.bof <> true
distinguishedName02 = lcase(rs2("distinguishedName"))
if instr(lcase(distinguishedName02), "serge fournier")<>0 then
h = h & "<td>rs2: " & distinguishedName02 & "</td>"
else
'fmid.WriteLn("<br>" & distinguishedName02)
end if
rs2.movenext
wend
else
'=== no records / results
'fmid.WriteLn("<br>ERROR - 0 results")

end if
end if
''''''''''''''''''''''''''''
' end of line in table
''''''''''''''''''''''''''''
h = h & "</tr>"
fbot.WriteLn(h)
else
'fbot.WriteLn(distinguishedName01 & " --- " & dnsHostName01 & "<br>")
end if '=== bbz found

compucnt02 = compucnt02 + 1
rs.movenext

wend

fmid.WriteLn("FIN")

h = ""
h = h & "</table>"

fbot.WriteLn(h)

end if

reskeymid=0
resbutmidstr=""

end if


if resbutlefstr="scan" then

'''''''''''''''''''''''''''''''''''''''''''''''''''''''
' scan computers
'''''''''''''''''''''''''''''''''''''''''''''''''''''''

'=== this was a test with multiple button value (one for each line)
a = clefra(array("fmid","fbot"))

x=0
redim preserve distmp(x) :redim preserve namtmp(x) :redim preserve deftmp(x) :redim preserve typtmp(x) :redim preserve errtmp(x)
distmp(x)="what do you want to display"      '===== description displayed in front of the field
namtmp(x)="text01"                  '===== name of variable for programming purpose
deftmp(x)="hello world"           '===== default value inside the form (the form will be 20 char long if no value here, but you can enter more)
typtmp(x)="textbox"               '===== type of data: textbox password (futur: more to come)
errtmp(x)="computer name" '===== text to display after the form "facultatif" blue text "error" red text are special keywords

buttmp=array("ok","cancel")       '===== at the end, there will be an "ok" button and a "cancel" button

a = dynforgen (distmp,namtmp,deftmp,typtmp,errtmp,buttmp,tit)

do
'=== flag to tell if the input is not valid
err01=0
'=== flag to say input is done, since there might be a defaut value, we must validate if user was finished
inpdon=0
'=== "ok" button or "enter" key are the same
'=== and nothing was pressed on left frame (control frame)

if resbutlefstr="" and (resbutmidstr="ok" or reskeymid=13) then
'=== User has clicked the OK button, retrieve the values
text=fmid.form01.text01.Value '=== namtmp is the variable name used earlier,before we call the dynamic form generation for input

if len(text) < 1 then
err01=1
'=== error message for the first form (if the keyword "error" is in this string, its displayed in RED)
if len(text) < 1 then
errtmp(0)="error - must be 1 char long at least"
else
errtmp(0)="ok"
end if

'=== if the value was not good, we generate the dynamic input for again, with an error message after the form in red
a = dynforgen(distmp,namtmp,deftmp,typtmp,errtmp,buttmp,tit)
'=== there was an invalid input so we reset the key or button pressed to nothing so the loop can continue
reskeymid=0
resbutmidstr=""
else
'=== the input was validated, we flag err01 to none, and flag inpdon to exit the loop
inpdon=1
err01=0
end if
end if
wscript.sleep 100

'=== while we wait for input value, user can press "escape" key, "cancel" button or close internet explorer
if resbutmidstr="cancel" or reskeymid=27 or bready=true or resbutlefstr<>"" then
'=== if user pressed escape or cancel, we clear the frames
if resbutmidstr="cancel" or reskeymid=27 then
a = clefra(array("fmid","fbot"))
resbutmidstr="cancel"
end if
exit do
end if
'=== if there was an input error and no one used left control frame to exit, we keep asking for input
loop while err01<>0 or inpdon=0
   

'=== if internet explorer was not closed (bready), a button was not pressed on left frame, and no excape or cancel in middle frame
if bready=false and resbutlefstr="" and reskeymid<>27 and resbutmidstr<>"cancel" then
a = clefra(array("fmid","fbot"))

cn.open "Provider=ADsDSOObject;"
cmd.activeconnection = cn

fbot.WriteLn("<br>Scanning domain computers")
'fbot.WriteLn("<br>directory where xml file is saved: " & basedir)

strInputPath = basedir & "\serverlist.txt" '- location of input
strOutputPath = basedir & "\output.csv" '- location of output

set objFSO = CreateObject("Scripting.FileSystemObject")
'set objTextIn = objFSO.OpenTextFile( strInputPath,1 )
set objTextOut = objFSO.CreateTextFile( strOutputPath )
objTextOut.WriteLine("computer,status")

h = "<table width=""100%"" BORDERCOLOR=""black"" class=MsoTableGrid border=1 CELLSPACING=0 cellpadding=2 style='border-collapse:collapse;border:none'>"

'=== domain root
fbot.WriteLn("<br>Getting domain root...")
SET objRoot = GETOBJECT("LDAP://RootDSE")
'for each propName in objRoot.Properties.PropertyNames
'=== DC=quebecormedia,DC=com

defaultNamingContext01 = objRoot.GET("defaultNamingContext")

fbot.WriteLn("<br>" & objRoot.GET("defaultNamingContext"))

defaultNamingContext01 = defaultNamingContext01 & ",OU=gemel"

'=== Query for all computers in the domain
'description Computer description (in AD)
'distinguishedName DN: OU location of the computer account can be read from here. No wildcard matching possible!
'dNSHostName FQDN
'location Location field
'memberOf Groups the computer account is a member of. No wildcard matching possible!
'name Netbios computer name
'operatingSystem e.g. Windows Server 2003
'operatingSystemServicePack e.g. Service Pack 1
'operatingSystemVersion e.g. 5.2 (3790)
'primaryGroupID 515: Computers
'516: Domain Controllers
'sAMAccountName Computer account name (name$)
'sAMAccountType always 805306369 (computer account)
'servicePrincipalName list of registered SPNs

'=== nice doc on ldap queries
'http://ldapwiki.willeke.com/wiki/Active%20Directory%20Computer%20Related%20LDAP%20Query#section-Active+Directory+Computer+Related+LDAP+Query-FindAllWorkstations

cmd.commandtext = "<LDAP://" & objRoot.GET("defaultNamingContext") & ">;(objectCategory=Computer);dnsHostName,distinguishedName,description"
'**** Bypass 1000 record limitation ****
cmd.properties("page size")=1000
fbot.WriteLn("<br>Getting computers...")
SET rs = cmd.EXECUTE

fbot.WriteLn("<br>Looping through computers...")
fbot.WriteLn("<br>")


'=== check all columns in the recordset (debug separator was , not ; )
test=0
if test=1 then
compucnt01 = 0
rs.movefirst
WHILE rs.eof<>true AND rs.bof<>true and compucnt01<1
for each field01 in rs.fields
fbot.WriteLn("<br>Field: " & field01.name)
next
rs.movenext
compucnt01 = compucnt01 + 1
wend
end if

'=== want to see progress live, make talbe now in html frame
fbot.WriteLn(h)

compucnt01 = 0
compucnt02 = 0
rs.movefirst
WHILE rs.eof <> true AND rs.bof <> true
'=== WRTIE A DOT EVERY 20 RECORDS
IF compucnt02/10 = INT(compucnt02/10) THEN fbot.WriteLn(".")

distinguishedName01 = lcase(rs("distinguishedName"))
dnsHostName01 = rs("dnsHostName")
'=== is the computer from bloobuzz?
if instr(distinguishedName01, "dc=gemel,dc=ca")<>0 then
'=== bloobuzz total
compucnt01 = compucnt01 + 1

h = ""
h = h & "<tr>" '=== line 1
h = h & "<td>" & compucnt01 & "</td>"
h = h & "<td>" & dnsHostName01 & "</td>" '<td>" & distinguishedName01 & "</td>"

ping01 = ping(dnsHostName01)
h = h & "<td>" & ping01 & "</td>"
'fmid.WriteLn("ping " & dnsHostName01 & " " &  ping01)


if ping01 = true then
'=== last logonname of this computer

strComputer = dnsHostName01
err01 = 0: err02 = ""
on error resume next
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
err01 = err
err02 = err.description
on error goto 0

if err01 = 0 then

'=== last logon name on this computer
Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)
For Each objItem in colItems
'net_domain = objItem.Domain
net_user_name = objItem.UserName
Next
h = h & "<td>" & net_user_name & "</td>"

mem01 = 0
if mem01 = 1 then

'''''''''''''''''''''''''''
'   Memory Information
'''''''''''''''''''''''''''
if verbose = "y" then
  'objOutputFile.WriteLine date & " " & time & " Memory Info ... DEBUT"
  'wscript.echo "Memory Info"
end if
'sql = "DELETE FROM memory WHERE memory_mac_address = '" & net_mac_address & "'"
'create_sql sql, objTextFile, database

Set colItems = objWMIService.ExecQuery("Select MemoryDevices FROM Win32_PhysicalMemoryArray",,48)
For Each objItem in colItems
  system_memory_banks = objItem.MemoryDevices
Next

On Error Resume Next

Set colItems = objWMIService.ExecQuery("Select Capacity,DeviceLocator,FormFactor,MemoryType,TypeDetail,Speed FROM Win32_PhysicalMemory",,48)
mem_count = 0
For Each objItem in colItems
  mem_count = mem_count + 1
  If mem_count > int(system_memory_banks) then
  Exit For
  End If
  If objItem.FormFactor = "7" then
 mem_formfactor = "SIMM"
  ElseIf objItem.FormFactor = "8" then
 mem_formfactor = "DIMM"
  ElseIf objItem.FormFactor = "11" then
 mem_formfactor = "RIMM"
  ElseIf objItem.FormFactor = "12" then
 mem_formfactor = "SODIMM"
  ElseIf objItem.FormFactor = "13" then
 mem_formfactor = "SRIMM"
  Else
 mem_formfactor = "Unknown"
  End If

  If objItem.MemoryType = "0" then
 mem_detail = "Unknown"
  ElseIf objItem.MemoryType = "1" then
 mem_detail = "Other"
  ElseIf objItem.MemoryType = "2" then
 mem_detail = "DRAM"
  ElseIf objItem.MemoryType = "3" then
 mem_detail = "Synchronous DRAM"
  ElseIf objItem.MemoryType = "4" then
 mem_detail = "Cache DRAM"
  ElseIf objItem.MemoryType = "5" then
 mem_detail = "EDO"
  ElseIf objItem.MemoryType = "6" then
 mem_detail = "EDRAM"
  ElseIf objItem.MemoryType = "7" then
 mem_detail = "VRAM"
  ElseIf objItem.MemoryType = "8" then
 mem_detail = "SRAM"
  ElseIf objItem.MemoryType = "9" then
 mem_detail = "RAM"
  ElseIf objItem.MemoryType = "10" then
 mem_detail = "ROM"
  ElseIf objItem.MemoryType = "11" then
 mem_detail = "Flash"
  ElseIf objItem.MemoryType = "12" then
 mem_detail = "EEPROM"
  ElseIf objItem.MemoryType = "13" then
 mem_detail = "FEPROM"
  ElseIf objItem.MemoryType = "14" then
 mem_detail = "EPROM"
  ElseIf objItem.MemoryType = "15" then
 mem_detail = "CDRAM"
  ElseIf objItem.MemoryType = "16" then
 mem_detail = "3DRAM"
  ElseIf objItem.MemoryType = "17" then
 mem_detail = "SDRAM"
  ElseIf objItem.MemoryType = "18" then
 mem_detail = "SGRAM"
  ElseIf objItem.MemoryType = "19" then
 mem_detail = "RDRAM"
  ElseIf objItem.MemoryType = "20" then
 mem_detail = "DDR"
  End If

  If objItem.TypeDetail = "1" then
 mem_typedetail = "Reserved"
  ElseIf objItem.TypeDetail = "2" then
 mem_typedetail = "Other"
  ElseIf objItem.TypeDetail = "4" then
 mem_typedetail = "Unknown"
  ElseIf objItem.TypeDetail = "8" then
 mem_typedetail = "Fast-paged"
  ElseIf objItem.TypeDetail = "16" then
 mem_typedetail = "Static column"
  ElseIf objItem.TypeDetail = "32" then
 mem_typedetail = "Pseudo-static"
  ElseIf objItem.TypeDetail = "64" then
 mem_typedetail = "RAMBUS"
  ElseIf objItem.TypeDetail = "128" then
 mem_typedetail = "Synchronous"
  ElseIf objItem.TypeDetail = "256" then
 mem_typedetail = "CMOS"
  ElseIf objItem.TypeDetail = "512" then
 mem_typedetail = "EDO"
  ElseIf objItem.TypeDetail = "1024" then
 mem_typedetail = "Window DRAM"
  ElseIf objItem.TypeDetail = "2048" then
 mem_typedetail = "Cache DRAM"
  ElseIf objItem.TypeDetail = "4096" then
 mem_typedetail = "Non-volatile"
  Else
 mem_typedetail = "Unknown"
  End If

  sql = "INSERT INTO memory ( memory_mac_address, memory_bank, " _
  & "memory_form_factor, memory_type, memory_detail, memory_capacity, memory_speed) " _
  & "VALUES ('" _
  & net_mac_address & "','" _
  & objItem.DeviceLocator & "','" _
  & mem_formfactor & "','" _
  & mem_detail & "','" _
  & mem_typedetail & "','" _
  & int(objItem.Capacity /1024 /1024) & "','" _
  & objItem.Speed & "')"
  'create_sql sql, objTextFile, database
Next
'sql = ""
'objOutputFile.WriteLine date & " " & time & " Memory Info ... FIN"

h = h & "<td>memory info " & sql & " </td>"
end if '=== mem01
else
'=== wmi error
h = h & "<td>ERROR WMI</td>"
end if '=== on error

else
'=== ping did not succeed

end if '=== ping true

''''''''''''''''''''''''''''
' end of line in table
''''''''''''''''''''''''''''
h = h & "</tr>"
fbot.WriteLn(h)
else
fbot.WriteLn(distinguishedName01 & " --- " & dnsHostName01 & "<br>")
end if '=== bbz found

compucnt02 = compucnt02 + 1
rs.movenext

wend

fmid.WriteLn("FIN")

h = ""
h = h & "</table>"

fbot.WriteLn(h)

end if

reskeymid=0
resbutmidstr=""

end if
 
   '=== if the button named this is pressed we do this
   '=== resbutlefstr: result from pressing a button in the left frame (control frame, flef object)
   '=== its a string that contain the programmable name of the button that was pressed in the left frame (arabutnam)
 
   if resbutlefstr="clrframes" then

      a = clefra(array("fmid","fbot"))

      'fbot.WriteLn("tried to clear middle frame")
 
   end if
 
   if resbutlefstr="info" then
      a = clefra(array("fmid","fbot"))
   
      '=== print button
      aa = lcase(fbot.readystate)
      do until aa="complete" or aa="terminé" or aa="interactive"
         'if logall = 1 then fil02.writeline "*********************************** readystate of " & ffranam & ": " & aa
         wscript.sleep 100
         aa = lcase(fbot.readystate)
      loop
     
      for each a in priara
         fbot.WriteLn(a)
      next
      for each a in botara
         fbot.WriteLn(a)
      next
   
 
      fbot.WriteLn("<H2>Crucible Cleaner Troubleshooting Database with Dynamic Web Interface</H2><br>")
 
      texara=array(_
      "",_
      "1. REQUIREMENTS:",_
      "1.1 Microsoft windows xp, vista (32 or 64), seven (32 or 64) (without UAC, users access control, off)",_
      "1.2 Internet explorer",_
      "1.3 .NET framework 1.1 (included with windows)",_
      "1.4 microsoft access database: 45834_crucible_cleaning_diagnostic.mdb",_
      "1.5 images directory: PhotoHydComponent",_
      "",_
      "2. CARACTERISTICS:",_
      "",_
      "2.1 This dynamic web interface was programmed to access a microsoft access database information to troubleshoot a Crucible Cleaner",_
      "",_
      "3. REFERENCES:",_
      "",_
      "3.1 This program was made by STAS",_
      "3.2 STAS project number: 45834",_
      "",_
      "STAS Inc.",_
      "1846 Outarde, Chicoutimi (Qué.), Canada G7K 1H1",_
      "Tél.: 418-545-6574",_
      "Fax 1: 418-545-8335, Fax 2: 418-696-1951",_
      "Email: fournier.serge@STAS.com",_
      "Contact: Serge Fournier, Prog./Analyst")
   
      for each a in texara
         aa = lcase(fbot.readystate)
         do until aa="complete" or aa="terminé" or aa="interactive"
            if logall = 1 then fil02.writeline "*********************************** readystate of " & ffranam & ": " & aa
            wscript.sleep 100
            aa = lcase(fbot.readystate)
         loop
         fbot.WriteLn(a & "<br>")
      next
      aa = lcase(fbot.readystate)
      do until aa="complete" or aa="terminé" or aa="interactive"
         if logall = 1 then fil02.writeline "*********************************** readystate of " & ffranam & ": " & aa
         wscript.sleep 100
         aa = lcase(fbot.readystate)
      loop
   
      fbot.location.reload(true)
   
      reskeymid=0
      resbutmidstr=""
   
   end if
 
   '=== .1 seconds
   wscript.sleep 50
 
'=== we loop until internet explorer was closed or the quit button was pressed
loop until bReady or resbutlefstr="quit01"

'======================
'====================== end of main loop
'======================

'=== someone pressed "quit" on left frame (control frame, flef object)

'=== at the end, if internet explorer was not closed, we close it
if bready=false then
   oie.quit
   set oie=nothing
end if
if logall=1 then
   fil02.WriteLine date & " " & time & " END"
end if
if logall = 1 then
   fil02.close
end if

'=== we end wscript.exe, exiting all running code interpretation
wscript.quit

'==================================================================================================

'=== many subs

'=== if internet explorer is closed (event) we change bready value to TRUE
sub IE_onQuit()
   bReady=true
end sub


'============================================== subs and functions ====================================

'=== frames clear content by navigating to a blank
'=== input is an array containing name of frames as "flef" = frame left
'=== this sub generate a code and execute it in a string (cc)
'=== fully dynamic programming at it's best ;)

function clefra(aara)
 
   cc=""
   for each aa in aara
      'cc = cc & "Do While (oIE.Busy)" & vbcrlf
      'cc = cc & "   wscript.sleep 200" & vbcrlf
      'cc = cc & "Loop" & vbcrlf
      'cc = cc & "Do While oie.readystate<>4" & vbcrlf
      'cc = cc & "   wscript.sleep 200" & vbcrlf
      'cc = cc & "Loop" & vbcrlf
      'cc = cc & aa & ".location.reload(true)" & vbcrlf
      'cc = cc & "Do While (oIE.Busy)" & vbcrlf
      'cc = cc & "   wscript.sleep 200" & vbcrlf
      'cc = cc & "Loop" & vbcrlf
      'cc = cc & "Do While oie.readystate<>4" & vbcrlf
      'cc = cc & "   wscript.sleep 200" & vbcrlf
      'cc = cc & "Loop" & vbcrlf
      'cc = cc & aa & ".WriteLn(""&nbsp;"")" & vbcrlf
      'cc = cc & aa & ".location.reload(true)" & vbcrlf
      'cc = cc & "Do While oie.readystate<>4" & vbcrlf
      'cc = cc & "   wscript.sleep 200" & vbcrlf
      'cc = cc & "Loop" & vbcrlf
      'cc = cc & "Do While (oIE.Busy)" & vbcrlf
      'cc = cc & "   wscript.sleep 200" & vbcrlf
      'cc = cc & "Loop" & vbcrlf
      'cc = cc & "Do until " & aa & ".ReadyState = ""Terminé"" or " & aa & ".ReadyState = ""Complete""" & vbcrlf
      'cc = cc & "   wscript.sleep 200" & vbcrlf
      'cc = cc & "Loop" & vbcrlf
   
      '•uninitialized - Has not started loading yet
      '•loading - Is loading
      '•interactive - Has loaded enough and the user can interact with it
      '•complete - Fully loaded


      htmtab=""
      if aa = "flef" then
         aa = lcase(flef.readystate)
         do until aa="complete" or aa="terminé" or aa="interactive"
            if logall=1 then fil02.writeline "*********************************** readystate of flef: " & aa
            wscript.sleep 100
            aa = lcase(flef.readystate)
         loop
         htmtab = htmtab & "&nbsp;"
         aa = lcase(flef.readystate)
         do until aa="complete" or aa="terminé" or aa="interactive"
            if logall=1 then fil02.writeline "*********************************** readystate of flef: " & aa
            wscript.sleep 100
            aa = lcase(flef.readystate)
         loop
         for each a in lefara
            htmtab = htmtab & a
         next
         flef.writeln(htmtab)
         flef.location.reload(true)
         aa = lcase(flef.readystate)
         do until aa="complete" or aa="terminé" or aa="interactive"
            if logall=1 then fil02.writeline "*********************************** readystate of flef: " & aa
            wscript.sleep 100
            aa = lcase(flef.readystate)
         loop    
      end if
   
      if aa = "fmid" then
         aa = lcase(fmid.readystate)
         do until aa="complete" or aa="terminé" or aa="interactive"
            if logall=1 then fil02.writeline "*********************************** readystate of fmid: " & aa
            wscript.sleep 100
            aa = lcase(fmid.readystate)
         loop
         htmtab = htmtab & "&nbsp;"
         aa = lcase(fmid.readystate)
         do until aa="complete" or aa="terminé" or aa="interactive"
            if logall=1 then fil02.writeline "*********************************** readystate of fmid: " & aa
            wscript.sleep 100
            aa = lcase(fmid.readystate)
         loop
         for each a in midara
            htmtab = htmtab & a
         next
         fmid.writeln(htmtab)
       
         fmid.location.reload(true)
         aa = lcase(fmid.readystate)
         do until aa="complete" or aa="terminé" or aa="interactive"
            if logall=1 then fil02.writeline "*********************************** readystate of fmid: " & aa
            wscript.sleep 100
            aa = lcase(fmid.readystate)
         loop
         if logall=1 then fil02.writeline "mid frame cleared----------- ccc -----------"                    
      end if
   
      if aa = "fbot" then
         aa = lcase(fbot.readystate)
         do until aa="complete" or aa="terminé" or aa="interactive"
            if logall = 1 then fil02.writeline "*****************111****************** readystate of fbot: " & aa
            wscript.sleep 100
            aa = lcase(fbot.readystate)
         loop
         htmtab = htmtab & "&nbsp;"
         aa = lcase(fbot.readystate)
         do until aa="complete" or aa="terminé" or aa="interactive"
            if logall = 1 then fil02.writeline "*****************222****************** readystate of fbot: " & aa
            wscript.sleep 100
            aa = lcase(fbot.readystate)
         loop
         for each a in midara
            htmtab = htmtab & a
         next
         fbot.writeln(htmtab)
       
         fbot.location.reload(true)
         aa = lcase(fbot.readystate)
         do until aa="complete" or aa="terminé" or aa="interactive"
            if logall = 1 then fil02.writeline "*****************333****************** readystate of fbot: " & aa
            wscript.sleep 100
            aa = lcase(fbot.readystate)
         loop                
      end if
   
   next

   'execute cc
 
   '=== we also clear the variables used to control the action buttons and the key pressed in each frames
   '=== so the action wont be taken twice (or infinitly) in the main loop
 
   'set flef = oie.document.frames("left").document
   'set fmid = oie.document.frames("middle").document
   'set fbot = oie.document.frames("bottom").document
 
'for i=0 to ubound(arabutnam)
'   flef.forms(0).elements(arabutnam(i)).onclick = getref("buttonlef")
'next

'=== we also chek the key presse in each frame
'=== we do this cause we want "enter" key to be used instead of pressing "ok" button with the mouse
'set flef.onkeypress = GetRef("Checklef")
'set fmid.onkeypress = GetRef("Checkmid")
'set fbot.onkeypress = GetRef("Checkbot")

   resbutlefstr = ""
   resbutmidstr = ""
   resbutbotstr = ""
   reskeylef = 0
   reskeymid = 0
   reskeybot = 0

end function

'=== form dynamically generated =========================================================================

function dynforgen (distmp, namtmp,deftmp,typtmp,errtmp,buttmp,title)
 
   '=== generate a form for input in the input frame (fmid object)
   '=== focus on the first field with no default value
   '=== display suffix message in red if "error" (or "erreur" - french) keyword is in it
   htmtab=""
 
   for each a in midara
      htmtab = htmtab & a
   next
 
   htmtab = htmtab & "<h3><span class=SpellE>" & title & "</span></h3>"
   '=== default focus on empty field (with no default value)
   deffoc=0
   for ii=0 to ubound(namtmp)
      if deftmp(ii)="" then
         if instr(lcase(errtmp(ii)),"facultatif")=0 then
            htmtab = htmtab & "<BODY onLoad=""document.form01." & namtmp(ii) & ".focus()"">"
            deffoc=1
         end if
      end if
      '=== no default value empty, we focus on first field
   next
   if deffoc=0 then
      htmtab = htmtab & "<BODY onLoad=""document.form01." & namtmp(0) & ".focus()"">"
   end if
   htmtab = htmtab & "<div class=MsoNormal align=center style='text-align:center'>"
   htmtab = htmtab & "</div>"

   htmtab = htmtab & "<form name=form01>"

   '=== button and error message
   for ii=0 to ubound(namtmp)

      htmtab = htmtab & distmp(ii) & ": "

      '=== we disable "enter" to submit form because we manage this event as a onkeypress in the parent frame of the form later
      '=== we had to do this, because the web page form is not run on a server, and the web page dont have control, the VBS script outside the page have control
   
      htmtab = htmtab & "<input type=""" & typtmp(ii) & """ id=" & namtmp(ii) & " NAME=""" & namtmp(ii) & """ size=""" & max(20,len(deftmp(ii))) & """ value=""" & deftmp(ii) & """ onKeypress=""return event.keyCode!=13"""
      'fmid.WriteLn("")
      if instr(lcase(errtmp(ii)),"error")<>0 or instr(lcase(errtmp(ii)),"erreur")<>0 then
         col="red"
      else
         col="blue"
      end if
      htmtab = htmtab & "&nbsp; <b><span style='color:" & col & "'>&nbsp" & errtmp(ii) & "</span></b><br style='mso-special-character:line-break'>"
   next

   htmtab = htmtab & "<![if !supportLineBreakNewLine]><br style='mso-special-character:line-break'>"
   htmtab = htmtab & "<![endif]></p>"
 
   for ii=0 to ubound(buttmp)
      typ01 = "button"
      htmtab = htmtab & "<input type=""" & typ01 & """ name=""" & buttmp(ii) & """ value=""&nbsp;" & buttmp(ii) & "&nbsp;"">"
      htmtab = htmtab & "&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"
   next
 
   htmtab = htmtab & "</div>"
   htmtab = htmtab & "</form>"
   htmtab = htmtab & "</body>"
   htmtab = htmtab & "</html>"
   fmid.writeln htmtab
   fmid.location.reload(true)

   '=== wait for internet explorer to be ready after we refresh the page with the new form
   for ii=0 to ubound(buttmp)
      Do While (oIE.Busy)
         wscript.sleep 100
      loop
      do while oie.readystate<>4
         wscript.sleep 100
      Loop
      '=== value to return for each button in the form
      fmid.forms(0).elements(buttmp(ii)).onclick = getref("buttonmid")
   next
 
   '=== regenerate the event that call a sub if a button is pressed
   set fmid.onkeypress = GetRef("Checkmid")
 
   '=== clear button pressed and key pressed for this frame
   resbutmidstr=""
   reskeymid=0
end function

'===  max
Function max(a, b)
If a > b Then max = a Else max = b
End Function

function crewebmai(oie, doctit, maitit, arabutnam, arabutdes, aradepnam, aradepcol)

'=== create an internet explorer object (oie) that will be in 3 frames (flef, fmid, fbot), acting at the main interface for all this program

oie.FullScreen = False
'.ToolBar   = False
'.StatusBar = False
'.Navigate("About:Blank")
'.visible = true

oIE.left=0 ' window position
oIE.top = 0 ' and other properties
'.ParentWindow
'        .resizeto 640,300
'        .moveto (.screen.width
oIE.height = 500
oIE.width = 500
oIE.menubar = 1 '=== no menu
oIE.toolbar = 1
oIE.statusbar = 1
oIE.RegisterAsDropTarget = True
oie.Navigate("about:blank")
'oie.Navigate("about:tabs")
oie.document.title = doctit
oiewid = oie.document.parentwindow.screen.width
oiehei = oie.document.parentwindow.screen.height
sizwidpercent = 100
sizheipercent = 95
loswid = 100-sizwidpercent
loshei = 100-sizheipercent
newwid = oiewid*sizwidpercent*.01
newhei = oiehei*sizheipercent*.01
oie.document.parentwindow.resizeto newwid,newhei
newx = oiewid * loswid * .01 /2
newy = oiehei * (loshei/2) * .01 /2
oie.document.parentwindow.moveto newx, newy
oIE.visible = 1 '=== visible on
oie.addressbar=false

'=== we will always have 3 frames, control, input and output (flef, fmid, fbot)
'=== used an array to have a good view of the line of html and possibility to add something else easily

aratmp=array(_
"<HTML>",_
"<HEAD><TITLE>" & doctit & "</TITLE>",_
"<meta content=""text/html; charset=utf-8"" http-equiv=""Content-Type"">",_
"<meta http-equiv=""X-UA-Compatible"" content=""IE=8"">",_
"</HEAD>",_
"<FRAMESET id='main' COLS=""13%, *"">",_
"<FRAME SRC=""About:Blank"" NAME=""left"" id=""left"">",_
"<frameset id='main2' rows=""30%,70%"">",_
"<FRAME SRC=""About:Blank"" NAME=""middle"" id=""middle"">",_
"<FRAME SRC=""About:Blank"" NAME=""bottom"" id=""bottom"">",_
"</FRAMESET>", _
"</frameset>", _
"</HTML>")

'oie.Navigate("About:Blank")

'=== send the array content in internet explorer to create 3 frames
for i = 0 to UBound(aratmp, 1)
   oie.document.WriteLn(aratmp(i))
next

oie.refresh

Do While (oIE.Busy)
   wscript.sleep 50
Loop

'=== wait till document loaded
do while oie.readystate<>4
   wscript.sleep 50
Loop

'=== vista activate
'=== make internet explorer the main active window
a = objShe.AppActivate("http:/// - " & doctit & " - M")
a = objShe.AppActivate(doctit & " - M")

'=== theses objects are used to send data to the 3 different frames
'=== if you dont define them as object, the access to them is very slow when we use the names instead of the objects

'=== object used to write in a frame with writeln
fileversion = objFSO.GetFileVersion("C:\program files\internet explorer\iexplore.exe")
finddot = instr(fileversion,".")
fileversion2 = left(fileversion,finddot-1)

if fileversion2 = "10" or fileversion2 = "11" then
'=== ie10 frame access
set flef = oie.parent.document.getElementByid("left").contentdocument
set fmid = oie.parent.document.getElementByid("middle").contentdocument
set fbot = oie.parent.document.getElementByid("bottom").contentdocument
else
set flef = oie.document.frames("left").document
set fmid = oie.document.frames("middle").document
set fbot = oie.document.frames("bottom").document
end if

'=== object used to navigate an empty page in a frame
'set flefl = oie.document.frames("left").location
'set fmidl = oie.document.frames("middle").location
'set fbotl = oie.document.frames("bottom").location

'=== string result for a button press in a frame (lef = left frame, mid = middle frame (up))
resbutlefstr=""
resbutmidstr=""
resbutbotstr=""

reskeylef=0
reskeymid=0
reskeybot=0

'=== all the chek to be made in first page (1 at the moment, since ready have many values)

nbrbut=UBound(arabutnam, 1)
redim buttag(nbrbut)
form = "flef"

flef.WriteLn("<html><body>")
flef.WriteLn("<body background=""" & basedir & "images_interface\fond_gauche.jpg"">")
flef.WriteLn("<h3><span class=SpellE>" & maitit & "</span></h3>")
flef.WriteLn("<form name='form1'>")

'(1) Where you want the image to appear: <span id="image"></span>

'(2) Get a reference to it: var e = document.getElementById('image');

'(3) Insert the img HTML code into the span: e.innerHTML = '<img src="./images/your_picture.jpg" />';

'aa = """file:///" & basedir & "PhotoHydComponent\002-00_HydroCraft_HC-EC_EndCover.jpg"""
'aa = "'" & basedir & "PhotoHydComponent\002-00_HydroCraft_HC-EC_EndCover.jpg'"
'aa = """./test.jpg"""
'aa = replace(aa,"\","/")
htmtab = ""
'htmtab = htmtab & "<img src=" & aa & " alt=" & aa & " />"

fmid.location.reload(true)
'msgbox(htmtab)
'oie.document.getElementById("middle").document.body.innerhtml = htmtab
'document.getElementById("myiframe").contentWindow.document.body.innerHTML = "<input type='button' value='Click' onclick='parent.buttonClick()'>";
'<script type="text/javascript">


'<script type="text/javascript">
'function chanceImage() {
'document.getElementById('image).innerHTML = '<img src="image.png" alt="Image" border="0">';
'}
'</script>

'htmtab = ""
'htmtab = htmtab & "<script type=""text/javascript"">"
'htmtab = htmtab & "document.getElementById(""middle"").contentWindow.document.body.innerHTML = '<img src=" & aa & " alt=""Image"" border=""0"">';"
'htmtab = htmtab & "</script>"

'fmid.writeln htmtab
'fmid.location.reload(true)
oie.document.getElementById("middle").contentWindow.document.body.innerhtml = htmtab

'fmid.location.reload(true)

for i=0 to ubound(arabutnam)
 
   '=== convert xls to mdb button appear for stas only
 
   if ((usenam="wildboy" or usenam="fournier.serge" or usenam="fortin.jp" or usenam="lavoie.daniel" or usenam="doucet.gm") and arabutnam(i)="excel2mdb") or arabutnam(i)<>"excel2mdb" then
 
      'style="background-color: #cc0000; color: #ffffff;" /
      b = "<input type=""button"" style=""height:50px;font-size:14px;width:100%;"" name=""" & arabutnam(i) & """ value=""" & arabutdes(i) & """"
      i2=i
      if i>ubound(aradepnam) then
         i2=ubound(aradepnam)
      else
         a=aradepnam(i2)
      end if

      if a<>lasdep then
         '=== new departement name
         flef.WriteLn( "<br>" & a & "<br>")
         lasdep=a    
      end if
      b = b & " style=""background-color: #" & aradepcol(i2) & "; color: #000000;""><br>"
      flef.WriteLn(b)
   end if
next

flef.WriteLn("</form>")
flef.WriteLn("</body>")
flef.WriteLn("</html>")

'=== we dont refresh this frame, its the first one

end function

'=== sub to call when something is pressed
'=== called for many buttons, return the button name or a keyboard code (Ascii)
sub buttonlef
   set src = flef.parentWindow.event.srcElement
   resbutlefstr = src.name
end sub

sub buttonmid
   set src = fmid.parentWindow.event.srcElement
   resbutmidstr = src.name
end sub

sub buttonbot
   set src = fbot.parentWindow.event.srcElement
   resbutbotstr = src.name
end sub

sub Checklef
   reskeylef = flef.parentWindow.event.keycode
end sub

sub Checkmid
   reskeymid = fmid.parentWindow.event.keycode
end sub

sub Checkbot
   reskeybot = fbot.parentWindow.event.keycode
end sub

'=== chek in the actual folder if a file exist
function filsea(filname)

'=== chek also actual folder for a "Rappel_LOG" file (instr)
Set objFolder2 = objFSO.GetFolder(basedir)'=== dir
Set objFiles2 = objFolder2.files '=== fichiers

found=0  '=== fichier de rapport pas trouve
For Each objFile3 in objFiles2
   nomfile =objfile3.name
   nomfile= lcase(nomfile)
 
next


end function

'=== delete a table in a database

function tabdel()
       
         for each tab in objcat.Tables
            If tab.Type = "TABLE" Then
               b=lcase(tab.name)
               '=== object.delete not supported, so we delete with name
               objcat.tables.delete b
               fbot.WriteLn("delete: " & b & "<br>")
            END IF
         next

end function

'=== for reference
function dynbotcho00
               i3=0
               For each dia01 in choiceara
                  sql = makque(dia01,tab,sel,whe,"","=","")
                  a = exesql(objcon,tag,sql)

                  '=== make same array for a multiples queries
                  if tag.eof=0 then
                     'a = dynbotcho("DIAGNOSTIC",tag,0,sql,1,1,1,1) '=== 1 2 3
                     if ubound(choiceara)=0 and i3=0 then
                        a = dynbotcho("DIAGNOSTIC",tag,0,sql,1,1,1,1) '=== 1 2 3
                     elseif i3=0 then
                        '=== header
                        a = dynbotcho("DIAGNOSTIC",tag,0,sql,1,1,0,0) '=== 1 2 3
                     elseif i3<>ubound(choiceara) and i3<>0 then
                        '=== footer
                        a = dynbotcho("DIAGNOSTIC",tag,0,sql,0,1,0,0) '=== 1 2 3
                     elseif i3=ubound(choiceara) then
                        a = dynbotcho("DIAGNOSTIC",tag,0,sql,0,1,1,1) '=== 1 2 3
                     end if
                     i3 = i3 + 1
                  else
                     '=== 0 results
                     a = nores(sql)
                  end if
               next
end function

function dynbotcho(ffra, ttext, aaratit, aara, cc01 ,hh, mm, ff, rr, ttxtbox,ffranam)
   '=== ffra frame to use for display (object)
   '=== ttext to display
   '=== aara = array with what to display
   '=== cc01 = choice button (no choice button when we display disgnostics, cause of multiple tables in one)
   '=== sql = sql query for debugging
   '=== hh = 1 = header
   '=== mm = 1 = middle
   '=== bb = 1 = footer
   '=== rr = 1 = reload at end
   '=== ttxtbox = all data are in a textbox so we can edit them (1) no date in text box (0)
   '=== ffranam = frame name
 
   htmtab = ""
   if ffranam = "lef" then
      for each a in lefara
         htmtab = htmtab & a
      next
   end if
   if ffranam = "mid" then
      for each a in midara
         htmtab = htmtab & a
      next
   end if
   if ffranam = "bot" then
      for each a in botara
         htmtab = htmtab & a
      next
   end if

   if logall = 1 then fil02.writeline "--- the sub dynbotcho has been called"
 
   call oieready
   '=== print button
   priara = array("<input type=""button"" onClick=""javascript:print()"" value=""Print""/>")
 
   xmax = UBound(aara, 1) 'Returns the Number of columns  --- elements in first dimension
   'on error resume next
   on error resume next
   '=== chek the number of elements in second dimension, if there is none, then the array is only a list with 1 column
   ymax = UBound(aara, 2) 'Returns the Number of rows     --- elements in second dimension
 
   '=== number of dimensions in case there is only 1 column
   if err<>0 then
      dimnum=1
      if logall=1 then
         fil02.WriteLine date & " " & time & " max column: " & xmax
      end if
   else
      dimnum=2
      if logall=1 then
         'fil02.WriteLine date & " " & time & " max column: " & xmax
         fil02.WriteLine date & " " & time & " max row   : " & ymax
         'fil02.WriteLine date & " " & time & " offset    : " & maxoff
         'fil02.WriteLine date & " " & time & " offsetnow : " & offset
      end if
   end if
   on error goto 0
 
   if dimnum=2 then
      if totrec>=maxoff then ymax=maxoff+offset-1
      if ymax>totrec then ymax=totrec
      'if ymax>maxoff then ymax=maxoff
   end if
   '=== web script for buttons to return the number of the button that was pressed
   htmtab = htmtab & "<form name=form01>"
   '=== print button
   if hh=1 then
      for each a in priara
         htmtab = htmtab & a
         'if logall=1 then fil02.writeline "*-------============*"
         'ffra.WriteLn("<BODY onLoad=""document.form01." & namtmp(0) & ".focus()"">")
      next
      if cc01=0 then htmtab = htmtab & "<br><br>"
   end if

   '=== search button only if bottom frame
   if ffranam="bot" and cc01<>0 then
      strsearch=""
      'fmid.WriteLn("    <input type=""" & typtmp(ii) & """           id=" & namtmp(ii)NAME=""" & namtmp(ii) & """ size=""" & max(20,len(deftmp(ii))) & """ value=""" & deftmp(ii) & """ onKeypress=""return event.keyCode!=13""")
      if secseatag=1 then
         htmtab = htmtab & "<input type=""textbox"" style=""width:15%;"" id=""boxsearch"" NAME=""boxsearch"" size=""20"" value=""" & strsearch & """ onKeypress=""return event.keyCode!=13"">"
         htmtab = htmtab & "<input type=""button"" name=""Search"" value=""Search"">"
      end if
   end if

   if totrec>=maxoff and cc01<>0 then
'htmtab = htmtab & "<input type=""button"" name=""" & "but" & trim(cstr(yy+1)) & """ value=""" & "Select " & yy+1 & """"
'htmtab = htmtab &  " style=""background-color: #" & "cccccc" & "; color: #000000;""><br>"
      htmtab = htmtab & "<input type=""button"" name=""Precedent"" value=""Precedent"">"
      htmtab = htmtab & "<input type=""button"" name=""Next"" value=""Next"">"
      'ffra.WriteLn(" style=""background-color: #" & "cccccc" & "; color: #000000;"">")
   end if
   if ffranam="bot" and cc01<>0 then
      htmtab = htmtab & "Displaying " & offset + 1 & " to " & ymax + 1 & " / " & totrec + 1 & " Records"
      htmtab = htmtab & "<br><br>"
   end if

   '=== select buttons
   if cc01<>0 then
      '=== buttons var only if select is active
      if cc01<>0 then
         for yy=0 to ymax
         
         next
      end if
   end if
 
   fast=0
   '=== header
   if hh=1 then
      if logall = 1 then fil02.writeline "--- header frame"
   
      htmtab = htmtab & ttext & "<b><table width=""100%"" BORDERCOLOR=""black"" class=MsoTableGrid border=1 CELLSPACING=0 cellpadding=2 style='border-collapse:collapse;border:none'>"
      htmtab = htmtab & "<CAPTION></CAPTION><span style='color:purple'>" & vbcrlf
   
      if fast=1 then ffra.WriteLn(htmtab):htmtab=""
      '=== tableau html
      htmtab = htmtab & "<TR>"
      if fast=1 then ffra.WriteLn(htmtab):htmtab=""
      i=0
      For Each a In aaratit
         '=== columns names
         if cc01<>0 then if i=0 then htmtab = htmtab & "<td><p>Select</td>"
         '=== test to insert text box inside each field with a default value for editing
         test=0
         if test=0 then
            htmtab = htmtab & "<td><p>" & Trim(a) & "</td>"
            if fast=1 then ffra.WriteLn(htmtab):htmtab=""
         else
            '=== futur button to order by that column
            '=== futur textbox to search in this column
            htmtab = htmtab & "<td><p>" & Trim(a) & "</td>"
            if fast=1 then ffra.WriteLn(htmtab):htmtab=""
         end if
         i=i+1
         if dimnum=1 then exit for
      Next
         htmtab = htmtab & "</tr>"
         if fast=1 then ffra.WriteLn(htmtab):htmtab=""
   end if

   '=== middle
   if mm=1 then
      if logall = 1 then fil02.writeline "--- middle frame"
      '=== x is inversed when only one column
      if dimnum=1 then
         ymax=xmax
         '=== no offset possible here
         ymin=0
      else
         '=== there is 2 dimensions, that mean multiple row
         '=== so we must assume there is an offset
         ymin=offset
      end if
   
      For yy = ymin To ymax
         htmtab = htmtab & "<TR>"
         if dimnum=2 then
            'ffra.WriteLn(yy)
         
            '=== multiple row
            For xx = 0 To xmax
               'If IsNull(myarray(xx, yy)) Then myarray(xx, yy) = ""
               if xx=0 and cc01<>0 then
                  htmtab = htmtab & "<td><p>"
                  htmtab = htmtab & "<input type=""button"" name=""" & "but" & trim(cstr(yy+1)) & """ value=""" & "Select " & yy+1 & """"
                  htmtab = htmtab &  " style=""background-color: #" & "cccccc" & "; color: #000000;""><br>"
                  htmtab = htmtab & "</td>"
                  if fast=1 then ffra.WriteLn(htmtab):htmtab=""
               end if
             
            if ttxtbox=0 then
               htmtab = htmtab & "<td><p>" & aara(xx, yy) & "</td>"
               if fast=1 then ffra.WriteLn(htmtab):htmtab=""
            else
               'aa="<input type=""textbox"" style=""width:100%;"" id=""box" & xx & "_" & yy & """ NAME=""box" & xx & "_" & yy & """ size=""" & max(1,len(aara(xx, yy))) & """ value=""" & aara(xx, yy) & """ onKeypress=""return event.keyCode!=13"""
               ffra.WriteLn("<td><p><input type=""textbox"" style=""width:100%;"" id=""box" & xx & "_" & yy & """ NAME=""box" & xx & "_" & yy & """ size=""" & max(1,len(aara(xx, yy))) & """ value=""" & aara(xx, yy) & """ onKeypress=""return event.keyCode!=13""></td>")
               'htmtab = htmtab & "<td><p>" & aara(yy, xx) & "</td>"
               'if fast=1 then ffra.WriteLn(htmtab):htmtab=""
            end if
            Next
         else
         
            '=== there is only 1 row
            htmtab = htmtab & "<td><p>"
            htmtab = htmtab & "<input type=""button"" name=""" & "but" & trim(cstr(yy+1)) & """ value=""" & "Select " & yy+1 & """"
            htmtab = htmtab &  " style=""background-color: #" & "cccccc" & "; color: #000000;""><br>"
            htmtab = htmtab & "</td>"
         
            if ttxtbox=0 then
               htmtab = htmtab & "<td><p>" & aara(yy) & "</td>"
            else
               aa="<input type=""textbox"" style=""width:100%;"" id=""box" & yy & """ NAME=""box" & yy & """ size=""" & max(1,len(aara(yy))) & """ value=""" & aara(yy) & """ onKeypress=""return event.keyCode!=13"""
               htmtab = htmtab & "<td><p>" & aa & "</td>"
               'htmtab = htmtab & "<td><p>" & aara(yy, xx) & "</td>"
            end if
         
         end if
         htmtab = htmtab & "</tr>" & vbcrlf
         if fast=1 then ffra.WriteLn(htmtab):htmtab=""
 
      Next
   end if
   
   '=== footer
   if ff=1 then
      if logall = 1 then fil02.writeline "--- footer frame"
      htmtab = htmtab & "</table></span></b><br>"
      if logall=1 then fil02.writeline "--- writing data into frame"
      if fast=1 then ffra.WriteLn(htmtab):htmtab=""
   end if
 
   htmtab = htmtab & "</form>"
   if fast=1 then ffra.WriteLn(htmtab):htmtab=""
 
   aa = lcase(ffra.readystate)
   do until aa="complete" or aa="terminé" or aa="interactive"
      if logall = 1 then fil02.writeline "*********************************** readystate of " & ffranam & ": " & aa
      wscript.sleep 100
      aa = lcase(ffra.readystate)
   loop
   if fast=0 then ffra.WriteLn(htmtab)
   
   '=== reload (will not reload if we are in middle of a muliple elements/query table)
   if rr=1 then
      if logall=1 then
         'fil02.writeline htmtab
         fil02.writeline "--- reloading FRAME"
      end if
      'oie.document.getElementById("bottom").innerhtml htmtab
      'oie.document.getElementById("bottom").src
      'iframe.location.reload(true)
   
      aa = lcase(ffra.readystate)
      do until aa="complete" or aa="terminé" or aa="interactive"
         if logall = 1 then fil02.writeline "*********************************** readystate of " & ffranam & ": " & aa
         wscript.sleep 100
         aa = lcase(ffra.readystate)
      loop    
   
      ffra.location.reload(false)

   end if
 
   '=== ?
   if mm=1 and cc01<>0 then
      For yy = ymin To ymax
         if dimnum=2 then
            ffra.forms(0).elements("but" & trim(cstr(yy+1))).onclick = getref("button" & ffranam)
         else
         '=== there is only 1 column
            ffra.forms(0).elements("but" & trim(cstr(yy+1))).onclick = getref("button" & ffranam)
         end if
      Next
   end if
   if logall=1 then
      fil02.WriteLine date & " " & time & " max column: " & totrec
   end if
   if totrec>=maxoff and cc01<>0 then
      ffra.forms(0).elements("Precedent").onclick = getref("button" & ffranam)
      ffra.forms(0).elements("Next").onclick = getref("button" & ffranam)
   end if
   if ffranam="bot" and cc01<>0 then
      if secseatag<>0 then
         ffra.forms(0).elements("Search").onclick = getref("button" & ffranam)
      end if
   end if
   set ffra.onkeypress = GetRef("Check" & ffranam)
 
   'for i=0 to ubound(arabutnam)
   '   flef.forms(0).elements(arabutnam(i)).onclick = getref("buttonlef")
   'next
end function

sub oieready()
   do while oie.readystate<>4
      wscript.sleep 100
   loop
 
   'if logall=1 then fil02.writeline "============== oie readystate: " & oie.readystate
   'Do
   '   wscript.sleep 100
   'loop until oie.ReadyState = "Terminé" or oie.ReadyState = "Complete"
 
   Do While (oIE.Busy)
      wscript.sleep 100
   Loop
end sub


'=== ssea = search string

'=== tab 0 symptoms
'=== tab 1 components
'=== tab 2 diagnostics
'=== tab 3 causes

'=== ttyp 0 search
'=== ttyp 1 fast results
'=== ttyp 2 detail results

'=== ssufix = ordere by or something at the end of query
'                                            order  and   %
function makque(ssea, ttab, sselect,wwhere, ssufix,ooper,wwild)
   ssea = replace(ssea,"'","''")
   ssea = trim(ssea)
   sseaara = split(ssea," ") '=== array of all words for search
 
   ss = "select "
 
   ii = 0
   '=== columns to search in
   for each aa in allara(ttab,sselect)
      ss = ss & aa
      if ii<>ubound(allara(ttab,1),sselect) then ss = ss & ","
      ii=ii+1
   next
 
   '=== from table
   ss = ss & " from [" & alltab(ttab) & "] "
   if len(ssea)<>0 then
      ss = ss & "where ("
 
      '=== search word(S) in table, AND operator
      ii = 0
      for each ss2 in sseaara
         ii2=0
         for each aa in allara(ttab,wwhere)
            if wwild="" then
               ss = ss & "[" & aa & "] " & ooper & " " & wwild & ss2 & wwild
            else
               ss = ss & "[" & aa & "] " & ooper & " '" & wwild & ss2 & wwild & "'"
            end if
            if ii2 <> UBound(allara(ttab,wwhere), 1) then ss = ss & " or "
            ii2=ii2+1
         next
         if ii <> UBound(sseaara, 1) then ss = ss & ") and ("
         ii=ii+1
      next
      '=== order by a column name
      ss = ss & ")" & ssufix
   else
      ss = ss & ssufix
   end if
   makque = ss

end function

function exesql(objcon,tag,sql)
   
   on error resume next
   set tag = objcon.execute(SQL)
   if err<>0 then
      aaa= err.description
      on error goto 0
      l1 = "error in query"
      l2 = "query: " & sql
      l3 = "error: " & aaa
      l4 = "the program will now end"
      fbot.WriteLn(l1 & "<BR><br>" & l2 & "<BR><br>" & l3 & "<BR><br>" & l4 & "<BR><br>")
      'msgbox(l1 & vbcrlf & l2 & vbcrlf & l3 & vbcrlf & l4 & vbcrlf)
      if logall=1 then
          fil02.writeline "query:"
          fil02.writeline sql
          fil02.writeline err.description
       
      end if
      wscript.quit
   end if
   
end function

'=== tab = table object (adox)
'=== colnam = string containing column name

function crecol(tab,colnam)

                  Set objcol = CreateObject("ADOX.Column")
         
                  'typdat=202   '=== string adVarWChar
                  'maxlen=250
                  'typdat=131   '=== float adnumeric
                  'maxlen=10
                  typdat=3     '=== integer adinteger
                  maxlen=10
           
                  if typdat=3 then a="adinteger"
                  if typdat=202 then a="adVarWChar"
                  if typdat=131 then a="adnumeric"
             
                  objcol.name = colnam
                  objcol.type = typdat
                  if typdat = 3 or typdat = 202 then
                     objcol.DefinedSize = maxlen
                     if typdat=3 then
                        '=== must set parent catalog before setting autoincrement
                        Set objcol.ParentCatalog = objcat
                        objcol.Properties("AutoIncrement")=true
                     end if
                  elseif typdat = 131 then
                     objcol.precision = 28
                     objcol.numericscale = 8
                  end if
                  fbot.WriteLn("column creation: " & colnam & "<br>")
                  Tab.Columns.Append objcol

end function

'=== count the number of record in the array
function cnttotrec(aara)
 
   xmax = UBound(aara, 1) 'Returns the Number of columns  --- elements in first dimension
   on error resume next
   '=== chek the number of elements in second dimension, if there is none, then the array is only a list with 1 column
   ymax = UBound(aara, 2) 'Returns the Number of rows     --- elements in second dimension
 
   '=== number of dimensions in case there is only 1 column
   if err<>0 then
      aa = xmax
   else
      aa = ymax
   end if

   on error goto 0
 
   cnttotrec = aa

end function

function dynmidres(TTEXT,aara,rres,aaratit,ccoltot)
 
   call oieready
   htmtab=""
   htmtab = htmtab & "<HTML><BODY>"
   for each a in midara
      htmtab = htmtab & a
   next
 
         htmtab = htmtab & TTEXT & ": " & rres & "<b><table  width=""100%"" BORDERCOLOR=""black"" class=MsoTableGrid border=1 CELLSPACING=0 cellpadding=2 style='border-collapse:collapse;border:none'>"
         htmtab = htmtab & "<CAPTION></CAPTION><span style='color:purple'>"
         htmtab = htmtab & "<TR>"
 
         i=0
         For Each aa In aaratit
            '=== columns names
            if i=0 then htmtab = htmtab & "<td><p>Choice</td>"
            htmtab = htmtab & "<td><p>" & Trim(aa) & "</td>"
            i=i+1
         Next
       
         htmtab = htmtab & "</tr>"
       
         For xx = 0 To ccoltot
            'If IsNull(myarray(xx, yy)) Then myarray(xx, yy) = ""
            if xx=0 then
               htmtab = htmtab & "<td><p>"
               htmtab = htmtab & rres
               htmtab = htmtab & "</td>"
            end if
         
            htmtab = htmtab & "<td><p>" & aara(xx,rres-1) & "</td>"
            'col = col & myarray(xx, yy)
         Next
         htmtab = htmtab & "</tr>"
         htmtab = htmtab & "</table></span></b><br>"
       
         '=== image of the component
         aa = """file://" & basedir & "PhotoHydComponent\002-00_HydroCraft_HC-EC_EndCover.jpg"""
         aa = replace(aa,"\","/")
         '<DIV style='display:none'><IMG SRC='image.gif'></DIV>
         htmtab = htmtab & "<img src=" & aa & " alt=" & aa & " />"
         htmtab = htmtab & "</BODY></HTML>"

         oie.document.getElementById("middle").contentWindow.document.body.innerhtml = htmtab
         'fmid.WriteLn(htmtab)

end function

FUNCTION SPLIT2(AA,SS)
             
   set bb= nothing
   BB = Split(AA, SS)
             
   set aa2=nothing
   AA2 = array("newsplittedarray")
   ii=0
   for each cc in bb
      if cc<>"" then
         redim PRESERVE aa2(ii)
         aa2(Ii)=cc
         ii=ii+1
      end if
   next

   split2 = aa2

END FUNCTION



function bigtablewait()
 
   strsearch=""
   offset=0
   do
      wscript.sleep 100
   
      '=== while we wait for input value (or button press), user can press "escape" key, "cancel" button or close internet explorer
      if resbutmidstr="cancel" or reskeymid=27 or bready=true or resbutlefstr<>"" then
         '=== if user pressed escape or cancel, we clear the frames
         if resbutmidstr="cancel" or reskeymid=27 then
            a = clefra(array("fmid","fbot"))
            resbutmidstr="cancel"
         end if
         exit do
      end if  
               
      if resbutbotstr="Precedent" then
         a=offset
         offset=offset-maxoff
         offset=max(0,offset)
         resbutbotstr=""
         if offset<>a then
            '=== totrec total number of record (displayed at end of first line)
            '=== maxoff maxiumm number of row in a page
            '=== offset page flip number (multiple of maxoff)
            a = dynbotcho(fbot, tabnam2, aratit, ara01, 1 ,1, 1, 1, 1, edtmod,"bot")
         end if
      end if            
   
      if resbutbotstr="Next" then
         a=offset
         offset=offset+maxoff
         if offset>totrec then offset=offset-maxoff
            resbutbotstr=""
            if offset<>a then
               a = dynbotcho(fbot, tabnam2, aratit, ara01, 1 ,1, 1, 1, 1, edtmod,"bot")
            end if
         end if
             
      if resbutbotstr="Search" or reskeybot=13 then
             
         strsearch=fbot.form01.boxsearch.Value
         strsearch=lcase(strsearch)
               
         '=== make a dynamic query to search for every words in every columns
         'makque(ssea, ttab, sselect,wwhere, ssufix,ooper,wwild)
         
         'if whe=3 then whe=0
         sql = makque(strsearch,tab,sel,whe,"",ooper,wwild)
         
         if logall=1 then
            fil02.WriteLine date & " " & time & " QUERY: "
            fil02.WriteLine sql
            'fil02.WriteLine date & " " & time & " Autoincrement status: " & objcol.Properties("AutoIncrement")
         end if
         a = exesql(objcon,tag,sql)
         
         if tag.eof=0 then
            myarray=TAG.GetRows()
         else
            redim myarray(coltot,0)
            'fbot.WriteLn("<br>total columns: " & coltot & "<br>")
            for i=0 to coltot
               myarray(i,0)="ERROR there was 0 record in this query"
            next
            fbot.WriteLn("<br>ERROR<br>" & sql & "<br><br>gave 0 results<br>")
         end if
               
         offset=0
         totrec = cnttotrec(myarray)
         if logall=1 then
            fil02.WriteLine date & " " & time & " total records: " & totrec+1
         end if
         a = dynbotcho(fbot, tabnam2, aratit, ara01, 1 ,1, 1, 1, 1, edtmod,"bot")
               
         resbutbotstr=""
      end if
      reskeybot=0
   
   loop while resbutbotstr=""
   offset=0
end function


function symptomssearch(strsea)

   mdbfil02 = basedir & "45834_crucible_cleaning_diagnostic.mdb"
   set objcon = nothing
   Set objcon = CreateObject("ADODB.Connection")
   constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mdbfil02
   objcon.open constr
 
   '=== symptom words to search (separated by a space)
   tab = 0 '=== table to seach in    (alltab)
   sel = 1 '=== columns to list      (allara)
   whe = 0 '=== columns to search in (Allara)

   'sql = "select top 1 * from " & alltab(tab)
   'a = exesql(objcon,tag,sql)
 
   sql = makque(strsea,tab,sel,whe," order by [probabilité] DESC","LIKE","%")
   if logall=1 then
      fil02.writeline "query:   " & sql
   end if
 
   a = exesql(objcon,tag,sql)

   '=== get all column names      
   coltot=0
   redim aratit(coltot)
   For Each a In TAG.fields
   '=== columns names
      redim preserve aratit(coltot)
      aratit(coltot)=Trim(a.Name)
      coltot=coltot+1
   Next
   coltot=coltot-1
 
   if tag.eof=0 then
      ara01 = tag.GetRows()
      if logall=1 then fil02.writeline "ara01 a été rempli de data"
   else
      redim ara01(coltot,0)
      fbot.WriteLn("<br>total columns: " & coltot & "<br>")
      for i=0 to coltot
         ara01(i,0)="ERROR there was 0 record in this query"
      next
      fbot.WriteLn("<br>ERROR<br>" & sql & "<br>gave 0 results<br>")    
   end if
 
   '=== get all data in a two dimensionnal array
 
   '=== ffra frame to use for display (object)
   '=== ttext to display
   '=== aara = array with what to display
   '=== cc = choice button
   '=== sql = sql query for debugging
   '=== hh = 1 = header
   '=== mm = 1 = middle
   '=== bb = 1 = footer
   '=== rr = 1 = reload at end
   '=== ttxtbox = all data are in a textbox so we can edit them
   actrec = 0
   offset = 0
   search=""
   '=== total of records (max y in array if there is a x only)
   totrec = cnttotrec(ara01)
 
   tabnam2="SYMPTOMS"
   a = dynbotcho(fbot, tabnam2, aratit, ara01, 1 ,1, 1, 1, 1, edtmod, "bot")
 
   ooper = "LIKE"
   wwild="%"
   whe2tag=0 '=== no search in a search here, cause we are already looking for words in all search columns
   whe2 = 1 '=== search in a search
   a = bigtablewait

   if bready=false and resbutlefstr="" and reskeymid<>27 and resbutmidstr<>"cancel" then
             
      '================= symptom done ========================================
     
      '=== convert the choice made with the button to a number (remove "but" from left side)
      ressym = right(resbutbotstr,len(resbutbotstr)-3)
      resbutmidstr=""
   
      '=== get the array that contain the choice in dbnam (database name)
      'fbot.WriteLn(ressym)

      a = clefra(array("fmid","fbot"))          '=== doing the job, all input are ok

      '=== look for our choice in the array in the right column, num1
      i = 0
      for each a in aratit
         b=lcase(a)
         if instr(b,"num1") then
            coldia = i
         end if
         i=i+1
      next
   
      ressym2 = ara01(coldia,ressym-1)
      if logall=1 then fil02.writeline "--- choice made.........: " & ressym2
   
      a = dynmidres("PROBLEM SELECTED",ara01,ressym,aratit,coltot)     '=== RESULTS SELECTED in ara01, ressym = result for symptom

      a = clrmenu
      'choice = trim(cstr(ara01(0,ressym)))
   
      '=== put 0 before result for component table search
      'IF len(chosym)<3 then chosym = string("0",len(3-len(chosym))) & chosym
   
      '========================== component choice
   
      '===
      tab = 1 '=== table to seach in    (alltab)
      sel = 1 '=== columns to list      (allara)
      whe = 3 '=== columns to search in (Allara) (3=symptoms, 4=diagnostics, 5=causes)
   
      sql = makque("-" & ressym2 & "-",tab,sel,whe,"","LIKE","%")
      'fbot.WriteLn(sql & "<br>")
      a = exesql(objcon,tag,sql)

      '=== get all column names      
      coltot=0
      redim aratit(coltot)
      For Each a In TAG.fields
      '=== columns names
         redim preserve aratit(coltot)
         aratit(coltot)=Trim(a.Name)
         coltot=coltot+1
      Next
      coltot=coltot-1
 
      if tag.eof=0 then
         ara01 = tag.GetRows()
         if logall=1 then fil02.writeline "ara01 a été rempli de data"
      else
         redim ara01(coltot,0)
         fbot.WriteLn("<br>total columns: " & coltot & "<br>")
         for i=0 to coltot
            ara01(i,0)="ERROR there was 0 record in this query"
         next
         fbot.WriteLn("<br>ERROR<br>" & sql & "<br>gave 0 results<br>")    
      end if
   
      '=== get all data in a two dimensionnal array
      totrec = cnttotrec(ara01)
   
      tabnam2="COMPONENTS"
      a = dynbotcho(fbot, tabnam2, aratit, ara01, 1 ,1, 1, 1, 1, edtmod,"bot")
   
      ooper = "LIKE"
      wwild = "%"
      'whe=0
      whe2tag=1
      whe2 = 1 '=== search in a search, we look for words, but in the result containing the number from the symptom
      a = bigtablewait

      if bready=false and resbutlefstr="" and reskeymid<>27 and resbutmidstr<>"cancel" then
       
         '================ component done

         '=== convert the choice made with the button to a number (remove "but" from left side)
         rescom = right(resbutbotstr,len(resbutbotstr)-3)
         resbutmidstr=""
   
         '=== get the array that contain the choice in dbnam (database name)
         'fbot.WriteLn(rescom)
       
         call oieready
         a = clefra(array("fmid","fbot"))          '=== doing the job, all input are ok
       
         a = dynmidres("COMPONENT SELECTED",ara01,rescom,aratit,coltot)     '=== RESULTS SELECTED in ara01, ressym = result for symptom

         a = clrmenu

          '=== (3=symptoms, 4=diagnostics, 5=causes)
             
         'alltab(0) = "symptoms"
         'alltab(1) = "components"
         'alltab(2) = "diagnostic"
         'alltab(3) = "causes"
       
         '=== the result is many numbers, for all diagnostics (diganostics column)
         i = 0
         for each a in aratit
            b=lcase(a)
            if instr(b,"diagnostic") then
               coldia = i
            end if
            i=i+1
         next
       
         if logall=1 then
            fil02.writeline "diagnostic column: " & coldia & "   NAME: " & aratit(coldia)
            fil02.writeline "diagnostic column: " & ara01(coldia,rescom-1)
         end if

         rescom2 = ara01(coldia,rescom-1)
       
         set choiceara= nothing
         choiceara = Split2(rescom2, "-")
         totrec2 = ubound(choiceara)
           
         tab = 2 '=== table to seach in    (alltab)
         sel = 1 '=== columns to list      (allara)
         whe = 3 '=== columns to search in (Allara) (tab,3 = "num1")

         i3=0
         ooper = "LIKE"
         wwild = "%"
         whe2tag=0
         'whe2 = 1 '=== search in a search
         For each dia01 in choiceara
            sql = makque(dia01,tab,sel,whe,"","=","")
            if logall=1 then
               fil02.writeline "query:"
               fil02.writeline sql
            end if
            a = exesql(objcon,tag,sql)
         
            coltot=0
         
            redim aratit(coltot)
            For Each a In TAG.fields
            '=== columns names
               redim preserve aratit(coltot)
               aratit(coltot)=Trim(a.Name)
               coltot=coltot+1
            Next
            coltot=coltot-1
         
            if tag.eof=0 then
               ara01 = tag.GetRows()
               if logall=1 then fil02.writeline "=== ara01 a été rempli de data"
            else
               if logall = 1 then fil02.writeline "no results in the first search for symptoms"
            end if
         
            totrec = cnttotrec(ara01)

            if logall=1 then
               fil02.writeline "numbers of results   : " & totrec2
               fil02.writeline "number of disgnostics: " & i3
            end if
         
            '=== make same array for a multiples queries
            if totrec2+1 > 0 then
               if totrec2=0 and i3=0 then
                  '=== there is only 1 result, with diagnostics
                  actrec = 0
                  offset = 0
                  search=""
                  if logall=1 then fil02.writeline "1 1 1 1"
                  'dynbotcho(ffra, ttext, aaratit, aara, selectbutton ,hh, mm,ff,   rr  , ttxtbox ,ffranam)
                  a = dynbotcho(fbot, "DIAGNOSTIC", aratit, ara01, 0 , 1, 1, 1, 1, edtmod  ,"bot")
               
                  'a = dynbotcho("DIAGNOSTIC",tag,0,sql,1,1,1,1) '=== 1 2 3
               elseif i3=0 then
                  '=== header
                  'a = dynbotcho("DIAGNOSTIC",tag,0,sql,1,1,0,0) '=== 1 2 3
                  actrec = 0
                  offset = 0
                  search=""
                  if logall=1 then fil02.writeline "1 1 0 0"
                  a = dynbotcho(fbot, "DIAGNOSTIC", aratit, ara01, 0 ,1, 1, 0, 0, edtmod,"bot")
               elseif i3<>totrec2 and i3<>0 then
                  '=== footer
                  'a = dynbotcho("DIAGNOSTIC",tag,0,sql,0,1,0,0) '=== 1 2 3
                  actrec = 0
                  offset = 0
                  search=""
                  if logall=1 then fil02.writeline                  "0  1  0  0"
                  a = dynbotcho(fbot, "DIAGNOSTIC", aratit, ara01, 0 ,0, 1, 0, 0, edtmod,"bot")
               elseif i3=totrec2 then
                  'a = dynbotcho("DIAGNOSTIC",tag,0,sql,0,1,1,1) '=== 1 2 3
                  actrec = 0
                  offset = 0
                  search=""
                  if logall=1 then fil02.writeline "0 1 1 1"
                  a = dynbotcho(fbot, "DIAGNOSTIC", aratit, ara01, 0 ,0, 1, 1, 1, edtmod,"bot")
               end if
               i3 = i3 + 1
               'if logall=1 then fil02.writeline "i3    : " & i3 & " / "& totrec2
               'if logall=1 then fil02.writeline "dia013: " & dia01
            end if
         next
         if logall=1 then fil02.writeline "i3    : " & i3 & " / "& totrec2
         'wscript.quit
             
      elseif resbutlef=0 and button="cancel" then '=== cancel was pressed
         'fbot.WriteLn("cancelled<br>")
         a = clrmenu
         a = clefra(array("fmid","fbot"))
      end if
   
      '====== cause
      objcon.Close

   elseif resbutlefstr="" and (resbutmidstr="cancel" or reskeymid=27) then
      '=== nothing was pressed on left, but cancel was used or escape
      a=clrmenu
      a = clefra(array("fmid","fbot"))
   'elseif resbutlefstr<>"" then
      '=== sometthing hapenned with the buton on the left side (menu/control)
   
   end if
 
end function

'============---------------===============--------------============

function causessearch(strsea)
   '===
   mdbfil02 = basedir & "45834_crucible_cleaning_diagnostic.mdb"
   set objcon = nothing
   Set objcon = CreateObject("ADODB.Connection")
   constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mdbfil02
   objcon.open constr
 
   '=== cause = words to search (separated by a space)
   tab = 3 '=== table to seach in    (alltab)
   sel = 1 '=== columns to list      (allara)
   whe = 0 '=== columns to search in (Allara)

   'sql = "select top 1 * from " & alltab(tab)
   'a = exesql(objcon,tag,sql)
 
   sql = makque(strsea,tab,sel,whe,"","LIKE","%")
   if logall=1 then
      fil02.writeline "query:   " & sql
   end if
 
   a = exesql(objcon,tag,sql)

   '=== get all column names      
   coltot=0
   redim aratit(coltot)
   For Each a In TAG.fields
   '=== columns names
      redim preserve aratit(coltot)
      aratit(coltot)=Trim(a.Name)
      coltot=coltot+1
   Next
   coltot=coltot-1
 
   if tag.eof=0 then
      ara01 = tag.GetRows()
      if logall=1 then fil02.writeline "ara01 a été rempli de data"
   else
      redim ara01(coltot,0)
      fbot.WriteLn("<br>total columns: " & coltot & "<br>")
      for i=0 to coltot
         ara01(i,0)="ERROR there was 0 record in this query"
      next
      fbot.WriteLn("<br>ERROR<br>" & sql & "<br>gave 0 results<br>")    
   end if
 
   '=== get all data in a two dimensionnal array
 
   '=== ffra frame to use for display (object)
   '=== ttext to display
   '=== aara = array with what to display
   '=== cc = choice button
   '=== sql = sql query for debugging
   '=== hh = 1 = header
   '=== mm = 1 = middle
   '=== bb = 1 = footer
   '=== rr = 1 = reload at end
   '=== ttxtbox = all data are in a textbox so we can edit them
   actrec = 0
   offset = 0
   search=""
   '=== total of records (max y in array if there is a x only)
   totrec = cnttotrec(ara01)
 
   tabnam2="CAUSE"
   a = dynbotcho(fbot, tabnam2, aratit, ara01, 1 ,1, 1, 1, 1, edtmod, "bot")
 
   ooper = "LIKE"
   wwild="%"
   whe2tag=0 '=== no search in a search here, cause we are already looking for words in all search columns
   whe2 = 1 '=== search in a search
   a = bigtablewait

   if bready=false and resbutlefstr="" and reskeymid<>27 and resbutmidstr<>"cancel" then
             
      '================= symptom done ========================================
     
      '=== convert the choice made with the button to a number (remove "but" from left side)
      ressym = right(resbutbotstr,len(resbutbotstr)-3)
      resbutmidstr=""
   
      '=== get the array that contain the choice in dbnam (database name)
      'fbot.WriteLn(ressym)

      a = clefra(array("fmid","fbot"))          '=== doing the job, all input are ok

      '=== look for our choice in the array in the right column, num1
      i = 0
      for each a in aratit
         b=lcase(a)
         if instr(b,"num1") then
            coldia = i
         end if
         i=i+1
      next
   
      ressym2 = ara01(coldia,ressym-1)
      if logall=1 then fil02.writeline "--- choice made.........: " & ressym2
   
      a = dynmidres("CAUSE SELECTED",ara01,ressym,aratit,coltot)     '=== RESULTS SELECTED in ara01, ressym = result for symptom

      a = clrmenu
      'choice = trim(cstr(ara01(0,ressym)))
   
      '=== put 0 before result for component table search
      'IF len(chosym)<3 then chosym = string("0",len(3-len(chosym))) & chosym
   
      '========================== component choice
   
      '===
      tab = 1 '=== table to seach in    (alltab)
      sel = 1 '=== columns to list      (allara)
      whe = 5 '=== columns to search in (Allara) (3=symptoms, 4=diagnostics, 5=causes)
   
      sql = makque("-" & ressym2 & "-",tab,sel,whe,"","LIKE","%")
      'fbot.WriteLn(sql & "<br>")
      a = exesql(objcon,tag,sql)

      '=== get all column names      
      coltot=0
      redim aratit(coltot)
      For Each a In TAG.fields
      '=== columns names
         redim preserve aratit(coltot)
         aratit(coltot)=Trim(a.Name)
         coltot=coltot+1
      Next
      coltot=coltot-1
 
      if tag.eof=0 then
         ara01 = tag.GetRows()
         if logall=1 then fil02.writeline "ara01 a été rempli de data"
      else
         redim ara01(coltot,0)
         fbot.WriteLn("<br>total columns: " & coltot & "<br>")
         for i=0 to coltot
            ara01(i,0)="ERROR there was 0 record in this query"
         next
         fbot.WriteLn("<br>ERROR<br>" & sql & "<br>gave 0 results<br>")    
      end if
   
      '=== get all data in a two dimensionnal array
      totrec = cnttotrec(ara01)
   
      tabnam2="COMPONENTS"
      a = dynbotcho(fbot, tabnam2, aratit, ara01, 1 ,1, 1, 1, 1, edtmod,"bot")
   
      ooper = "LIKE"
      wwild = "%"
      'whe=0
      whe2tag=1
      whe2 = 1 '=== search in a search, we look for words, but in the result containing the number from the symptom
      a = bigtablewait

      if bready=false and resbutlefstr="" and reskeymid<>27 and resbutmidstr<>"cancel" then
       
         '================ component done

         '=== convert the choice made with the button to a number (remove "but" from left side)
         rescom = right(resbutbotstr,len(resbutbotstr)-3)
         resbutmidstr=""
   
         '=== get the array that contain the choice in dbnam (database name)
         'fbot.WriteLn(rescom)
       
         call oieready
         a = clefra(array("fmid","fbot"))          '=== doing the job, all input are ok
       
         a = dynmidres("COMPONENT SELECTED",ara01,rescom,aratit,coltot)     '=== RESULTS SELECTED in ara01, ressym = result for symptom

         a = clrmenu

          '=== (3=symptoms, 4=diagnostics, 5=causes)
             
         'alltab(0) = "symptoms"
         'alltab(1) = "components"
         'alltab(2) = "diagnostic"
         'alltab(3) = "causes"
       
         '=== the result is many numbers, for all diagnostics (diganostics column)
         i = 0
         for each a in aratit
            b=lcase(a)
            if instr(b,"diagnostic") then
               coldia = i
            end if
            i=i+1
         next
       
         if logall=1 then
            fil02.writeline "diagnostic column: " & coldia & "   NAME: " & aratit(coldia)
            fil02.writeline "diagnostic column: " & ara01(coldia,rescom-1)
         end if

         rescom2 = ara01(coldia,rescom-1)
       
         set choiceara= nothing
         choiceara = Split2(rescom2, "-")
         totrec2 = ubound(choiceara)
           
         tab = 2 '=== table to seach in    (alltab)
         sel = 1 '=== columns to list      (allara)
         whe = 3 '=== columns to search in (Allara) (tab,3 = "num1")

         i3=0
         ooper = "LIKE"
         wwild = "%"
         whe2tag=0
         'whe2 = 1 '=== search in a search
         For each dia01 in choiceara
            sql = makque(dia01,tab,sel,whe,"","=","")
            if logall=1 then
               fil02.writeline "query:"
               fil02.writeline sql
            end if
            a = exesql(objcon,tag,sql)
         
            coltot=0
         
            redim aratit(coltot)
            For Each a In TAG.fields
            '=== columns names
               redim preserve aratit(coltot)
               aratit(coltot)=Trim(a.Name)
               coltot=coltot+1
            Next
            coltot=coltot-1
         
            if tag.eof=0 then
               ara01 = tag.GetRows()
               if logall=1 then fil02.writeline "=== ara01 a été rempli de data"
            else
               if logall = 1 then fil02.writeline "no results in the first search for symptoms"
            end if
         
            totrec = cnttotrec(ara01)

            if logall=1 then
               fil02.writeline "numbers of results   : " & totrec2
               fil02.writeline "number of disgnostics: " & i3
            end if
         
            '=== make same array for a multiples queries
            if totrec2+1 > 0 then
               if totrec2=0 and i3=0 then
                  '=== there is only 1 result, with diagnostics
                  actrec = 0
                  offset = 0
                  search=""
                  if logall=1 then fil02.writeline "1 1 1 1"
                  'dynbotcho(ffra, ttext, aaratit, aara, selectbutton ,hh, mm,ff,   rr  , ttxtbox ,ffranam)
                  a = dynbotcho(fbot, "DIAGNOSTIC", aratit, ara01, 0 , 1, 1, 1, 1, edtmod  ,"bot")
               
                  'a = dynbotcho("DIAGNOSTIC",tag,0,sql,1,1,1,1) '=== 1 2 3
               elseif i3=0 then
                  '=== header
                  'a = dynbotcho("DIAGNOSTIC",tag,0,sql,1,1,0,0) '=== 1 2 3
                  actrec = 0
                  offset = 0
                  search=""
                  if logall=1 then fil02.writeline "1 1 0 0"
                  a = dynbotcho(fbot, "DIAGNOSTIC", aratit, ara01, 0 ,1, 1, 0, 0, edtmod,"bot")
               elseif i3<>totrec2 and i3<>0 then
                  '=== footer
                  'a = dynbotcho("DIAGNOSTIC",tag,0,sql,0,1,0,0) '=== 1 2 3
                  actrec = 0
                  offset = 0
                  search=""
                  if logall=1 then fil02.writeline                  "0  1  0  0"
                  a = dynbotcho(fbot, "DIAGNOSTIC", aratit, ara01, 0 ,0, 1, 0, 0, edtmod,"bot")
               elseif i3=totrec2 then
                  'a = dynbotcho("DIAGNOSTIC",tag,0,sql,0,1,1,1) '=== 1 2 3
                  actrec = 0
                  offset = 0
                  search=""
                  if logall=1 then fil02.writeline "0 1 1 1"
                  a = dynbotcho(fbot, "DIAGNOSTIC", aratit, ara01, 0 ,0, 1, 1, 1, edtmod,"bot")
               end if
               i3 = i3 + 1
               'if logall=1 then fil02.writeline "i3    : " & i3 & " / "& totrec2
               'if logall=1 then fil02.writeline "dia013: " & dia01
            end if
         next
         if logall=1 then fil02.writeline "i3    : " & i3 & " / "& totrec2
         'wscript.quit
             
      elseif resbutlef=0 and button="cancel" then '=== cancel was pressed
         'fbot.WriteLn("cancelled<br>")
         a = clrmenu
         a = clefra(array("fmid","fbot"))
      end if
   
      '====== cause
      objcon.Close

   elseif resbutlefstr="" and (resbutmidstr="cancel" or reskeymid=27) then
      '=== nothing was pressed on left, but cancel was used or escape
      a=clrmenu
      a = clefra(array("fmid","fbot"))
   'elseif resbutlefstr<>"" then
      '=== sometthing hapenned with the buton on the left side (menu/control)
   
   end if
 

end function

function componentssearch(strsea)

   mdbfil02 = basedir & "45834_crucible_cleaning_diagnostic.mdb"
   set objcon = nothing
   Set objcon = CreateObject("ADODB.Connection")
   constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & mdbfil02
   objcon.open constr
 
   '=== COMPONENT = words to search (separated by a space)
   tab = 1 '=== table to seach in    (alltab)
   sel = 1 '=== columns to list      (allara)
   whe = 0 '=== columns to search in (Allara)
 
   'sql = "select top 1 * from " & alltab(tab)
   'a = exesql(objcon,tag,sql)
 
   sql = makque(strsea,tab,sel,whe,"","LIKE","%")
   if logall=1 then
      fil02.writeline "query:   " & sql
   end if
 
   a = exesql(objcon,tag,sql)

   '=== get all column names      
   coltot=0
   redim aratit(coltot)
   For Each a In TAG.fields
   '=== columns names
      redim preserve aratit(coltot)
      aratit(coltot)=Trim(a.Name)
      coltot=coltot+1
   Next
   coltot=coltot-1
 
   if tag.eof=0 then
      ara01 = tag.GetRows()
      if logall=1 then fil02.writeline "ara01 a été rempli de data"
   else
      redim ara01(coltot,0)
      fbot.WriteLn("<br>total columns: " & coltot & "<br>")
      for i=0 to coltot
         ara01(i,0)="ERROR there was 0 record in this query"
      next
      fbot.WriteLn("<br>ERROR<br>" & sql & "<br>gave 0 results<br>")    
   end if
 
   '=== get all data in a two dimensionnal array
 
   '=== ffra frame to use for display (object)
   '=== ttext to display
   '=== aara = array with what to display
   '=== cc = choice button
   '=== sql = sql query for debugging
   '=== hh = 1 = header
   '=== mm = 1 = middle
   '=== bb = 1 = footer
   '=== rr = 1 = reload at end
   '=== ttxtbox = all data are in a textbox so we can edit them
   actrec = 0
   offset = 0
   search=""
   '=== total of records (max y in array if there is a x only)
   totrec = cnttotrec(ara01)
 
   tabnam2="COMPONENT"
   a = dynbotcho(fbot, tabnam2, aratit, ara01, 1 ,1, 1, 1, 1, edtmod, "bot")
 
   ooper = "LIKE"
   wwild="%"
   whe2tag=0 '=== no search in a search here, cause we are already looking for words in all search columns
   whe2 = 1 '=== search in a search
   a = bigtablewait

      if bready=false and resbutlefstr="" and reskeymid<>27 and resbutmidstr<>"cancel" then
       
         '================ component done

         '=== convert the choice made with the button to a number (remove "but" from left side)
         rescom = right(resbutbotstr,len(resbutbotstr)-3)
         resbutmidstr=""
   
         '=== get the array that contain the choice in dbnam (database name)
         'fbot.WriteLn(rescom)
       
         call oieready
         a = clefra(array("fmid","fbot"))          '=== doing the job, all input are ok
       
         a = dynmidres("COMPONENT SELECTED",ara01,rescom,aratit,coltot)     '=== RESULTS SELECTED in ara01, ressym = result for symptom

         a = clrmenu

          '=== (3=symptoms, 4=diagnostics, 5=causes)
             
         'alltab(0) = "symptoms"
         'alltab(1) = "components"
         'alltab(2) = "diagnostic"
         'alltab(3) = "causes"
       
         '=== the result is many numbers, for all diagnostics (diganostics column)
         i = 0
         for each a in aratit
            b=lcase(a)
            if instr(b,"diagnostic") then
               coldia = i
            end if
            i=i+1
         next
       
         if logall=1 then
            fil02.writeline "diagnostic column: " & coldia & "   NAME: " & aratit(coldia)
            fil02.writeline "diagnostic column: " & ara01(coldia,rescom-1)
         end if

         rescom2 = ara01(coldia,rescom-1)
       
         set choiceara= nothing
         choiceara = Split2(rescom2, "-")
         totrec2 = ubound(choiceara)
           
         tab = 2 '=== table to seach in    (alltab)
         sel = 1 '=== columns to list      (allara)
         whe = 3 '=== columns to search in (Allara) (tab,3 = "num1")

         i3=0
         ooper = "LIKE"
         wwild = "%"
         whe2tag=0
         'whe2 = 1 '=== search in a search
         For each dia01 in choiceara
            sql = makque(dia01,tab,sel,whe,"","=","")
            if logall=1 then
               fil02.writeline "query:"
               fil02.writeline sql
            end if
            a = exesql(objcon,tag,sql)
         
            coltot=0
         
            redim aratit(coltot)
            For Each a In TAG.fields
            '=== columns names
               redim preserve aratit(coltot)
               aratit(coltot)=Trim(a.Name)
               coltot=coltot+1
            Next
            coltot=coltot-1
         
            if tag.eof=0 then
               ara01 = tag.GetRows()
               if logall=1 then fil02.writeline "=== ara01 a été rempli de data"
            else
               if logall = 1 then fil02.writeline "no results in the first search for symptoms"
            end if
         
            totrec = cnttotrec(ara01)

            if logall=1 then
               fil02.writeline "numbers of results   : " & totrec2
               fil02.writeline "number of disgnostics: " & i3
            end if
         
            '=== make same array for a multiples queries
            if totrec2+1 > 0 then
               if totrec2=0 and i3=0 then
                  '=== there is only 1 result, with diagnostics
                  actrec = 0
                  offset = 0
                  search=""
                  if logall=1 then fil02.writeline "1 1 1 1"
                  'dynbotcho(ffra, ttext, aaratit, aara, selectbutton ,hh, mm,ff,   rr  , ttxtbox ,ffranam)
                  a = dynbotcho(fbot, "DIAGNOSTIC", aratit, ara01, 0 , 1, 1, 1, 1, edtmod  ,"bot")
               
                  'a = dynbotcho("DIAGNOSTIC",tag,0,sql,1,1,1,1) '=== 1 2 3
               elseif i3=0 then
                  '=== header
                  'a = dynbotcho("DIAGNOSTIC",tag,0,sql,1,1,0,0) '=== 1 2 3
                  actrec = 0
                  offset = 0
                  search=""
                  if logall=1 then fil02.writeline "1 1 0 0"
                  a = dynbotcho(fbot, "DIAGNOSTIC", aratit, ara01, 0 ,1, 1, 0, 0, edtmod,"bot")
               elseif i3<>totrec2 and i3<>0 then
                  '=== footer
                  'a = dynbotcho("DIAGNOSTIC",tag,0,sql,0,1,0,0) '=== 1 2 3
                  actrec = 0
                  offset = 0
                  search=""
                  if logall=1 then fil02.writeline                  "0  1  0  0"
                  a = dynbotcho(fbot, "DIAGNOSTIC", aratit, ara01, 0 ,0, 1, 0, 0, edtmod,"bot")
               elseif i3=totrec2 then
                  'a = dynbotcho("DIAGNOSTIC",tag,0,sql,0,1,1,1) '=== 1 2 3
                  actrec = 0
                  offset = 0
                  search=""
                  if logall=1 then fil02.writeline "0 1 1 1"
                  a = dynbotcho(fbot, "DIAGNOSTIC", aratit, ara01, 0 ,0, 1, 1, 1, edtmod,"bot")
               end if
               i3 = i3 + 1
               'if logall=1 then fil02.writeline "i3    : " & i3 & " / "& totrec2
               'if logall=1 then fil02.writeline "dia013: " & dia01
            end if
         next
         if logall=1 then fil02.writeline "i3    : " & i3 & " / "& totrec2
         'wscript.quit
             
      elseif resbutlef=0 and button="cancel" then '=== cancel was pressed
         'fbot.WriteLn("cancelled<br>")
         a = clrmenu
         a = clefra(array("fmid","fbot"))
      end if
   
      '====== cause
      objcon.Close

end function

function fPingTest( strComputer )
dim objShell,objPing
dim strPingOut, flag
set objShell = CreateObject("Wscript.Shell")
set objPing = objShell.Exec("ping " & strComputer)
strPingOut = objPing.StdOut.ReadAll
if instr(LCase(strPingOut), "reply") or instr(LCase(strPingOut), "ponse de") then
flag = TRUE
else
flag = FALSE
end if
fPingTest = flag

end function

Function Ping(strHost)
Dim objPing, objRetStatus
'progressText strHost, "Pinging"

Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery("select * from Win32_PingStatus where address = '" & strHost & "' AND ResolveAddressNames = TRUE")

For Each objRetStatus in objPing
If IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode <> 0 then
Ping = False
Else
Ping = True
End if
Next
End Function



'====== write a value in registry, trap error
function regwri(regkey, value, type01)
   aa = lcase(type01)

   if aa = "reg_multi_sz" then
      '=== split keyname from keypath cause for a multi sz the technique is different
      regnam = right(regkey, len(regkey) - instrrev(regkey,"\"))
      regpat = left(regkey,len(regkey) - instr(regkey,"\")-3)
      if mid(regpat,1,19)="HKEY_LOCAL_MACHINE\" then
         regpat = mid(regpat,20,len(regpat))
      end if
   
      objReg.SetMultiStringValue hklm,regpat,regnam,value
      'msgbox("test done" & vbcrlf & hklm & vbcrlf & regpat & vbcrlf & regnam & vbcrlf)   elseif type01<>"" then
   elseif aa<>"" then
   
      if mid(regkey,1,19)="HKEY_LOCAL_MACHINE\" then
        regpat = right(regkey,len(regkey)-19)
      end if
   
      regpat = left(regpat, instrrev(regpat,"\"))
      'msgbox(regpat)
      regnam = right(regkey, len(regkey) - instrrev(regkey,"\"))
   
      'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\RegisteredOwner
   
      err01 = 0 : err02 = ""
      'on error resume next
      'objshe.RegWrite regkey,value,type01
   
      fbot.WriteLn("<br>Before regwrite: " & type01 & "<br>")
      fbot.WriteLn("Before regwrite: " & hklm & "<br>")
      fbot.WriteLn("Before regwrite: " & regpat & "<br>")
      fbot.WriteLn("Before regwrite: " & regnam & "<br>")
      fbot.WriteLn("Before regwrite: " & value & "<br><br>")
   
      Return01 = objReg.SetStringValue(hklm,regpat,regnam,value)
      'msgbox(return01)
      if return01 <>0 then
        msgbox("ERROR" & vbcrlf & return01 & vbcrlf & "regpat: " & regpat & vbcrlf & regnam & vbcrlf & value & vbcrlf & regkey)
      else
        'msgbox("ERROR" & vbcrlf & return01 & vbcrlf & "regpat: " & regpat & vbcrlf & regnam & vbcrlf & value & vbcrlf & regkey)
      end if
      'If (Return01 = 0) And (Err.Number = 0) Then
          'Wscript.Echo "HKEY_LOCAL_MACHINE\Software\MyKey" & " contains 'string value'"
   
      err01 = err
      err02 = err.description
      on error goto 0
   
      'on error goto 0
      if err01 <>0 then
        'msgbox("ERROR writing register base")
        'objFil01.WriteLine date & " " & time & " ERREUR regwri écriture dans le base de registre: " & regkey & " Value: " & value & " type: " & type01
        'objFil01.WriteLine date & " " & time & " " & err01 & " " & err02
      end if
   else
      objshe.RegWrite regkey,""
   end if
   if err.number<>0 then
      'msgfin = msgfin & "`n" & regkey & "`n"
      toterrcop = toterrcop + 1
      msgfin03 = msgfin03 & vbcrlf & "error - register base not written: " & vbcrlf & regkey & vbcrlf & err.description & vbcrlf
      if usenam = debugname then
         'msgbox("cannot write key" & vbcrlf & regkey & vbcrlf & value)
      end if
   end if
end function


'====== create a process
function doprocess(strcommand, param)
Const SW_NORMAL = 1
'strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

' Configure the Notepad process to show a window
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_

' 1 - Window is shown minimized
' 3 - Window is shown maximized
' 5 - Window is shown in normal view
' 12 - Window is hidden and not displayed to the user

objConfig.ShowWindow = 1
a=right(strcommand,11)
if a="cscript.exe" or a="wscript.exe" then
objConfig.ShowWindow = 12
end if

IF A ="outlook.exe" then
strQuery = "Select * from Win32_Process Where Name = 'Outlook.exe'"
Set colProcesses = objWMIService.ExecQuery(strQuery)
For Each objProcess In colProcesses
If lCase(objProcess.Name) = "outlook.exe" Then
outrun=1
Else
Outrun=0
End If
Next
end if
'Const LOW = 64
'Const BELOW_NORMAL = 16384
'Const NORMAL = 32
'Const ABOVE_NORMAL = 32768
'Const HIGH = 128

objConfig.PriorityClass = 16384
'=== Create Notepad process
Set objProcess = objWMIService.Get("Win32_Process")
if param<>"" then
   strcommand = strcommand & " " & param
end if
IF (A ="outlook.exe" and outrun=0) or a<>"outlook.exe" then

   '=== localhost start process

   'intReturn = objProcess.Create(strCommand, Null, objConfig, intProcessID)
end if

'============== remote start
'=== Connect to WMI
'set objWMIService = getobject("winmgmts://" & strComputer & "/root/cimv2")
'=== Obtain the Win32_Process class of object.
Set objProcess = objWMIService.Get("Win32_Process")
Set objProgram = objProcess.Methods_("Create").InParameters.SpawnInstance_
objProgram.CommandLine = strCommand

'msgbox("ordinateur: " & strcomputer)

'Execute the program now at the command line.

Set strShell = objWMIService.ExecMethod("Win32_Process", "Create", objProgram)  



end function

'====== adjust a process priority
function adjprocess()
   'Const LOW = 64
   'Const BELOW_NORMAL = 16384
   'Const NORMAL = 32
   'Const ABOVE_NORMAL = 32768
   'Const HIGH = 128
 
   Const ABOVE_NORMAL = 32768
   strComputer = "."
   Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
   Set colProcesses = objWMIService.ExecQuery("Select * from Win32_Process Where Name = 'nsrexecd.exe'")
   For Each objProcess in colProcesses
       objProcess.SetPriority(ABOVE_NORMAL)
   Next
end function


Sunday, April 17, 2016

crypto virus protection and backup (not replications)

Crypto virus is a ransomware.

The user is the one installing this "virus", thinking it is a mp3 or any other lies internet can find to make you install a program.

This program, wich is not a virus (virus propagate themselves, this is a program that you install on your computer) will encrypt all your files in 2048 bits encryption (nearly impossible to crack). This is a long process.

There is a bad habit done by network administrators these days. They will install a RAID on your server, telling you that your data cannot be lost because the raid will always have a backup copy on another disk.

A RAID does NOT do any backup. It does a replication of your data. If the crypto virus hit your network, the infected files will simply be replicated by your raid.

You have a dropbox or any cloud replication. Your data are safe... NOT! Again, encrypted files will simply be replicated on your dropbox or onedrive.

After a crypto virus infection you still can pay the ransom. You have a good chance to get your data back (i would say 50%). But you just paid a hacker a ransom to get your files back. What will this hacker do with the money? Retirement? Certainly not. He will try to encrypt your files again because you are a paying customer!

So please to all newbie network administrators: a replication is not a backup. A cloud replication is not a backup. A RAID replication or mirror is not a backup.

A backup is a DAILY copy of your data (by date) on a removable support that is removed after the backup. Ideally, it is a tape. Small business can use a blue ray burner. At least once every 3 months.

here is a program that will change windows program execution policie to prevent execution of false "mp3" files that are actually a .exe to install crypto virus:
https://www.foolishit.com/cryptoprevent-malware-prevention/

It is free

Good luck and please backup (copy on removable support) your data regulary. And keep more than one copy. And remove the support after the backup and get it home for safekeeping everyday (in case of fire)


DNS

What is a dns server?
It is used to resolve name in your network and resolve internet adresses

Many poeple make the bad configuration that follow:
In their local network card, in IPV4 config, in DNS configuration.
They put in the dns server 8.8.8.8 and 8.8.4.4 (google's dns servers)
If you do that, your own computer will not be able to communicate with your domain server fully.

Now something even worst.
In the IPV4 network card configuration, some poeple put in their DNS servers some external dns servers adresses. You cannot do that. That is not how a dns server work. The dns server will have forwarders to go outside your network, but it need to go inside first in the IPV4 config of it's own network card. In IPV4 dns list, it must point to itself.

Your DNS server, will allow all the computers on your local network to communicate only if you resolve himself before going outside. Your DNS server have the list of all the names on your network and their ip adresses. But if you ask him to search on an external dns server first, no computer will be found. Only web pages. Oh great, your internet will work... but your local network will not perform very good...

If you have two dns servers, In IPV4 config, They should point to each others first.

After that, your internet provider should be the one giving you the DNS path to follow. Geographically. Why not jump directly to the united states? Because if a road get broken, you must find another road to go to your destination. Now if you are in Canada and go directly to the us, and one road break. You will not be able to resolve names to your destination.

If you follow a geographical path (nearest DNS server first, aka, your internet's provider DNS) then you will see the signs "road broken, please take this alternate road".

STOP putting external DNS everywhere in a local network! Please! :)





Saturday, April 16, 2016

Dynamic signature for outlook in HTM, with LDAP data

Hello,

In your domain server (LDAP), there is information about every users
First name, Last name, cell phone number, job title etc.

This info can be used to generate a dynamic signature for outlook

This script will read LDAP information and generate a HTM file in the folder windows 7 and office use for signatures.

This was NOT tested in windows 7 sp1 with outlook 2013
(i just extracted some code from my main logon script, so i might have missed something)



'==================== dynamic-outlook-signature.vbs ====================

'=== network groups (pas le login) avec tous les CN, OU, DC
'=== object principaux
Set objshe    = WScript.CreateObject("WScript.Shell") '=== command line calls
Set objFSO    = wscript.CreateObject("Scripting.FileSystemObject") '=== file control, open, write etc)

Set objUser = CreateObject("ADSystemInfo") '=== user object from local computer
Set CurrentUser = GetObject("LDAP://" & objUser.UserName) '=== user object from domain server, ldap

useappdat = objShe.SpecialFolders.Item("appdata")     '=== application data folder
'''''''''''''''''''''''''''''''''''
' signature htm outlook
'''''''''''''''''''''''''''''''''''
'useappdat
filesign01 = useappdat & "\microsoft\signatures\signature dynamique.htm"
'=== open log file
Set objfilsign01 = objFso.OpenTextFile(filesign01, 2, true)
'=== html table with 4 columns
'=== column 1 = name
width01 = 150
'=== all ldap info http://ss64.com/vb/syntax-userinfo.html
uselna = lcase(currentuser.sn)         '=== last name
if len(uselna)>0 then
'=== uppercase first letter
uselna = replace(uselna,mid(uselna,1,1),chr(asc(mid(uselna,1,1))-32))
end if
usefna = lcase(currentuser.givenname)   '=== first name
if len(usefna)>0 then
usefna = replace(usefna,mid(usefna,1,1),chr(asc(mid(usefna,1,1))-32))
end if
titre01 = currentuser.title '=== job title: analyste programmeur technicien informatique
role01 = currentuser.company                        '=== directeur ou autre (pas la compagnie)
email01 = currentuser.mail
phone01 = currentuser.telephoneNumber
if usenam = "serge.fournier" then homephone01 = currentuser.homePhone
mobilephone01 = currentuser.otherMobile
'=== column 2 = a green vertical line
width02 = 10
'=== column 3 = the compagny logo
width03 = 100
'=== column 4 = confidential notice
width04 = 830
'=== table
widthtotal01 = width01 + width02 + width03 + width04

s = "<html>"
s = s & "<table border=0 width=" & widthtotal01 & ">"
s = s & "<tr>"
s = s & "<td width=" & width01 & ">"
s = s & "<font face=""arial"" size=1.5>"
s = s & "<center>" & vbcrlf

s = s & "<b>" & usefna & " " & uselna & "<br>" & titre01 & "<br></b>" & vbcrlf
if len(role01)>0 then s = s & role01 & "<br>"
if len(email01)>0 then s = s & email01 & "<br>" & vbcrlf
if len(phone01)>0 then s = s & phone01 & "<br>" & vbcrlf
if len(mobilephone01)>0 then s = s & mobilephone01 & "<br>" & vbcrlf
if len(homephone01)>0 then s = s & homephone01 & "<br>" & vbcrlf
s = s & "www.gemel.ca<br>" & vbcrlf
s = s & "</center>" & vbcrlf
s = s & "</font>" & vbcrlf
s = s & "</td>" & vbcrlf

'=== just a green line for separation (image)
s = s & "<td width=" & width02 & ">" & vbcrlf
s = s & "<img src=""http://gemel.ca/wp-content/uploads/2016/04/Capture.png"" alt=""Mountain View"" width=""3"" height=""100"">" & vbcrlf
s = s & "</td>" & vbcrlf
        '=== compagny logo from facebook
s = s & "<td width=" & width03 & ">" & vbcrlf
s = s & "<img src=""https://scontent-ord1-1.xx.fbcdn.net/hphotos-xlf1/v/t1.0-9/10502515_801846939859068_758613211923328072_n.jpg?oh=7971845e1caf024546f60f19bac58fe5&oe=5778AD92"" alt=""Mountain View"" width=""88"" height=""88"">" & vbcrlf
s = s & "</td>" & vbcrlf
s = s & "<td width=" & width04 & ">" & vbcrlf
s = s & "<font face=""arial"" size=1.1>" & vbcrlf
s = s & "<b><i>SOUS TOUTES RÉSERVES</i></b><br><b>Avis de confidentialité et de propriété intellectuelle</b> - La présente communication est confidentielle et transmise sous le sceau du secret professionnel. Si vous n’êtes pas le destinataire visé ou son mandataire chargé de lui transmettre cette communication, vous êtes par la présente avisé qu’il est expressément interdit d’en dévoiler la teneur, de la copier, de la distribuer ou de prendre quelque mesure fondée sur l’information qui y est contenue. Si vous avez reçu cette communication par erreur, veuillez nous en aviser immédiatement par téléphone ou par courriel et détruire ce courriel et toute pièce jointe. Le droit d'auteur sur le présent document électronique appartient à Gémel inc. et ses professionnels; ce document ne peut être transmis, téléchargé ou reproduit, sous aucune forme, imprimée ou électronique que ce soit, sans l'autorisation expresse écrite des titulaires du droit d'auteur." & vbcrlf
s = s & "</font>" & vbcrlf
s = s & "</td>" & vbcrlf
s = s & "</tr>" & vbcrlf
s = s & "</table>" & vbcrlf
s = s & "</html>" & vbcrlf

objfilsign01.WriteLine s
objfilsign01.close

Sunday, April 3, 2016

dynamic powershell web interface




########################## ps_web_interface.ps1 ##############################
# 2017-10-22
# corrected a bug thet prevented command line powershell to manipulate internet explorer buttons

# 2017-09-17
# for inner html to work, you need to install office 2013
# since office 2013 is not installed on a server, i will make it work without it (for frame clearing)

# 2017-02-11
# added id to buttons because in microsoft edge, name was not the same as id

# 2016-04-03
# added some innerhtml to clear frames properly

# 2016-04-02
# First draft of the powershell version of my web interface for network administrators

### manifest
# powershell web interface for a network administrator
# par: serge.fournier(a)hotmail.com
# 2016-03-28

### DEscription:
# A powershell script to use internet explorer as interface for more powershell scripts
# It start internet explorer, divide it in 3 frames (flef, fmid and fbot)
# In the left frame, there is control buttons
# In middle frame (up) you can input some data to be processed
# (it's just some textbox in html that return their results to powershell)
# In the bottom frame, you can display the processing or the results of your scripts

### requirements
# because this script is not signed
# (this will allow unsigned local powershell scripts to run)
#   windows 7
#     Set-ExecutionPolicy RemoteSigned #################################
#   windows 10
#     Set-ExecutionPolicy -scope CurrentUser RemoteSigned ##############
#   run it in powershell ISE interface
#

### powershell error in english
# Update-Help -UICulture en-US
# [Threading.Thread]::CurrentThread.CurrentUICulture = 'en-US'

# variables typed

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{ 
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process -WindowStyle hidden powershell -Verb runAs -ArgumentList $arguments
Break
}

add-type @"
public struct oieparamin01
    {
    public int height01;
    public int width01;
    public string[] arabutnam;
    }
"@

add-type @"
public struct oieparamout01
    {
    public object oie;
    public object flef;
    public object fmid;
    public object fbot;
    }
"@

add-type @"
public struct dynamicformparamout
    {
    public string[] arabutnam;
    public string[] araresults;
    }
"@

###########################################
#   wait for com object OIE to be ready
###########################################
function isoieready($oie)
    {
    $millisec = 50
    While (($oie.ReadyState -ne 4) -and ($oie.hwnd -ne $null)) { Start-Sleep -Milliseconds $millisec}
    While (($oie.busy) -and ($oie.hwnd -ne $null)) { Start-Sleep -Milliseconds $millisec}
    return $oie.hwnd
    }

##########################################
#   internet explorer
##########################################
function makenewOIE($oieparamin01)
    {
   
    $oieparamout01 = new-object oieparamout01;
   
    # start ie object
    $oie = new-object -com InternetExplorer.Application
    $oie.FullScreen = $False

    # wait for a time then fatal error if iexplore does not get created
    $timeout01 = 0
    #$ieStatus01 = Get-ProcessWithOwner iexplore

    $oIE.left=0 # window position
    $oIE.top = 0 # and other properties
    $oIE.height = $oieparamin01.height01
    $oIE.width = $oieparamin01.width01
    $oIE.menubar = 1 #=== no menu
    $oIE.toolbar = 1
    $oIE.statusbar = 1
    $oIE.RegisterAsDropTarget = $True
    $oie.Navigate("about:blank")
    $oie.document.title = "Powershell Web Interface"

    # calculate for ie to take all screen but a small lane of 10% up top
    # get screen resolution
    # work only in powershell ISE or as admin (presumably)
    [void] [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")           
    [void] [Reflection.Assembly]::LoadWithPartialName("System.Drawing")           
    $Screens = [system.windows.forms.screen]::AllScreens 

    $DeviceName = $Screens[0].DeviceName           
    $oiewid  = $Screens[0].Bounds.Width           
    $oiehei  = $Screens[0].Bounds.Height           
    $IsPrimary = $Screens[0].Primary           

    $sizwidpercent = 100
    $sizheipercent = 95
    $loswid = 100-$sizwidpercent
    $loshei = 100-$sizheipercent
    $newwid = $oiewid*$sizwidpercent*.01
    $newhei = $oiehei*$sizheipercent*.01
    # this stuff work in ISE console but not outside of it
    try {$oie.document.parentwindow.resizeto($newwid,$newhei)} catch {}
    $newx = $oiewid * $loswid * .01 /2
    $newy = $oiehei * ($loshei/2) * .01 /2
    try {$oie.document.parentwindow.moveto($newx, $newy)} catch {}
    $oie.addressbar=$false

    $oie.visible = $true

    $dummy = isoieready($oie)

    $doctit = "Powershell Web Interface"

    $h = "<HTML>"
    $h+="<HEAD><TITLE>" + $doctit + "</TITLE>"
    $h+="<meta content=""text/html; charset=utf-8"" http-equiv=""Content-Type"">"
    $h+="<meta http-equiv=""X-UA-Compatible"" content=""IE=8"">"
    $h+="</HEAD>"
    $h+="<FRAMESET id='main' COLS=""13%, *"">"
    $h+="<FRAME SRC=""About:Blank"" NAME=""left"" id=""left"">"
    $h+="<frameset id='main2' rows=""30%,70%"">"
    $h+="<FRAME SRC=""About:Blank"" NAME=""middle"" id=""middle"">"
    $h+="<FRAME SRC=""About:Blank"" NAME=""bottom"" id=""bottom"">"
    $h+="</FRAMESET>"
    $h+="</frameset>"
    $h+="</HTML>"

    $oIE.document.documentelement.innerhtml = $h
   
    #if (isoieready($oie)) {$oie.document.IHTMLDocument2_write($h)}
   
    #$oie.Navigate('file://C:\win10una1703frapro_home\sources\$oem$\$1\_util\web_interface_powershell\mainmenu.html')
    #$oie.refresh()

    #if (isoieready($oie)) {$oie.document.IHTMLDocument2_write("<br>")}

    $dummy = isoieready($oie)

    # get ie version by register base
    # https://gallery.technet.microsoft.com/scriptcenter/Servers-Inventory-report-97da5709

    # get ie file version, 9 and before does not act like 10 and after for frame objects
    $fileversion = [System.Diagnostics.FileVersionInfo]::GetVersionInfo("C:\program files\internet explorer\iexplore.exe").FileVersion
    $finddot = $fileversion.indexof(".")
    $fileversion2 =  $fileversion.substring(0,$finddot)

    #start-sleep -m 100

    if (($fileversion2 -eq "10") -or ($fileversion2 -eq "11") -or ($fileversion2 -eq "12"))
        {
       
        #$flef = $oie.parent.document.getElementByid("left").document.documentelement # not working in frame...
       
        if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " Before getting frames" | Out-File $filnam01 -append}
       
        if (isoieready($oie)) {$flef = $oie.parent.document.getElementByid("left").contentdocument}
        if (isoieready($oie)) {$fmid = $oie.parent.document.getElementByid("middle").contentdocument}
        if (isoieready($oie)) {$fbot = $oie.parent.document.getElementByid("bottom").contentdocument}
       
        #if (isoieready($oie)) {$flef = $oie.parent.document.getElementByid("left").document.contentdocument}
        #                  set crefra = oie.parent.document.getElementByid(ffranam).contentdocument
       
        #$flef = $oie.parent.document.getElementByid("left").contentdocument
       
        if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " After getting frames" | Out-File $filnam01 -append}
        #set crefra = oie.parent.document.getElementByid(ffranam).contentdocument
        #break
        }
    else
        {
        if (isoieready($oie)) {$flef = $oie.document.frames("left").document}
        if (isoieready($oie)) {$fmid = $oie.document.frames("middle").document}
        if (isoieready($oie)) {$fbot = $oie.document.frames("bottom").document}
        }

    ### buttons to display in web interface
    #$fmid.IHTMLDocument2_write("arabutnam of 0: " + $arabutnam[0])

    $h = "<html><body>"
    #$h+="<body background=""" & basedir & "LOGO-background.jpg"">")
    $h+="<h3><span class=SpellE>" + $maitit + "</span></h3>"
    $h+="<form name='form1'>"
   
    if (isoieready($oie)) {$flef.IHTMLDocument2_write($h)}

    $i = 0
    foreach ($element in $arabutnam)
        {
        #$fmid.IHTMLDocument2_write($element)
       
        $h = "<input type=""hidden"" id=""" + $arabutnam[$i] + """ name=""" + $arabutnam[$i] + """ value=""0"">"
        $h+= "<input type=""button"" style=""height:50px;font-size:14px;white-space: normal;width:100%;"" value=""" + $arabutdes[$i] + """ " #name=""" + $arabutnam[$i] + """
        $h+= "onclick=""" + $arabutnam[$i] + ".value=1"""
       
        $i2=$i
        if ($i -gt $arabutnam.getupperbound(0))
            {
            $i2=$arabutnam.getupperbound(0)
            }
        else
            {
            $a=$aradepnam[$i2]
            }
        if ($a -ne $lasdep)
            {
            #=== new departement name
            if (isoieready($oie)) {$flef.IHTMLDocument2_write("<br>" + $a + "<br>")}
            $lasdep=$a
            }
        $h+=" style=""background-color: #" + $aradepcol[$i2] + "; color: #000000;""><br>"
        if (isoieready($oie)) {$flef.IHTMLDocument2_write($h)}
        $i=$i+1
        }

    $h = "</form>" + "</body>" + "</html>"
    if (isoieready($oie)) {$flef.IHTMLDocument2_write($h)}

    $oieparamout01.oie = $oie
    $oieparamout01.flef = $flef
    $oieparamout01.fmid = $fmid
    $oieparamout01.fbot = $fbot

    return $oieparamout01

    }
################################################
#   dynamicform in html
################################################

function dynamicform()
    {
    #dynamicform($pardescription, $parname, $pardefault, $partype, $parbuttons, $parvalidation, $parsuffix)
    if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " dynamic form generation" | Out-File $filnam01 -append}
   
    $dynamicformparamout01 = new-object dynamicformparamout;
    #$global:resbutstr = ""
    $resbut = 0
    $validation = 0
    $result= $null
   
    do
        {
        if ($validation -eq 0)
            {
            $h= "<body>"
            $h+= "<html>"
           
            # focus on a textbox (usually the first one)
            $h+= "<BODY onLoad=""document.form01." + $parname[0] + ".focus()"">"

            $h+= "<div class=MsoNormal align=center style='text-align:center'>"
            $h+= "</div>"
            $h+= "<form name=form01>"
           
            # input fields/textbox
            $i = 0
            foreach ($element in $parname)
                {
                $h+= $parprefix[$i] + ": "
                $h+= "<input type=" + $partype[$i] + ""
                $h+= " id=" + $parname[$i]
                $h+= " NAME=""" + $parname[$i] + """ size=""20"" value=""" + $pardefault[$i] + """ onKeypress=""return event.keyCode!=13"""

                $col = "blue"
               
                $h+= "&nbsp; <b><span style='color:" + $col + "'>&nbsp" + $parsuffix[$i] + "</span></b><br style='mso-special-character:line-break'>"

                $h+= "<![if !supportLineBreakNewLine]><style='mso-special-character:line-break'>"
                $h+= "<![endif]></p>"
                $i++
                }
           
            # button ok and cancel
            $i = 0
            foreach ($element in $parbuttons)
                {
                $typ01 = "button"
                $h+= "<input type=""hidden"" id=""" + $element + """ name=""" + $element + """ value=""0"">"
                $h+= "<input type=""" + $typ01 + """ value=""&nbsp;" + $element + "&nbsp;"" "
                $h+= "onclick=""" + $element + ".value=1"">"
                #$h+= "<input type=""" + $typ01 + """ name=""" + $element + """ value=""&nbsp;" + $element + "&nbsp;"">"
                $h+= "&nbsp&nbsp&nbsp"
                $i++
                #$h = "<input type=""hidden"" id=""" + $arabutnam[$i] + """ name=""" + $arabutnam[$i] + """ value=""0"">"
                #$h+= "<input type=""button"" style=""height:50px;font-size:14px;width:100%;"" value=""" + $arabutdes[$i] + """ " #name=""" + $arabutnam[$i] + """
                #$h+= "onclick=""" + $arabutnam[$i] + ".value=1"""
                }
           
            $h+= "</div>"
            $h+= "</form>"
            $h+= "</body>"
            $h+= "</html>"
            #IF (isoieready($oie)) {$fmid.IHTMLDocument2_write($h)}
           
            IF (isoieready($oie)) {$fmid.IHTMLDocument2_write($h)}
        }
        else
        {
            # dont display stuff again, wait for ok to click
       
        }
        start-sleep -m 50
       
        # button dynamic form check
        foreach ($element in $parbuttons)
            {
            if ($global:resbutstr -eq "")
                {
                if (isoieready($oie)) {$resbut = $fmid.getElementByID($element).value}
                if ($resbut -ne 0) {$global:resbutstr = $element}
                }
            }
       
        # buttons left frame check

        & $Actionflef
        $resbutstr = $global:resbutstr
        #$global:resbutstr =""
        try {$resbutstr = $resbutstr.tolower()}catch{}
           
        if ($global:resbutstr -ne "")
            {
            if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + $global:resbutstr + " was pressed" | Out-File $filnam01 -append}

            # validate result and reloop if something is wrong
            }
       
        # will return result after sub
        $dynamicformparamout01.arabutnam = $global:resbutstr

        if ($global:resbutstr -eq "ok")
            {
            # validate results
           
           
            $i = 0
            $result = $null
            foreach ($element in $parname)
                {
                $resultdummy = ""
                if (isoieready($oie)) {$resultdummy = $fmid.getElementByID($parname[$i]).value}
                [string[]]$result+= $resultdummy
               
                #if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " stuff: " + $i + " " + $result[$i]| Out-File $filnam01 -append}
                $i++
                }
           
            }
            else
            {
            # something else than OK was pressed
            $result = $null
            }
        # everything is valid, even empty strings in html boxes
        $validation=1
        } until ((($global:resbutstr -ne "") -and ($validation -eq 1)) -or ($oie.hwnd -eq $null))
   
    # reset ok and cancel buttons value to 0
    foreach ($element in $parbuttons)
        {
        if (isoieready($oie)) {$fmid.getElementByID($element).value=0}
        }
   
    $dynamicformparamout01.araresults = $result
    return $dynamicformparamout01
    #, $resbutcancel
    }

##############################################
#   START
##############################################

# get powershell version
# $PSVersionTable

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$scriptname = split-path -leaf $MyInvocation.MyCommand.Definition
$Logfilename = $scriptname + "_log.txt"
$filnam01 = $scriptPath + "\" + $Logfilename
$logall = 1
$dynamicformparamout01 = new-object dynamicformparamout;
   
if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " START" | Out-File $filnam01}

$maitit = "Powershell Web Interface"

$project01 = "test"
#$project01 = "office365"

# each project have it's own buttons in left frame

if ($project01 -eq "test")
    {
    # buttons to display in internet explorer left frame
    [string[]]$arabutnam="test"
    [string[]]$arabutdes="test something"
    [string[]]$aradepnam="Change"
    [string[]]$aradepcol="cccccc"
    }

if ($project01 -eq "office365")
    {
    # buttons to display in internet explorer left frame
    [string[]]$arabutnam="createlibrary"
    [string[]]$arabutdes="office 365 library creation"
    [string[]]$aradepnam="Change"
    [string[]]$aradepcol="cccccc"
    }

# buttons for all projects
$arabutnam+="githubcreatecommit"
$arabutdes+="Github create and commit"
$aradepnam+="Github"
$aradepcol+="cccccc"

$arabutnam+="githubget"
$arabutdes+="Gethub Get"
$aradepnam+="Github"
$aradepcol+="cccccc"

$arabutnam+="info01"
$arabutdes+="Information"
$aradepnam+="all"
$aradepcol+="cccccc"

$arabutnam+="quit01"
$arabutdes+="Quitter"
$aradepnam+="all"
$aradepcol+="cccccc"

# internet explorer interface for powershell
$oieparamin01 = new-object oieparamin01;
$oieparamin01.height01 = 800
$oieparamin01.width01 = 1150
# we call the fonction with a typed/struct variable as parameter, this way we can change the number of parameters dynamically
$oieparamout01 = new-object oieparamout01;
$oieparamout01  = makenewOIE($oieparamin01)
# put the frames in friendly variables names
$oie = $oieparamout01.oie
$flef = $oieparamout01.flef
$fmid = $oieparamout01.fmid
$fbot = $oieparamout01.fbot

#=== make internet explorer the main active window
#a = objShe.AppActivate("http:/// - " & doctit & " - M")
#a = objShe.AppActivate(doctit & " - M")

$usenam = [Environment]::UserName

#$fmid.IHTMLDocument2_write([System.Security.Principal.WindowsIdentity]::GetCurrent().Name + "<br>")

#=== string result for a button press in a frame (lef = left frame, mid = middle frame (up))
$resbutstr=""

$reskeylef=0
$reskeymid=0
$reskeybot=0

#=== we also chek the key presse in each frame
#=== we do this cause we want "enter" key to be used instead of pressing "ok" button with the mouse
#$flef.onkeypress = GetRef("Checklef")
#$fmid.onkeypress = GetRef("Checkmid")
#$fbot.onkeypress = GetRef("Checkbot")

#############################################
#   main loop
#############################################
#events
#http://demay.iut.lr.free.fr/doc/2A/IC1/PowerShell/La%20gestion%20des%20evenements%20sous%20PowerShell.pdf

### this dynamic (code in code) script will check for buttons pressed in left frame (control frame)
$Actionflef =
    {

    foreach ($element in $arabutnam)
        {
        if ($global:resbutstr -eq "")
            {
                if (isoieready($oie))
                    {
                    $resbut = $flef.getElementByID($element).value
                    }
                if ($resbut -eq 1)
                    {
                    # put button that was pressed in left frame in a global variable
                    $global:resbutstr = $element
                    $flef.getElementByID($element).value = 0
                    #write-host $resbut
                    #write-host $element
                    }
            }
        }
    }


#https://github.com/PowerShellMafia/PowerSploit/blob/master/Exfiltration/Get-Keystrokes.ps1

############################ event test flag #################
$event01 = 0
   
#################################################################################
# balloon tip 5 seconde or until $balloon.dispose()
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Title = "This is the title"
$Text = "This is the text"
$EventTimeOut = 5

$balloon = New-Object System.Windows.Forms.NotifyIcon
$balloon.Icon = [System.Drawing.SystemIcons]::Information
$balloon.BalloonTipTitle = $Title
$balloon.BalloonTipText = $Text
$balloon.Visible = $True

$balloon.ShowBalloonTip(1)

$balloon.Dispose()

While (($resbutstr –ne "quit01") -and ($oie.hwnd -ne $null))
    {
    start-sleep -m 50

    # check buttons in left frame
    & $Actionflef
   
    $resbutstr = $global:resbutstr
    $global:resbutstr =""

    try {$resbutstr = $resbutstr.tolower()}catch{}

    #if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " " + $oie | Out-File $filnam01 -append}
    #if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " " + $flef | Out-File $filnam01 -append}
   
    $resbut = 0
    #write-host $resbutstr

    ###################################################
    # github create and commit
    ###################################################

    if ($resbutstr -eq "githubcreatecommit")
        {
        $resbutstr = ""
        $resbut = 0

        if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " button githubcreatecommit was clicked" | Out-File $filnam01 -append}

        if (isoieready($oie)) {$FMID.IHTMLDocument2_open("ABOUT:BLANK") | out-null}
        if (isoieready($oie)) {$Fbot.IHTMLDocument2_open("ABOUT:BLANK") | out-null}
       
        $fmid.IHTMLDocument2_write("<br>Github create and commit is not done yet")
       
        $fmid.IHTMLDocument2_write("<br><br>Press any button in left frame to continue...")


        }
    if ($resbutstr -eq "githubget")
        {
        $resbutstr = ""
        $resbut = 0

        if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " button githubcreatecommit was clicked" | Out-File $filnam01 -append}

        # clear frame
        if (isoieready($oie)) {$FMID.IHTMLDocument2_open("ABOUT:BLANK") | out-null}
        if (isoieready($oie)) {$Fbot.IHTMLDocument2_open("ABOUT:BLANK") | out-null}
       
        $fmid.IHTMLDocument2_write("<br>Github get is not done yet")
       
        $fmid.IHTMLDocument2_write("<br><br>Press any button in left frame to continue...")


        }
    if ($resbutstr -eq "test")
        {
        $resbutstr = ""
        $resbut = 0
        # before we go to the dynamic form, we reset left frame button value
        #if (isoieready($oie)) {$flef.getElementByID($resbutstr).value = 0}
       
        # TEST reset button value (unpress the button)

        if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " button TEST was clicked" | Out-File $filnam01 -append}
       
        # clear frame
        if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " clearing frame" | Out-File $filnam01 -append}

        # clear frame
        if (isoieready($oie)) {$FMID.IHTMLDocument2_open("ABOUT:BLANK") | out-null}
        if (isoieready($oie)) {$Fbot.IHTMLDocument2_open("ABOUT:BLANK") | out-null}
       
        # get and validate some parameters

        [string[]]$parprefix="Name of the project to create"
        [string[]]$parname="name01"
        [string[]]$pardefault="helloworld"
        [string[]]$partype="textbox"
        [string[]]$parsuffix="Entrez un numéro de projet"
       
        # parameter number 2 to inputbox
        $parprefix+="stuff to enter"
        $parname+="name02"
        $pardefault+="salutlesamis"
        $partype+="textbox"
        $parsuffix+="ceci est un test"

        [string[]]$parbuttons="ok"
        $parbuttons+="cancel"
       
        $dynamicformparamout01 = dynamicform($parprefix, $parname, $pardefault, $partype, $parbuttons, $parsuffix, $arabutnam)
       
        # all value returned by the web form are in $result array
       
        $i=0
       
        if ($dynamicformparamout01.arabutnam -eq "ok")
            {
            ##############################################
            #   do some stuff
            #   1 create folder structure
            #   2 create a ldap user
            #   3 create ldap group
            #   4 create a office 365 site and library
            #   5 extract documents from office 365 based on terms and major version
            ##############################################           
           
            # clear frame
            if (isoieready($oie)) {$FMID.IHTMLDocument2_open("ABOUT:BLANK") | out-null}
       
            $h = ""
            $i = 0
                   
            $h+= "<table width=""100%"" BORDERCOLOR=""black"" class=MsoTableGrid border=1 CELLSPACING=0 cellpadding=2 style='border-collapse:collapse;border: 1px solid black'>"
           
            foreach ($element in $dynamicformparamout01.araresults)
                {
                $h+= "<tr>"
                # display results in fbot frame
                $h += "<td>" + $parprefix[$i] + "</td>"
                $h += "<td>" + $dynamicformparamout01.araresults[$i] + "</td>"
                if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " stuff2: " + $i + " " + $dynamicformparamout01.araresults[$i]| Out-File $filnam01 -append}
                $h+= "</tr>"
                $i++
                }
           
            $h+="</table>"
            IF (isoieready($oie)) {$fmid.IHTMLDocument2_write($h)}
           
            $resbutstr = ""
            $resbut = 0

            }
        elseif ($dynamicformparamout01.arabutnam -eq "cancel")
            {
            if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " another button was pressed: " + $dynamicformparamout01.arabutnam| Out-File $filnam01 -append}
           
            # reset button value for left frame (unclick the button)
            #if (isoieready($oie)) {$flef.getElementByID($resbutstr).value = 0}
            $resbutstr = ""
            $resbut = 0
            if (isoieready($oie)) {$FMID.IHTMLDocument2_open("ABOUT:BLANK") | out-null}
            if (isoieready($oie)) {$Fbot.IHTMLDocument2_open("ABOUT:BLANK") | out-null}

            }
        else
            {
            if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " another button was pressed: " + $dynamicformparamout01.arabutnam| Out-File $filnam01 -append}
            # since another button on left frame was pressed
            # no action is done here, and the button stay pressed until it's action is done
            # clear all frames
            if (isoieready($oie)) {$FMID.IHTMLDocument2_open("ABOUT:BLANK") | out-null}
            if (isoieready($oie)) {$Fbot.IHTMLDocument2_open("ABOUT:BLANK") | out-null}
           
            $resbutstr = $dynamicformparamout01.arabutnam
           
            }
       

        }

    if ($resbutstr -eq "office365")
        {
       
        # secure password example TO ENTER PASSWORD
        function str([Security.SecureString]$s)
            {
            return [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($s))
            }
        }

    if ($resbutstr -eq "info01")
        {
        $resbutstr = ""
        $resbut = 0
       
        #if (isoieready($oie)) {$flef.getElementByID($resbutstr).value = 0}
        if (isoieready($oie)) {$FMID.IHTMLDocument2_open("ABOUT:BLANK") | out-null}
        if (isoieready($oie)) {$Fbot.IHTMLDocument2_open("ABOUT:BLANK") | out-null}
       
        # main action for this button
        $h = "<br>Powershell web interface<br>"
        $h+= "<br>This program was made by: sergefournier(@)hotmail.com<br>"
        $h+= "<br>2016-03-04 added some innerhtml to clear frames<br>"
        $h+= "<br>2016-03-04 removed innerhtml cause it does not work without office installed<br>"
        IF (isoieready($oie)) {$fmid.IHTMLDocument2_write($h)}
       
        }
   
    # system string does not have tolower method so it generate an error
    #try {$resbutstr = $resbutstr.tolower()} catch {}
   
    }

$dummy = isoieready($oie)

if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " oie state: " + $dummy | Out-File $filnam01 -append}

if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " button pressed: " + $resbutstr | Out-File $filnam01 -append}

if ($logall=1) {(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " END quit was pressed or internet explorer closed" | Out-File $filnam01 -append}

# end of program, quit was pressed or OIE handle is null
if (isoieready($oie))
    {
    #$fmid.IHTMLDocument2_write("EXIT " + $resbutlefstr + "<br>")
   
    Get-EventSubscriber | Unregister-Event | out-null
    #try {Get-EventSubscriber -SourceIdentifier "clickflef" | Unregister-Event | out-null} catch {}
    #try {Get-EventSubscriber -SourceIdentifier "clickfmid" | Unregister-Event | out-null} catch {}
    #try {Get-EventSubscriber -SourceIdentifier "clickfbot" | Unregister-Event | out-null} catch {}   
    $oie.quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($oie) | out-null
    }

############## REFERENCE
function Check-NewGmail {
  param(
    [String]$Email = (Read-Host "Enter your email"),   
    [Security.SecureString]$Password = (Read-Host "Enter email password" -as)
  )

  function str([Security.SecureString]$s) {
    return [Runtime.InteropServices.Marshal]::PtrToStringAuto(
      [Runtime.InteropServices.Marshal]::SecureStringToBSTR($s)
    )
  }
  $com = New-Object -com MSXML2.XMLHTTP.3.0
  $com.open('GET', $('https://' + $Email + ':' + `
             (str $Password) + '@mail.google.com/mail/feed/atom'), $false)
  $com.setRequestHeader('Content-Type', 'application/x-www-from-urlcoded')
  $com.send()

  $com.responseText -match 'fullcount>\d+' | Out-Null; $res = ($matches[0] -split '>')[1]
  Write-Host You have $res new letter`(s`).
}

   
#Remove-Variable $oie