Search is not available for this dataset
content
stringlengths 0
376M
|
---|
<reponame>npocmaka/Windows-Server-2003
while true
Set System = GetObject("winmgmts:{impersonationLevel=impersonate}!Win32_ComputerSystem.Name=""ALANBOS3""")
WScript.Echo System.Caption
WScript.Echo System.PrimaryOwnerName
WScript.Echo System.Domain
WScript.Echo System.SystemType
wend
|
On Error Resume Next
Set t_Service = GetObject ("winmgmts:\root\default")
Set t_Class = t_Service.Get ("__CIMOMIDentification")
WScript.Echo t_Class.Path_.Path
Set t_Class = GetObject ("winmgmts:root/cimv2:win32_logicaldisk")
WScript.Echo t_Class.Path_.Path
Set t_Instance = GetObject ("winmgmts:{impersonationLevel=impersonate}!root/cimv2:win32_logicaldisk=""C:""")
WScript.Echo t_Instance.Path_.Path
Set t_Class = GetObject ("winmgmts:win32_logicaldisk")
WScript.Echo t_Class.Path_.Path
Set t_Instance = GetObject ("winmgmts:{impersonationLevel=impersonate}!win32_logicaldisk=""C:""")
WScript.Echo t_Instance.Path_.Path
if Err <> 0 Then
WScript.Echo Err.Number, Err.Description
Err.Clear
End If
|
<gh_stars>10-100
'This script shows how you can list all machine hardware details
on error resume next
set theLocator = CreateObject("WbemScripting.SWbemLocator")
if err <> 0 then
WScript.Echo "Error on CreateObject" & Err.Number & Err.Description
end if
set Service = theLocator.ConnectServer("wmi-tecra1", "root\cimv2", "Administrator")
Service.Security_.impersonationLevel = 3
if err <> 0 then
WScript.Echo "Error on ConnectServer" & Err.Number & Err.Description
end if
' THE PROCESSORS
Wscript.Echo
Wscript.Echo "The Processors on the machine:"
for each Processor in Service.InstancesOf ("Win32_Processor")
WScript.Echo Processor.Name & " Revision: " & Processor.Revision
WScript.Echo "DeviceID: " & Processor.DeviceID
WScript.Echo "Description: " & Processor.Description
WScript.Echo "AddressWidth: " & Processor.AddressWidth
WScript.Echo "DataWidth: " & Processor.DataWidth
WScript.Echo "CurrentClockSpeed: " & Processor.CurrentClockSpeed
Wscript.Echo
next
if err <> 0 then
WScript.Echo "Error" & Err.Number & Err.Description
end if
' THE Disk Drives
Wscript.Echo
Wscript.Echo "The Disk Drives on the machine:"
for each Drive in Service.InstancesOf ("Win32_DiskDrive")
WScript.Echo "DeviceID: " & Drive.DeviceID
WScript.Echo "Description: " & Drive.Description
WScript.Echo "Caption: " & Drive.Caption
WScript.Echo "Size: " & Drive.Size
WScript.Echo "BytesPerSector: " & Drive.BytesPerSector
WScript.Echo "SectorsPerTrack: " & Drive.SectorsPerTrack
WScript.Echo "InterfaceType: " & Drive.InterfaceType
WScript.Echo "MediaType: " & Drive.MediaType
WScript.Echo "Manufacturer: " & Drive.Manufacturer
WScript.Echo "Number of partitions: " & Drive.Partitions
WScript.Echo "TotalCylinders: " & Drive.TotalCylinders
WScript.Echo "TotalHeads: " & Drive.TotalHeads
WScript.Echo "TotalHeads: " & Drive.TotalHeads
WScript.Echo "TracksPerCylinder: " & Drive.TracksPerCylinder
Wscript.Echo
next
' THE CD ROM Drives
Wscript.Echo
Wscript.Echo "The CD ROM Drives on the machine:"
for each Drive in Service.InstancesOf ("Win32_CDRomDrive")
WScript.Echo "DeviceID: " & Drive.DeviceID
WScript.Echo "Description: " & Drive.Description
WScript.Echo "Caption: " & Drive.Caption
WScript.Echo "MediaType: " & Drive.MediaType
WScript.Echo "Manufacturer: " & Drive.Manufacturer
WScript.Echo "MediaLoaded: " & Drive.MediaLoaded
if Drive.MediaLoaded then
WScript.Echo "VolumeName: " & Drive.VolumeName
end if
Wscript.Echo
next
|
Option Explicit
Sub Main()
Dim test, i As Long
test = Array(0.34, 0.070145, 0.06, 0.05, 0.50214, 0.56, 1#, 0.99, 0#, 0.7388727)
For i = 0 To UBound(test)
Debug.Print test(i) & " := " & Price_Fraction(CSng(test(i)))
Next i
End Sub
Private Function Price_Fraction(n As Single) As Single
Dim Vin, Vout, i As Long
Vin = Array(0.06, 0.11, 0.16, 0.21, 0.26, 0.31, 0.36, 0.41, 0.46, 0.51, 0.56, 0.61, 0.66, 0.71, 0.76, 0.81, 0.86, 0.91, 0.96, 1.01)
Vout = Array(0.1, 0.18, 0.26, 0.32, 0.38, 0.44, 0.5, 0.54, 0.58, 0.62, 0.66, 0.7, 0.74, 0.78, 0.82, 0.86, 0.9, 0.94, 0.98, 1#)
For i = 0 To UBound(Vin)
If n < Vin(i) Then Price_Fraction = Vout(i): Exit For
Next i
End Function
|
Const SAKEY_RETURN = 13
Const SAKEY_ESCAPE = 27
Const SAKEY_LEFT = 37
Const SAKEY_UP = 38
Const SAKEY_RIGHT = 39
Const SAKEY_DOWN = 40
Set Keypad = CreateObject("sacom.sakeypad")
do while 1
Keypress = Keypad.Key
Select Case Keypress
case SAKEY_RETURN
wscript.echo "Return"
case SAKEY_ESCAPE
wscript.echo "Escape"
case SAKEY_LEFT
wscript.echo "Left arrow"
case SAKEY_RIGHT
wscript.echo "Right arrow"
case SAKEY_UP
wscript.echo "Up arrow"
case SAKEY_DOWN
wscript.echo "Down arrow"
End Select
loop
|
<filename>base/cluster/admin/msclus/vbscript/quorum.vbs
Option Explicit
Main
Sub Main
Dim oCluster
Dim ClusterName
Dim oQuorum
Dim nCount
Dim sCluster
Set oCluster = CreateObject("MSCluster.Cluster")
sCluster = InputBox( "Cluster to open?" )
oCluster.Open( sCluster )
'for nCount = 1 to 100
ClusterName = oCluster.Name
MsgBox "Cluster Name is " & ClusterName
'MsgBox "Cluster Version is " & oCluster.Version.BuildNumber
MsgBox "Quorum log size is " & oCluster.QuorumLogSize
MsgBox "Quorum log path is " & oCluster.QuorumPath
set oQuorum = oCluster.QuorumResource
MsgBox "Quorum resource name is " & oQuorum.Name
'oCluster.QuorumResource = oQuorum
'MsgBox "Iteration count is" & nCount
'next
MsgBox "Done!"
End Sub
|
on error resume next
set events = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecNotificationQuery _
("select * from __instancecreationevent where targetinstance isa 'Win32_NTLogEvent'")
if err <> 0 then
WScript.Echo Err.Description, Err.Number, Err.Source
end if
do
' Note that the timeout value below (in ms) passed
' as an argument can explicitly specified
set NTEvent = events.nextevent ()
if err <> 0 then
WScript.Echo Err.Number, Err.Description, Err.Source
else
WScript.Echo NTEvent.TargetInstance.Message
end if
exit do
loop
WScript.Echo "finished"
|
<gh_stars>10-100
' A "Hello, World!" program in Visual Basic.
Module Hello
Sub Main()
MsgBox("Hello, World!") ' Display message on computer screen.
End Sub
End Module
|
'Set objSet = GetObject("winmgmts://./root/cimv2").InstancesOf("Win32_Volume")
'Set objSet = GetObject("winmgmts:{impersonationLevel=impersonate}").InstancesOf("Win32_Volume")
Set objSet = GetObject("winmgmts:").InstancesOf("Win32_Volume")
for each Volume in objSet
WScript.Echo Volume.DriveLetter & " " & Volume.DeviceID
next
|
Function Divide(Dividend As Integer, Divisor As Integer, ByRef Result As Double) As Boolean
Divide = True
On Error Resume Next
Result = Dividend / Divisor
If Err <> 0 Then
Divide = False
On Error GoTo 0
End If
End Function
'For use :
Sub test_Divide()
Dim R As Double, Ddd As Integer, Dvs As Integer, B As Boolean
Ddd = 10: Dvs = 3
B = Divide(Ddd, Dvs, R)
Debug.Print "Divide return : " & B & " Result = " & R
Ddd = 10: Dvs = 0
B = Divide(Ddd, Dvs, R)
Debug.Print "Divide return : " & B & " Result = " & R
End Sub
|
Option Explicit
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Const HT As String = "H T"
Public Sub PenneysGame()
Dim S$, YourSeq$, ComputeSeq$, i&, Seq$, WhoWin$, flag As Boolean
Do
S = WhoWillBeFirst(Choice("Who will be first"))
If S = "ABORT" Then Exit Do
Debug.Print S; " start"
YourSeq = Choice("Your sequence", 3)
If YourSeq Like "*ABORT*" Then Exit Do
Debug.Print "Your sequence : " & YourSeq
ComputeSeq = vbNullString
For i = 1 To 3
ComputeSeq = ComputeSeq & Random
Next i
Debug.Print "Computer sequence : " & ComputeSeq
Seq = vbNullString
Do
Seq = Seq & Random
Debug.Print Seq
Sleep 1000
Loop While Not Winner(ComputeSeq, YourSeq, Seq, WhoWin)
Debug.Print WhoWin; " win"
If MsgBox(WhoWin & " win" & vbCrLf & "Play again?", vbYesNo) = vbNo Then flag = True
Debug.Print ""
Loop While Not flag
Debug.Print "Game over"
End Sub
Private Function WhoWillBeFirst(YourChoice As String) As String
Dim S$
S = Random
Select Case YourChoice
Case "ABORT": WhoWillBeFirst = YourChoice
Case Else:
WhoWillBeFirst = IIf(S = YourChoice, "You", "Computer")
End Select
End Function
Private Function Choice(Title As String, Optional Seq As Integer) As String
Dim S$, i&, t$
If Seq = 0 Then Seq = 1
t = Title
For i = 1 To Seq
S = vbNullString
Do
S = InputBox("Choose between H or T : ", t)
If StrPtr(S) = 0 Then S = "Abort"
S = UCase(S)
Loop While S <> "H" And S <> "T" And S <> "ABORT"
Choice = Choice & S
t = Title & " " & Choice
If Choice Like "*ABORT*" Then Exit For
Next i
End Function
Private Function Random() As String
Randomize Timer
Random = Split(HT, " ")(CInt(Rnd))
End Function
Private Function Winner(Cs$, Ys$, S$, W$) As Boolean
If Len(S) < 3 Then
Winner = False
Else
If Right(S, 3) = Cs And Right(S, 3) = Ys Then
Winner = True
W = "Computer & you"
ElseIf Right(S, 3) = Cs And Right(S, 3) <> Ys Then
Winner = True
W = "Computer"
ElseIf Right(S, 3) = Ys And Right(S, 3) <> Cs Then
Winner = True
W = "You"
End If
End If
End Function
|
Function heroArea(a As Integer, b As Integer, c As Integer) As Double
s = (a + b + c) / 2
On Error GoTo Err
heroArea = Sqr(s * (s - a) * (s - b) * (s - c))
Exit Function
Err:
heroArea = -1
End Function
Function hero(h As Double) As Boolean
hero = (h - Int(h) = 0) And h > 0
End Function
Public Sub main()
Dim list() As Variant, items As Integer
Dim a As Integer, b As Integer, c As Integer
Dim hArea As Double
Dim tries As Long
For a = 1 To 200
For b = 1 To a
For c = 1 To b
tries = tries + 1
If gcd(gcd(a, b), c) = 1 Then
hArea = heroArea(a, b, c)
If hero(hArea) Then
ReDim Preserve list(items)
list(items) = Array(CStr(hArea), CStr(a + b + c), CStr(a), CStr(b), CStr(c))
items = items + 1
End If
End If
Next c
Next b
Next a
list = sort(list)
Debug.Print "Primitive Heronian triangles with sides up to 200:"; UBound(list) + 1; "(of"; tries; "tested)"
Debug.Print
Debug.Print "First 10 ordered by area/perimeter/sides:"
Debug.Print "area perimeter sides"
For i = 0 To 9
Debug.Print Format(list(i)(0), "@@@"), Format(list(i)(1), "@@@"),
Debug.Print list(i)(2); "x"; list(i)(3); "x"; list(i)(4)
Next i
Debug.Print
Debug.Print "area = 210:"
Debug.Print "area perimeter sides"
For i = 0 To UBound(list)
If Val(list(i)(0)) = 210 Then
Debug.Print Format(list(i)(0), "@@@"), Format(list(i)(1), "@@@"),
Debug.Print list(i)(2); "x"; list(i)(3); "x"; list(i)(4)
End If
Next i
End Sub
|
<reponame>LaudateCorpus1/RosettaCodeData
Private Sub plot_coordinate_pairs(x As Variant, y As Variant)
Dim chrt As Chart
Set chrt = ActiveSheet.Shapes.AddChart.Chart
With chrt
.ChartType = xlLine
.HasLegend = False
.HasTitle = True
.ChartTitle.Text = "Time"
.SeriesCollection.NewSeries
.SeriesCollection.Item(1).XValues = x
.SeriesCollection.Item(1).Values = y
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "microseconds"
End With
End Sub
Public Sub main()
x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]
y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]
plot_coordinate_pairs x, y
End Sub
|
a = 1234.5678
' Round to three decimal places. Groups by default. Output = "1,234.568".
WScript.Echo FormatNumber(a, 3)
' Truncate to three decimal places. Output = "1234.567".
WScript.Echo Left(a, InStr(a, ".") + 3)
' Round to a whole number. Grouping disabled. Output = "1235".
WScript.Echo FormatNumber(a, 0, , , False)
' Use integer portion only and pad with zeroes to fill 8 chars. Output = "00001234".
WScript.Echo Right("00000000" & Int(a), 8)
|
<filename>admin/wmi/wbem/xmltransport/samples/client/scripts/execmethod.vbs
'***************************************************************************
'This script tests the execution of a method using XML/HTTP
'***************************************************************************
On Error Resume Next
Dim objLocator
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
' Replace the first argument to this function with the URL of your WMI XML/HTTP server
' For the local machine, use the URL as below
Dim objService
Set objService = objLocator.ConnectServer("[http://localhost/cimom]", "root\cimv2")
' Get the class/instance on which you wish to execute the method
Set process = objService.Get("Win32_Process")
' Create the arguments for method execution
set startupinfo = objService.Get("Win32_ProcessStartup")
set instance = startupinfo.SpawnInstance_
instance.Title = "Foo Bar"
result = process.Create ("notepad.exe",,instance,processid)
WScript.Echo "Method returned result = " & result
WScript.Echo "Id of new process is " & processid
if err <>0 then
WScript.Echo Err.Description
end if
|
Option Explicit
'//on error resume next
Dim objArgs
Dim objVolume, objSet, obj
Dim strQuery, strVolume, strHost, strNamespace
set objArgs = wscript.Arguments
if objArgs.count < 2 then
wscript.echo "Usage rwprop <host> <volumePath>"
wscript.quit(1)
end if
strHost = objArgs(0)
strVolume = Replace(objArgs(1), "\", "\\")
strNamespace = "winmgmts://" & strHost & "/root/cimv2"
'// Get the volume
strQuery = "select * from Win32_Volume where Name = '" & strVolume & "'"
set objSet = GetObject(strNamespace).ExecQuery(strQuery)
for each obj in objSet
set objVolume = obj
exit for
next
wscript.echo "Volume: " & objVolume.Name
wscript.echo "----------------------------------------------"
wscript.echo "--DriveLetter tests"
wscript.echo "----------------------------------------------"
Call DriveLetter(objVolume)
wscript.echo "----------------------------------------------"
wscript.echo "--Label tests"
wscript.echo "----------------------------------------------"
Call Label(objVolume)
wscript.echo "----------------------------------------------"
wscript.echo "--IndexingEnabled tests"
wscript.echo "----------------------------------------------"
Call IndexingEnabled(objVolume)
sub DriveLetter(ByRef objVolume)
'on error resume next
Dim rc
Dim strOrigDriveLetter
strOrigDriveLetter = objVolume.DriveLetter
wscript.echo "DriveLetter= " & objVolume.DriveLetter
if IsNull(objVolume.DriveLetter) then
call SetVerifyProperty(objVolume, "DriveLetter", "M:")
else
call SetVerifyProperty(objVolume, "DriveLetter", Null)
end if
call SetVerifyProperty(objVolume, "DriveLetter", "N:")
call SetVerifyProperty(objVolume, "DriveLetter", "P:")
call SetVerifyProperty(objVolume, "DriveLetter", Null)
wscript.echo "EXPECT FAILURE - assigning SuperBogusDriveLetter string"
call SetVerifyProperty(objVolume, "DriveLetter", "SuperBogusDriveLetter")
wscript.echo "EXPECT FAILURE - assigning -1"
call SetVerifyProperty(objVolume, "DriveLetter", -1)
call SetVerifyProperty(objVolume, "DriveLetter", strOrigDriveLetter)
end sub
sub Label(ByRef objVolume)
on error resume next
Dim rc, strOrigLabel
strOrigLabel = objVolume.Label
wscript.echo "Label= " & objVolume.Label
if IsNull(objVolume.Label) then
call SetVerifyProperty(objVolume, "Label", "superbad")
else
call SetVerifyProperty(objVolume, "Label", Null)
end if
call SetVerifyProperty(objVolume, "Label", "sexmachine")
call SetVerifyProperty(objVolume, "Label", "getonup")
call SetVerifyProperty(objVolume, "Label", "")
call SetVerifyProperty(objVolume, "Label", Null)
wscript.echo "EXPECT FAILURE - assigning SuperLongBogusLabelString..."
call SetVerifyProperty(objVolume, "Label", "SuperLongBogusLabelStringThatShouldBeWayTooLongForSuccess")
wscript.echo "EXPECT FAILURE - assigning -1"
call SetVerifyProperty(objVolume, "Label", -1)
call SetVerifyProperty(objVolume, "Label", strOrigLabel)
end sub
sub IndexingEnabled(ByRef objVolume)
on error resume next
Dim rc, fIndex
fIndex = objVolume.IndexingEnabled
if fIndex = True then
call SetVerifyProperty(objVolume, "IndexingEnabled", False)
else
call SetVerifyProperty(objVolume, "IndexingEnabled", True)
end if
call SetVerifyProperty(objVolume, "IndexingEnabled", False)
call SetVerifyProperty(objVolume, "IndexingEnabled", 0)
call SetVerifyProperty(objVolume, "IndexingEnabled", True)
call SetVerifyProperty(objVolume, "IndexingEnabled", 1)
wscript.echo "EXPECT FAILURE - assigning perLongBogusLabelString..."
call SetVerifyProperty(objVolume, "IndexingEnabled", "SuperLongBogusLabelStringThatShouldBeWayTooLongForSuccess")
wscript.echo "EXPECT FAILURE - assigning -102331"
call SetVerifyProperty(objVolume, "IndexingEnabled", -102331)
call SetVerifyProperty(objVolume, "IndexingEnabled", fIndex)
end sub
sub SetVerifyProperty(ByRef objInOut, ByRef strProp, ByRef Value)
on error resume next
dim objPropSet, objProp, RefreshValue, rc
set objPropSet = objInOut.Properties_
set objProp = objPropSet.Item(strProp)
wscript.echo "setting " & objInOut.Path_.Class & "." & strProp & "=" & Value
objProp.Value = Value
objInOut.Put_
rc = ReportIfErr(Err, "FAILED - " & objInOut.Path_.Class & " put operation")
set objInOut = RefreshObject(objInOut)
rc = ReportIfErr(Err, "FAILED - " & objInOut.Path_.Class & " refresh operation")
set objPropSet = objInOut.Properties_
set objProp = objPropSet.Item(strProp)
RefreshValue = objProp.Value
wscript.echo "refreshed " & objInOut.Path_.Class & "." & strProp & "=" & RefreshValue
end sub
Function MapErrorCode(ByRef strClass, ByRef strMethod, ByRef intCode)
Dim objClass, objMethod
Dim values
set objClass = GetObject(strNamespace).Get(strClass, &h20000)
set objMethod = objClass.methods_(strMethod)
values = objMethod.qualifiers_("values")
if ubound(values) < intCode then
wscript.echo " FAILED - no error message found for " & intCode & " : " & strClass & "." & strMethod
MapErrorCode = ""
else
MapErrorCode = values(intCode)
end if
End Function
Function ReportIfErr(ByRef objErr, ByRef strMessage)
Dim strError
ReportIfErr = objErr.Number
if objErr.Number <> 0 then
strError = strMessage & " : " & Hex(objErr.Number) & " : " & objErr.Description
wscript.echo (strError)
objErr.Clear
Set objLastError = CreateObject("wbemscripting.swbemlasterror")
wscript.wcho("Provider: " & objLastError.ProviderName)
wscript.wcho("Operation: " & objLastError.Operation)
wscript.wcho("Description: " & objLastError.Description)
wscript.wcho("StatusCode: 0x" & Hex(objLastError.StatusCode))
end if
End Function
Function RefreshObject(ByRef objIn)
on error resume next
Dim strRelPath, rc
set RefreshObject = GetObject(strNamespace).Get(objIn.Path_)
rc = ReportIfErr(Err, "FAILED - " & objIn.Path_.Class & ".Get operation")
End Function
|
<filename>Task/Find-the-missing-permutation/VBScript/find-the-missing-permutation.vb
arrp = Array("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD",_
"ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA",_
"CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD",_
"BADC", "BDAC", "CBDA", "DBCA", "DCAB")
Dim col(4)
'supposes that a complete column have 6 of each letter.
target = (6*Asc("A")) + (6*Asc("B")) + (6*Asc("C")) + (6*Asc("D"))
missing = ""
For i = 0 To UBound(arrp)
For j = 1 To 4
col(j) = col(j) + Asc(Mid(arrp(i),j,1))
Next
Next
For k = 1 To 4
n = target - col(k)
missing = missing & Chr(n)
Next
WScript.StdOut.WriteLine missing
|
<gh_stars>1-10
Dim total As Variant, prim As Variant, maxPeri As Variant
Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)
Dim p As Variant
p = CDec(s0) + CDec(s1) + CDec(s2)
If p <= maxPeri Then
prim = prim + 1
total = total + maxPeri \ p
newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2
newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2
newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2
End If
End Sub
Public Sub Program_PythagoreanTriples()
maxPeri = CDec(100)
Do While maxPeri <= 10000000#
prim = CDec(0)
total = CDec(0)
newTri 3, 4, 5
Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives."
maxPeri = maxPeri * 10
Loop
End Sub
|
# Taken from https://documentation.help/FreeBASIC/KeyPgPublic.html
Private Sub i_am_private
End Sub
Public Sub i_am_public
End Sub
|
<filename>admin/wmi/wbem/scripting/test/whistler/directory/ldapsd.vbs
set l = CreateObject("WbemScripting.SWbemLocator")
set s = l.Open ("umi://nw01t1/ldap","nw01t1domnb\administrator","nw01t1domnb")
set c = CreateObject("WbemScripting.SWbemNamedValueSet")
c.Add "INCLUDE_OWNER", true
c.Add "INCLUDE_DACL", true
C.Add "INCLUDE_GROUP", true
set u = s.Get (".ou=AjayTest", 16384, c)
set sd = u.GetSecurityDescriptor_
|
<gh_stars>10-100
'This script shows how you can list all process names
set service = GetObject ("winmgmts:{impersonationLevel=Impersonate}")
for each Process in Service.InstancesOf ("Win32_Process")
WScript.Echo Process.Name
next
|
VERSION 5.00
Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0"; "MSCOMCTL.OCX"
Begin VB.Form frmKeywords
BorderStyle = 1 'Fixed Single
Caption = "Edit Keywords"
ClientHeight = 9390
ClientLeft = 0
ClientTop = 330
ClientWidth = 9495
LinkTopic = "Form1"
MaxButton = 0 'False
MinButton = 0 'False
ScaleHeight = 9390
ScaleWidth = 9495
Begin VB.Frame fraCreateModify
Caption = "Create new/Modify Keyword"
Height = 2175
Left = 4800
TabIndex = 4
Top = 240
Width = 4575
Begin VB.CommandButton cmdCancel
Caption = "Cancel"
Height = 375
Left = 1920
TabIndex = 7
Top = 1680
Width = 1215
End
Begin VB.CommandButton cmdCreateModify
Caption = "Create/Modify"
Height = 375
Left = 3240
TabIndex = 8
Top = 1680
Width = 1215
End
Begin VB.TextBox txtKeyword
Height = 285
Left = 120
TabIndex = 6
Tag = "1"
Top = 600
Width = 4335
End
Begin VB.Label lblKeyword
Caption = "Keyword:"
Height = 255
Left = 120
TabIndex = 5
Top = 360
Width = 735
End
End
Begin VB.CommandButton cmdClose
Caption = "Close"
Height = 375
Left = 8160
TabIndex = 22
Top = 8880
Width = 1215
End
Begin VB.ListBox lstAllKeywords
Height = 2010
Left = 120
Sorted = -1 'True
TabIndex = 1
Tag = "1"
Top = 360
Width = 4575
End
Begin VB.CommandButton cmdModify
Caption = "Modify"
Height = 375
Left = 3480
TabIndex = 3
Top = 2520
Width = 1215
End
Begin VB.CommandButton cmdDelete
Caption = "Delete"
Height = 375
Left = 2160
TabIndex = 2
Top = 2520
Width = 1215
End
Begin VB.Frame fraSelectedKeyword
Caption = "Selected Keyword"
Height = 5775
Left = 120
TabIndex = 9
Top = 3000
Width = 9255
Begin MSComctlLib.ListView lvwTitles
Height = 2415
Left = 120
TabIndex = 21
Tag = "1"
Top = 3240
Width = 9015
_ExtentX = 15901
_ExtentY = 4260
LabelWrap = -1 'True
HideSelection = -1 'True
_Version = 393217
ForeColor = -2147483640
BackColor = -2147483643
BorderStyle = 1
Appearance = 1
NumItems = 0
End
Begin VB.ListBox lstSynonymSetsForKeyword
Height = 1815
Left = 120
Sorted = -1 'True
TabIndex = 13
Tag = "1"
Top = 840
Width = 4455
End
Begin VB.ListBox lstKeywordsInSynonymSet
Height = 1815
Left = 4680
Sorted = -1 'True
TabIndex = 17
Tag = "1"
Top = 840
Width = 4455
End
Begin VB.Label lblKeywordsInSynonymSet3
Caption = "contains the following Keywords:"
Height = 255
Left = 4680
TabIndex = 16
Top = 600
Width = 4455
End
Begin VB.Label lblKeywordsInSynonymSet2
Caption = "<Synonym Set>"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 255
Left = 6000
TabIndex = 15
Tag = "1"
Top = 360
Width = 3135
End
Begin VB.Label lblSynonymSetsForKeyword3
Caption = "belongs to the following Synonym Sets:"
Height = 255
Left = 120
TabIndex = 12
Top = 600
Width = 4455
End
Begin VB.Label lblSynonymSetsForKeyword2
Caption = "<Keyword>"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 255
Left = 1200
TabIndex = 11
Tag = "1"
Top = 360
Width = 3255
End
Begin VB.Label lblTitles3
Caption = "is associated with the following Titles:"
Height = 255
Left = 120
TabIndex = 20
Top = 3000
Width = 4455
End
Begin VB.Label lblTitles2
Caption = "<Keyword>"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 255
Left = 1200
TabIndex = 19
Tag = "1"
Top = 2760
Width = 3255
End
Begin VB.Label lblTitles1
Caption = "The Keyword"
Height = 255
Left = 120
TabIndex = 18
Top = 2760
Width = 975
End
Begin VB.Label lblSynonymSetsForKeyword1
Caption = "The Keyword"
Height = 255
Left = 120
TabIndex = 10
Top = 360
Width = 975
End
Begin VB.Label lblKeywordsInSynonymSet1
Caption = "The Synonym Set"
Height = 255
Left = 4680
TabIndex = 14
Top = 360
Width = 1335
End
End
Begin VB.Label lblAllKeywords
Caption = "All Keywords:"
Height = 255
Left = 120
TabIndex = 0
Top = 120
Width = 1695
End
End
Attribute VB_Name = "frmKeywords"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Private p_clsKeywords As AuthDatabase.Keywords
Private p_clsSynonymSets As AuthDatabase.SynonymSets
Private p_clsTaxonomy As AuthDatabase.Taxonomy
Private p_rsTitlesForKeyword As ADODB.Recordset
Private p_blnModifying As Boolean
Private Const STR_DEFAULT_KEYWORD_C As String = "<Keyword>"
Private Const STR_DEFAULT_SYNONYM_SET_NAME_C As String = "<Synonym Set>"
Private Sub Form_Load()
On Error GoTo LErrorHandler
Set p_clsKeywords = g_AuthDatabase.Keywords
Set p_clsSynonymSets = g_AuthDatabase.SynonymSets
Set p_clsTaxonomy = g_AuthDatabase.Taxonomy
Set p_rsTitlesForKeyword = New ADODB.Recordset
cmdClose.Cancel = True
cmdCreateModify.Default = True
p_InitializeTitlesListView
p_UpdateAllKeywords
p_SetModeModifying False
p_SetToolTips
SetFontInternal Me
LEnd:
Exit Sub
LErrorHandler:
p_DisplayErrorMessage "Form_Load"
GoTo LEnd
End Sub
Private Sub Form_Unload(Cancel As Integer)
Set p_clsKeywords = Nothing
Set p_clsSynonymSets = Nothing
Set p_clsTaxonomy = Nothing
Set p_rsTitlesForKeyword = Nothing
Set frmKeywords = Nothing
End Sub
Private Sub lstAllKeywords_Click()
On Error GoTo LErrorHandler
p_UpdateSynonymSetsForKeyword
p_UpdateTitlesForKeyword
p_EnableDeleteModify
lblSynonymSetsForKeyword2.Caption = lstAllKeywords.Text
lblTitles2.Caption = lstAllKeywords.Text
LEnd:
Exit Sub
LErrorHandler:
p_DisplayErrorMessage "lstAllKeywords_Click"
GoTo LEnd
End Sub
Private Sub lstSynonymSetsForKeyword_Click()
On Error GoTo LErrorHandler
p_UpdateKeywordsInSynonymSet
lblKeywordsInSynonymSet2.Caption = lstSynonymSetsForKeyword.Text
LEnd:
Exit Sub
LErrorHandler:
p_DisplayErrorMessage "lstSynonymSetsForKeyword_Click"
GoTo LEnd
End Sub
Private Sub cmdDelete_Click()
Dim intKID As Long
On Error GoTo LErrorHandler
intKID = lstAllKeywords.ItemData(lstAllKeywords.ListIndex)
p_clsKeywords.Delete intKID
p_UpdateAllKeywords
LEnd:
Exit Sub
LErrorHandler:
p_DisplayErrorMessage "cmdDelete_Click"
GoTo LEnd
End Sub
Private Sub cmdModify_Click()
On Error GoTo LErrorHandler
p_DisableDeleteModify
txtKeyword = lstAllKeywords.Text
txtKeyword.SetFocus
p_SetModeModifying True
LEnd:
Exit Sub
LErrorHandler:
p_DisplayErrorMessage "cmdModify_Click"
GoTo LEnd
End Sub
Private Sub cmdCancel_Click()
On Error GoTo LErrorHandler
p_EnableDeleteModify
txtKeyword = ""
p_SetModeModifying False
LEnd:
Exit Sub
LErrorHandler:
p_DisplayErrorMessage "cmdCancel_Click"
GoTo LEnd
End Sub
Private Sub cmdCreateModify_Click()
On Error GoTo LErrorHandler
If (p_blnModifying) Then
p_Modify
Else
p_Create
End If
LEnd:
Exit Sub
LErrorHandler:
p_DisplayErrorMessage "cmdCreateModify_Click"
GoTo LEnd
End Sub
Private Sub cmdClose_Click()
Unload Me
End Sub
Private Sub p_InitializeTitlesListView()
With lvwTitles
.AllowColumnReorder = True
.FullRowSelect = True
.GridLines = True
.HideSelection = False
.LabelEdit = lvwManual
.View = lvwReport
.ColumnHeaders.Add , , "Title", 2500
.ColumnHeaders.Add , , "Description", 2500
.ColumnHeaders.Add , , "URI of the topic", 2500
End With
End Sub
Private Sub p_ClearAllKeywords()
lstAllKeywords.Clear
p_DisableDeleteModify
End Sub
Private Sub p_UpdateAllKeywords()
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
p_ClearAllKeywords
p_ClearSynonymSetsForKeyword
p_ClearKeywordsInSynonymSet
p_ClearTitles
p_clsKeywords.GetAllKeywordsRs rs
If (rs.RecordCount > 0) Then
rs.MoveFirst
End If
Do While (Not rs.EOF)
lstAllKeywords.AddItem rs("Keyword") & ""
lstAllKeywords.ItemData(lstAllKeywords.NewIndex) = rs("KID")
rs.MoveNext
Loop
If (lstAllKeywords.ListCount > 0) Then
' This simulates clicking the list box.
lstAllKeywords.ListIndex = 0
End If
End Sub
Private Sub p_ClearSynonymSetsForKeyword()
lblSynonymSetsForKeyword2.Caption = STR_DEFAULT_KEYWORD_C
lstSynonymSetsForKeyword.Clear
End Sub
Private Sub p_UpdateSynonymSetsForKeyword()
Dim intKID As Long
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
p_ClearSynonymSetsForKeyword
p_ClearKeywordsInSynonymSet
intKID = lstAllKeywords.ItemData(lstAllKeywords.ListIndex)
p_clsSynonymSets.GetSynonymSetsForKeyword intKID, rs
If (rs.RecordCount <> 0) Then
rs.MoveFirst
End If
Do While (Not rs.EOF)
lstSynonymSetsForKeyword.AddItem rs("Name") & ""
lstSynonymSetsForKeyword.ItemData(lstSynonymSetsForKeyword.NewIndex) = rs("EID")
rs.MoveNext
Loop
If (lstSynonymSetsForKeyword.ListCount > 0) Then
' This simulates clicking the list box.
lstSynonymSetsForKeyword.ListIndex = 0
End If
End Sub
Private Sub p_ClearKeywordsInSynonymSet()
lblKeywordsInSynonymSet2.Caption = STR_DEFAULT_SYNONYM_SET_NAME_C
lstKeywordsInSynonymSet.Clear
End Sub
Private Sub p_UpdateKeywordsInSynonymSet()
Dim rs As ADODB.Recordset
Dim intEID As Long
Set rs = New ADODB.Recordset
p_ClearKeywordsInSynonymSet
intEID = lstSynonymSetsForKeyword.ItemData(lstSynonymSetsForKeyword.ListIndex)
p_clsKeywords.GetKeywordsInSynonymSet intEID, rs
If (rs.RecordCount <> 0) Then
rs.MoveFirst
End If
Do While (Not rs.EOF)
lstKeywordsInSynonymSet.AddItem rs("Keyword") & ""
rs.MoveNext
Loop
End Sub
Private Sub p_ClearTitles()
lblTitles2.Caption = STR_DEFAULT_KEYWORD_C
Do While (lvwTitles.ListItems.Count <> 0)
lvwTitles.ListItems.Remove 1
Loop
End Sub
Private Sub p_UpdateTitlesForKeyword()
Dim intKID As Long
Dim intIndex As Long
Dim li As ListItem
p_ClearTitles
intKID = lstAllKeywords.ItemData(lstAllKeywords.ListIndex)
p_clsTaxonomy.GetTitlesForKeyword intKID, p_rsTitlesForKeyword
If (p_rsTitlesForKeyword.RecordCount <> 0) Then
p_rsTitlesForKeyword.MoveFirst
End If
Do While (Not p_rsTitlesForKeyword.EOF)
Set li = lvwTitles.ListItems.Add()
li.Text = p_rsTitlesForKeyword("ENUTitle") & ""
li.SubItems(1) = p_rsTitlesForKeyword("ENUDescription") & ""
li.SubItems(2) = p_rsTitlesForKeyword("ContentURI") & ""
p_rsTitlesForKeyword.MoveNext
Loop
End Sub
Private Sub p_DisableAllKeywords()
lstAllKeywords.Enabled = False
End Sub
Private Sub p_EnableAllKeywords()
lstAllKeywords.Enabled = True
End Sub
Private Sub p_DisableDeleteModify()
cmdDelete.Enabled = False
cmdModify.Enabled = False
End Sub
Private Sub p_EnableDeleteModify()
cmdDelete.Enabled = True
cmdModify.Enabled = True
End Sub
Private Sub p_NameCreate()
fraCreateModify.Caption = "Create new Keyword"
cmdCreateModify.Caption = "Create"
cmdCancel.Visible = False
End Sub
Private Sub p_NameModify()
fraCreateModify.Caption = "Modify Keyword"
cmdCreateModify.Caption = "Modify"
cmdCancel.Visible = True
End Sub
Private Sub p_SetModeModifying(i_bln As Boolean)
If (i_bln) Then
p_NameModify
p_blnModifying = True
p_DisableAllKeywords
Else
p_NameCreate
p_blnModifying = False
p_EnableAllKeywords
End If
End Sub
Private Sub p_DisplayErrorMessage( _
ByVal i_strFunction As String _
)
Select Case Err.Number
Case errContainsGarbageChar
MsgBox "The Keyword " & txtKeyword & " contains garbage characters.", _
vbExclamation + vbOKOnly
Case errContainsStopSign
MsgBox "The Keyword " & txtKeyword & " contains a Stop Sign.", _
vbExclamation + vbOKOnly
Case errContainsStopWord
MsgBox "The Keyword " & txtKeyword & " contains a Stop Word.", _
vbExclamation + vbOKOnly
Case errContainsOperatorShortcut
MsgBox "The Keyword " & txtKeyword & " contains an operator shortcut.", _
vbExclamation + vbOKOnly
Case errContainsVerbalOperator
MsgBox "The Keyword " & txtKeyword & " contains a verbal operator.", _
vbExclamation + vbOKOnly
Case errContainsQuote
MsgBox "The Keyword " & txtKeyword & " contains a quote.", _
vbExclamation + vbOKOnly
Case errAlreadyExists
MsgBox "A Keyword with the name " & txtKeyword & "already exists", _
vbExclamation + vbOKOnly
Case errTooLong
MsgBox "The Keyword " & txtKeyword & " is too long", _
vbExclamation + vbOKOnly
Case E_FAIL
DisplayDatabaseLockedError
Case errDatabaseVersionIncompatible
DisplayDatabaseVersionError
Case errNotPermittedForAuthoringGroup, errAuthoringGroupDiffers, _
errAuthoringGroupNotPresent
DisplayAuthoringGroupError
Case Else
g_ErrorInfo.SetInfoAndDump i_strFunction
End Select
End Sub
Private Sub p_Create()
Dim strKeyword As String
strKeyword = RemoveExtraSpaces(txtKeyword.Text)
If (strKeyword = "") Then
Exit Sub
End If
p_clsKeywords.Create strKeyword
p_UpdateAllKeywords
txtKeyword.Text = ""
txtKeyword.SetFocus
End Sub
Private Sub p_Modify()
Dim strKeyword As String
Dim intKID As Long
strKeyword = RemoveExtraSpaces(txtKeyword.Text)
If (strKeyword = "") Then
Exit Sub
End If
intKID = lstAllKeywords.ItemData(lstAllKeywords.ListIndex)
p_clsKeywords.Rename intKID, strKeyword
p_UpdateAllKeywords
p_SetModeModifying False
txtKeyword = ""
End Sub
Private Sub p_SetToolTips()
lblAllKeywords.ToolTipText = "This is a list of all keywords that have been " & _
"created for this database."
lstAllKeywords.ToolTipText = lblAllKeywords.ToolTipText
txtKeyword.ToolTipText = "Type in a new keyword to add to the list."
lblSynonymSetsForKeyword1.ToolTipText = "This is a list of all the synonym sets " & _
"that the selected keyword belongs to."
lblSynonymSetsForKeyword2.ToolTipText = lblSynonymSetsForKeyword1.ToolTipText
lblSynonymSetsForKeyword3.ToolTipText = lblSynonymSetsForKeyword1.ToolTipText
lstSynonymSetsForKeyword.ToolTipText = lblSynonymSetsForKeyword1.ToolTipText
lblKeywordsInSynonymSet1.ToolTipText = "This is a list of all the keywords " & _
"that the selected synonym set contains."
lblKeywordsInSynonymSet2.ToolTipText = lblKeywordsInSynonymSet1.ToolTipText
lblKeywordsInSynonymSet3.ToolTipText = lblKeywordsInSynonymSet1.ToolTipText
lstKeywordsInSynonymSet.ToolTipText = lblKeywordsInSynonymSet1.ToolTipText
lblTitles1.ToolTipText = "This is a table of the nodes or topics, " & _
"and their properties, that the selected keyword is already associated with."
lblTitles2.ToolTipText = lblTitles1.ToolTipText
lblTitles3.ToolTipText = lblTitles1.ToolTipText
lvwTitles.ToolTipText = lblTitles1.ToolTipText
End Sub
|
' Knapsack problem/0-1 - 13/02/2017
dim w(22),v(22),m(22)
data=array( "map", 9, 150, "compass", 13, 35, "water", 153, 200, _
"sandwich", 50, 160 , "glucose", 15, 60, "tin", 68, 45, _
"banana", 27, 60, "apple", 39, 40 , "cheese", 23, 30, "beer", 52, 10, _
"suntan cream", 11, 70, "camera", 32, 30 , "T-shirt", 24, 15, _
"trousers", 48, 10, "umbrella", 73, 40, "book", 30, 10 , _
"waterproof trousers", 42, 70, "waterproof overclothes", 43, 75 , _
"note-case", 22, 80, "sunglasses", 7, 20, "towel", 18, 12, "socks", 4, 50)
ww=400
xw=0:iw=0:iv=0
w(1)=iw:v(1)=iv
for i1=0 to 1:m(1)=i1:j=0
if i1=1 then
iw=w(1)+data(j*3+1):iv=v(1)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i1
if iw<=ww then
w(2)=iw: v(2)=iv
for i2=0 to 1:m(2)=i2:j=1
if i2=1 then
iw=w(2)+data(j*3+1):iv=v(2)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i2
if iw<=ww then
w(3)=iw: v(3)=iv
for i3=0 to 1:m(3)=i3:j=2
if i3=1 then
iw=w(3)+data(j*3+1):iv=v(3)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i3
if iw<=ww then
w(4)=iw: v(4)=iv
for i4=0 to 1:m(4)=i4:j=3
if i4=1 then
iw=w(4)+data(j*3+1):iv=v(4)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i4
if iw<=ww then
w(5)=iw: v(5)=iv
for i5=0 to 1:m(5)=i5:j=4
if i5=1 then
iw=w(5)+data(j*3+1):iv=v(5)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i5
if iw<=ww then
w(6)=iw: v(6)=iv
for i6=0 to 1:m(6)=i6:j=5
if i6=1 then
iw=w(6)+data(j*3+1):iv=v(6)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i6
if iw<=ww then
w(7)=iw: v(7)=iv
for i7=0 to 1:m(7)=i7:j=6
if i7=1 then
iw=w(7)+data(j*3+1):iv=v(7)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i7
if iw<=ww then
w(8)=iw: v(8)=iv
for i8=0 to 1:m(8)=i8:j=7
if i8=1 then
iw=w(8)+data(j*3+1):iv=v(8)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i8
if iw<=ww then
w(9)=iw: v(9)=iv
for i9=0 to 1:m(9)=i9:j=8
if i9=1 then
iw=w(9)+data(j*3+1):iv=v(9)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i9
if iw<=ww then
w(10)=iw: v(10)=iv
for i10=0 to 1:m(10)=i10:j=9
if i10=1 then
iw=w(10)+data(j*3+1):iv=v(10)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i10
if iw<=ww then
w(11)=iw: v(11)=iv
for i11=0 to 1:m(11)=i11:j=10
if i11=1 then
iw=w(11)+data(j*3+1):iv=v(11)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i11
if iw<=ww then
w(12)=iw: v(12)=iv
for i12=0 to 1:m(12)=i12:j=11
if i12=1 then
iw=w(12)+data(j*3+1):iv=v(12)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i12
if iw<=ww then
w(13)=iw: v(13)=iv
for i13=0 to 1:m(13)=i13:j=12
if i13=1 then
iw=w(13)+data(j*3+1):iv=v(13)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i13
if iw<=ww then
w(14)=iw: v(14)=iv
for i14=0 to 1:m(14)=i14:j=13
if i14=1 then
iw=w(14)+data(j*3+1):iv=v(14)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i14
if iw<=ww then
w(15)=iw: v(15)=iv
for i15=0 to 1:m(15)=i15:j=14
if i15=1 then
iw=w(15)+data(j*3+1):iv=v(15)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i15
if iw<=ww then
w(16)=iw: v(16)=iv
for i16=0 to 1:m(16)=i16:j=15
if i16=1 then
iw=w(16)+data(j*3+1):iv=v(16)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i16
if iw<=ww then
w(17)=iw: v(17)=iv
for i17=0 to 1:m(17)=i17:j=16
if i17=1 then
iw=w(17)+data(j*3+1):iv=v(17)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i17
if iw<=ww then
w(18)=iw: v(18)=iv
for i18=0 to 1:m(18)=i18:j=17
if i18=1 then
iw=w(18)+data(j*3+1):iv=v(18)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i18
if iw<=ww then
w(19)=iw: v(19)=iv
for i19=0 to 1:m(19)=i19:j=18
if i19=1 then
iw=w(19)+data(j*3+1):iv=v(19)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i19
if iw<=ww then
w(20)=iw: v(20)=iv
for i20=0 to 1:m(20)=i20:j=19
if i20=1 then
iw=w(20)+data(j*3+1):iv=v(20)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i20
if iw<=ww then
w(21)=iw: v(21)=iv
for i21=0 to 1:m(21)=i21:j=20
if i21=1 then
iw=w(21)+data(j*3+1):iv=v(21)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i21
if iw<=ww then
w(22)=iw: v(22)=iv
for i22=0 to 1:m(22)=i22:j=21
nn=nn+1
if i22=1 then
iw=w(22)+data(j*3+1):iv=v(22)+data(j*3+2)
if iv>xv and iw<=ww then xw=iw:xv=iv:l=m
end if 'i22
if iw<=ww then
end if 'i22
next:m(22)=0
end if 'i21
next:m(21)=0
end if 'i20
next:m(20)=0
end if 'i19
next:m(19)=0
end if 'i18
next:m(18)=0
end if 'i17
next:m(17)=0
end if 'i16
next:m(16)=0
end if 'i15
next:m(15)=0
end if 'i14
next:m(14)=0
end if 'i13
next:m(13)=0
end if 'i12
next:m(12)=0
end if 'i11
next:m(11)=0
end if 'i10
next:m(10)=0
end if 'i9
next:m(9)=0
end if 'i8
next:m(8)=0
end if 'i7
next:m(7)=0
end if 'i6
next:m(6)=0
end if 'i5
next:m(5)=0
end if 'i4
next:m(4)=0
end if 'i3
next:m(3)=0
end if 'i2
next:m(2)=0
end if 'i1
next:m(1)=0
for i=1 to 22
if l(i)=1 then wlist=wlist&vbCrlf&data((i-1)*3)
next
Msgbox mid(wlist,3)&vbCrlf&vbCrlf&"weight="&xw&vbCrlf&"value="&xv,,"Knapsack - nn="&nn
|
<reponame>npocmaka/Windows-Server-2003<filename>admin/activec/designer/samples/drivestats/frmchoosedrive.frm<gh_stars>10-100
VERSION 5.00
Begin VB.Form frmChooseDrive
Caption = "Form1"
ClientHeight = 2850
ClientLeft = 60
ClientTop = 345
ClientWidth = 2100
LinkTopic = "Form1"
ScaleHeight = 2850
ScaleWidth = 2100
StartUpPosition = 2 'CenterScreen
Begin VB.CommandButton btnCancel
Cancel = -1 'True
Caption = "Cancel"
Height = 375
Left = 1103
TabIndex = 3
Top = 2280
Width = 855
End
Begin VB.CommandButton btnOK
Caption = "OK"
Default = -1 'True
Height = 375
Left = 143
TabIndex = 2
Top = 2280
Width = 735
End
Begin VB.ListBox lbDrives
Height = 1815
Left = 1320
TabIndex = 1
Top = 240
Width = 495
End
Begin VB.Label Label1
Caption = "Choose a drive:"
Height = 375
Left = 240
TabIndex = 0
Top = 240
Width = 855
End
End
Attribute VB_Name = "frmChooseDrive"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Dim m_DriveNames() As String
Dim m_DriveChosen As Integer
Dim m_fOK As Boolean
Public Sub SetDriveNames(ByRef Names() As String, ByVal Selected As Integer)
Dim i As Integer
m_DriveNames = Names
For i = LBound(m_DriveNames) To UBound(m_DriveNames)
lbDrives.AddItem m_DriveNames(i)
Next i
lbDrives.ListIndex = Selected - 1
End Sub
Public Property Get OK() As Boolean
OK = m_fOK
End Property
Private Sub btnCancel_Click()
m_fOK = False
Me.Hide
End Sub
Private Sub btnOK_Click()
m_fOK = True
m_DriveChosen = lbDrives.ListIndex + 1
Me.Hide
End Sub
Private Sub Form_Activate()
m_fOK = False
End Sub
Public Property Get DriveChosen() As Integer
DriveChosen = m_DriveChosen
End Property
Private Sub lbDrives_DblClick()
btnOK_Click
End Sub
|
'''''''''''''''''''''''''''''''''''''''''''''
'
' IWAM account synchronization utility
'
'''''''''''''''''''''''''''''''''''''''''''''
' Description:
' ------------
' This admin script allows you to update the launching identity of
' all IIS COM+ application packages that run out of process.
'
' There are certain operations that may cause the IWAM account, which
' is the identity under which out of process IIS applications run, to
' become out of sync between the COM+ data store and IIS or the SAM.
' On IIS startup the account information stored in the IIS Metabase
' is synchronized with the local SAM, but the COM+ applications will
' not automatically be updated. The result of this is that requests
' to out of process applications will fail.
'
' When this happens, the following events are written to the system
' event log:
'
' Event ID: 10004 Source: DCOM
' DCOM got error "Logon failure: unknown user name or bad password. "
' and was unable to logon .\IWAM_MYSERVER in order to run the server:
' {1FD7A201-0823-479C-9A4B-2C6128585168}
'
' Event ID: 36 Source: W3SVC
' The server failed to load application '/LM/W3SVC/1/Root/op'.
' The error was 'The server process could not be started because
' the configured identity is incorrect. Check the username and password.
'
' Running this utility will update the COM+ applications with the
' correct identity.
'
' To Run:
' -------
' This is the format for this script:
'
' cscript synciwam.vbs [-v|-h]
' -v verbose: print a trace of the scripts activity
' -h help: print script usage
'
' NOTE: If you want to execute this script directly from Windows, use
' 'wscript' instead of 'cscript'.
'
'''''''''''''''''''''''''''''''''''''''''''''
' Initialize error checking
On Error Resume Next
Const APP_ISOLATED = 1
Const APP_OOP_POOL_ID = "{3D14228D-FBE1-11d0-995D-00C04FD919C1}"
Const IIS_ANY_PROPERTY = 0
Dim WebServiceObj, WamUserName, WamUserPass
Dim ComCatalogObj, ComAppCollectionObj, ComApplication
Dim AppIdArray, AppIdArraySize, AppIdArrayElements
Dim IISAppPathArray, IISAppObj, IISAppPath
Dim TraceEnabled
' Get command line parameters
TraceEnabled = False
if Wscript.Arguments.Count > 0 then
select case WScript.Arguments(0)
case "-h", "-?", "/?":
PrintUsage
case "-v", "/v":
TraceEnabled = True
case else
PrintUsage
end select
end if
' Get a reference to the web service object
set WebServiceObj = GetObject("IIS://LocalHost/w3svc")
QuitOnError()
' Save the wam user name and password
WamUserName = WebServiceObj.WAMUserName
WamUserPass = WebServiceObj.WAMUserPass
QuitOnError()
' Assume that a blank password or user is an error
if WamUserName = "" or WamUserPass = "" then
WScript.Echo "Error: Empty user name or password."
WScript.Quit(1)
end if
' The com+ packages that we want to set are those that run in external
' processes. These include the process pool application and any isolated
' applications defined for this server.
IISAppPathArray = WebServiceObj.GetDataPaths( "AppIsolated", IIS_ANY_PROPERTY )
QuitOnError()
AppIdArraySize = UBound(IISAppPathArray) + 1
Redim AppIdArray( AppIdArraySize )
' Set the id for the pooled application
AppIdArrayElements = 0
AppIdArray(AppIdArrayElements) = APP_OOP_POOL_ID
AppIdArrayElements = AppIdArrayElements + 1
' Get the ids for all isolated applications
Trace "IIS Applications Defined: "
Trace "Name, AppIsolated, Package ID"
for each IISAppPath in IISAppPathArray
set IISAppObj = GetObject( IISAppPath )
Trace IISAppObj.Name & ", " & CStr(IISAppObj.AppIsolated) & ", " & CStr(IISAppObj.AppPackageID)
if APP_ISOLATED = IISAppObj.AppIsolated And IISAppObj.AppPackageID <> "" then
AppIdArray(AppIdArrayElements) = IISAppObj.AppPackageID
AppIdArrayElements = AppIdArrayElements + 1
end if
set IISAppObj = Nothing
next
Trace ""
' Readjust the size of the id array. The size is initially set
' larger than it needs to be. So we will reduce it so com+ does
' not have to do more work than necessary
Redim Preserve AppIdArray(AppIdArrayElements)
' Dump the array of application ids
if TraceEnabled then
WScript.Echo "Out of process applications defined: "
WScript.Echo "Count: " & CStr(AppIdArrayElements)
for i = 0 to AppIdArrayElements - 1
WScript.Echo AppIdArray(i)
next
WScript.Echo ""
end if
' Init com admin objects
set ComCatalogObj = CreateObject( "COMAdmin.COMAdminCatalog" )
QuitOnError()
set ComAppCollectionObj = ComCatalogObj.GetCollection( "Applications" )
QuitOnError()
ComAppCollectionObj.PopulateByKey( AppIdArray )
QuitOnError()
' Update the com applications
Trace "Updating Applications: "
for each ComApplication in ComAppCollectionObj
Trace "Name: " & ComApplication.Name & " Key: " & CStr(ComApplication.Key)
ReportErrorAndContinue()
ComApplication.Value("Identity") = WamUserName
ReportErrorAndContinue()
ComApplication.Value("Password") = <PASSWORD>
ReportErrorAndContinue()
next
ComAppCollectionObj.SaveChanges
QuitOnError()
'''''''''''''''''''''''''''''''''''''''''''''
' Helper functions
'
sub QuitOnError()
if err <> 0 then
WScript.Echo "Error: " & Hex(err) & ": " & err.description
Wscript.Quit(1)
end if
end sub
sub ReportErrorAndContinue()
if err <> 0 then
WScript.Echo "Error: " & Hex(err) & ": " & err.description
err.Clear
end if
end sub
sub Trace( str )
if TraceEnabled then
WScript.Echo CStr(str)
end if
end sub
sub PrintUsage()
Wscript.Echo "Usage: cscript synciwam.vbs [-v|-h]"
Wscript.Echo vbTab & "-v verbose: trace execution of the script"
Wscript.Echo vbTab & "-h help: print this message"
WScript.Quit(0)
end sub
|
<reponame>LaudateCorpus1/RosettaCodeData<gh_stars>1-10
dim t()
if Wscript.arguments.count=1 then
n=Wscript.arguments.item(0)
else
n=15
end if
redim t(n+1)
't(*)=0
t(1)=1
for i=1 to n
ip=i+1
for j = i to 1 step -1
t(j)=t(j)+t(j-1)
next 'j
t(i+1)=t(i)
for j = i+1 to 1 step -1
t(j)=t(j)+t(j-1)
next 'j
Wscript.echo t(i+1)-t(i)
next 'i
|
Public Sub testBinarySearch(n)
Dim a(1 To 100)
'create an array with values = multiples of 10
For i = 1 To 100: a(i) = i * 10: Next
Debug.Print BinarySearch(a, n, LBound(a), UBound(a))
End Sub
Public Sub stringtestBinarySearch(w)
'uses BinarySearch with a string array
Dim a
a = Array("AA", "Maestro", "Mario", "Master", "Mattress", "Mister", "Mistress", "ZZ")
Debug.Print BinarySearch(a, w, LBound(a), UBound(a))
End Sub
|
<filename>trunk/SaltyUtility/FONT/pack.bas
Attribute VB_Name = "Module1"
Option Explicit
Dim FontName() As String
Dim FontWidth() As Integer
Dim FontHeight() As Integer
Dim FontSize() As Integer
Dim AscLBound() As Integer
Dim AscUBound() As Integer
Dim Flag() As String
Private Sub GetList(ListFileName As String)
Dim lst As String
Dim lstb() As Byte
ReDim lstb(FileLen(ListFileName) - 1)
Open ListFileName For Binary Access Read As #1
Get #1, , lstb()
Close #1
lst = StrConv(lstb(), vbUnicode)
Dim LineStr() As String
LineStr() = Split(lst, vbCrLf)
ReDim FontName(UBound(LineStr()))
ReDim FontWidth(UBound(LineStr()))
ReDim FontHeight(UBound(LineStr()))
ReDim FontSize(UBound(LineStr()))
ReDim AscLBound(UBound(LineStr()))
ReDim AscUBound(UBound(LineStr()))
ReDim Flag(UBound(LineStr()))
Dim i As Long
For i = 0 To UBound(LineStr())
Dim ss() As String
ss() = Split(LineStr(i), ";")
FontName(i) = ss(0)
FontWidth(i) = ss(1)
FontHeight(i) = ss(2)
FontSize(i) = ss(3)
AscLBound(i) = ss(4)
AscUBound(i) = ss(5)
Flag(i) = ss(6)
Next i
End Sub
Private Sub StartWritePackFile(FileName As String)
On Error Resume Next
Kill FileName
On Error GoTo 0
Open FileName For Binary Access Write As #1
End Sub
Private Sub WritePackHeader()
Put #1, , CLng(UBound(FontName()) + 1)
Dim HeaderLength As Long
HeaderLength = 4 + (UBound(FontName()) + 1) * 28
Dim i As Long
Dim length As Long
length = HeaderLength
For i = 0 To UBound(FontName())
Dim BS() As Byte
BS() = StrConv(FontName(i), vbFromUnicode)
ReDim Preserve BS(7)
Put #1, , BS()
Put #1, , FontWidth(i)
Put #1, , FontHeight(i)
Put #1, , FontSize(i)
Put #1, , AscLBound(i)
Put #1, , AscUBound(i)
Select Case Flag(i)
Case "E"
Put #1, , CInt(&H40)
Case "ET"
Put #1, , CInt(&HC0)
Case "C"
Put #1, , CInt(&H41)
Case "CT"
Put #1, , CInt(&HC1)
Case Else
MsgBox "Error flag", vbCritical
End
End Select
Dim curlen As Long
curlen = FileLen(FontName(i))
Put #1, , length
length = length + curlen
Put #1, , length
Next i
End Sub
Private Sub WritePackFileData()
Dim i As Long
For i = 0 To UBound(FontName())
Dim buf() As Byte
ReDim buf(FileLen(FontName(i)) - 1)
Open FontName(i) For Binary Access Read As #2
Get #2, , buf()
Close #2
Put #1, , buf()
Next i
End Sub
Private Sub EndWritePackFile()
Close #1
End Sub
Sub Main()
ChDrive "F:\WorkDir\EleProjects\SaltyProject\SaltyUtility\FONT"
ChDir "F:\WorkDir\EleProjects\SaltyProject\SaltyUtility\FONT"
GetList "fonts.txt"
StartWritePackFile "Pack.bin"
WritePackHeader
WritePackFileData
EndWritePackFile
MsgBox "done"
End Sub
|
Option Explicit
Sub Main()
Dim temp$, T() As Long, i&
'Fibonacci:
T = Fibonacci_Step(1, 15, 1)
For i = LBound(T) To UBound(T)
temp = temp & ", " & T(i)
Next
Debug.Print "Fibonacci: " & Mid(temp, 3)
temp = ""
'Tribonacci:
T = Fibonacci_Step(1, 15, 2)
For i = LBound(T) To UBound(T)
temp = temp & ", " & T(i)
Next
Debug.Print "Tribonacci: " & Mid(temp, 3)
temp = ""
'Tetranacci:
T = Fibonacci_Step(1, 15, 3)
For i = LBound(T) To UBound(T)
temp = temp & ", " & T(i)
Next
Debug.Print "Tetranacci: " & Mid(temp, 3)
temp = ""
'Lucas:
T = Fibonacci_Step(1, 15, 1, 2)
For i = LBound(T) To UBound(T)
temp = temp & ", " & T(i)
Next
Debug.Print "Lucas: " & Mid(temp, 3)
temp = ""
End Sub
Private Function Fibonacci_Step(First As Long, Count As Long, S As Long, Optional Second As Long) As Long()
Dim T() As Long, R() As Long, i As Long, Su As Long, C As Long
If Second <> 0 Then S = 1
ReDim T(1 - S To Count)
For i = LBound(T) To 0
T(i) = 0
Next i
T(1) = IIf(Second <> 0, Second, 1)
T(2) = 1
For i = 3 To Count
Su = 0
C = S + 1
Do While C >= 0
Su = Su + T(i - C)
C = C - 1
Loop
T(i) = Su
Next
ReDim R(1 To Count)
For i = 1 To Count
R(i) = T(i)
Next
Fibonacci_Step = R
End Function
|
If condition Then statement
If condition Then statement Else statement
|
<gh_stars>10-100
'********************************************************************
'*
'* File: ExtensionsTest.VBS
'* Created: March 2000
'*
'* Main Function: Adds snapins, enumerates extensions, enables
'* disables the extension snapins.
'* Usage: ExtensionTest.VBS
'*
'* Copyright (C) 2000 Microsoft Corporation
'*
'********************************************************************
OPTION EXPLICIT
'Define constants
'Declare variables
Dim mmc
Dim doc
Dim snapins
Dim Services
Dim ServicesExtensions
Dim ServicesExtension
Dim Compmgmt
Dim CompmgmtExtensions
Dim CompmgmtExtension
Dim message
Dim intRet
'get the various objects we'll need
Set mmc = wscript.CreateObject("MMC20.Application")
Set doc = mmc.Document
Set snapins = doc.snapins
'add services & compmgmt snapins
Set Services = snapins.Add("{58221c66-ea27-11cf-adcf-00aa00a80033}") ' Services snapin
Set Compmgmt = snapins.Add("{58221C67-EA27-11CF-ADCF-00AA00A80033}") ' Compmgmt snapin
EnumerateExtensions(Services)
EnumerateExtensions(Compmgmt)
DisableAnExtension Services, "Send"
Services.EnableAllExtensions(1)
message = "Please verify all extensions of " & Services.Name & "are enabled."
intRet = MsgBox(message, vbInformation, "Verify test")
' Now remove Services & try to disable the extension
RemoveSnapinAndEnableExtension Services, "Send"
Set mmc = Nothing
'********************************************************************
'*
'* Sub Welcome
'*
'********************************************************************
Sub Welcome()
Dim intDoIt
intDoIt = MsgBox(L_Welcome_MsgBox_Message_Text, _
vbOKCancel + vbInformation, _
L_Welcome_MsgBox_Title_Text )
If intDoIt = vbCancel Then
WScript.Quit
End If
End Sub
'********************************************************************
'*
'* Sub EnumerateExtensions(objSnapin)
'* Purpose: Enumberates the extensions of the given snapin.
'* Input: objSnapin given snapin.
'*
'* Output: Results of the enumeration are either printed on screen or saved in strOutputFile.
'*
'********************************************************************
Sub EnumerateExtensions(objSnapin)
ON ERROR RESUME NEXT
Dim Extensions
Dim Extension
Dim SnapinName
Dim ExtensionNames
Dim count
Dim OtherData
Set Extensions = objSnapin.Extensions
count = Extensions.Count
If count > 0 Then
SnapinName = objSnapin.Name
OtherData = "Vendor : " + objSnapin.Vendor
OtherData = OtherData + ", Version : " + objSnapin.Version
OtherData = OtherData + ", CLSID : " + objSnapin.SnapinCLSID
intRet = MsgBox(OtherData, vbInformation, "About Information for " & SnapinName)
For Each Extension in Extensions
ExtensionNames = ExtensionNames + Extension.Name
ExtensionNames = ExtensionNames + ","
EnumerateExtensions(Extension)
Next
ExtensionNames = ExtensionNames + "."
intRet = MsgBox(ExtensionNames, vbInformation, "Extensions for " & SnapinName)
End If
End Sub
'********************************************************************
'*
'* Function FindExtension(objSnapin,strExtension)
'* Purpose: Finds an extension for given primary snapin with given name.
'* Input: objSnapin given snapin.
'* strExtension given extension name.
'*
'* Output: returns true if extension exists. objExtension carries the returned object.
'*
'********************************************************************
Function FindExtension(objSnapin, strExtension, objExtension)
Dim Extensions
Dim Extension
Set Extensions = objSnapin.Extensions
For Each objExtension in Extensions
If InStr(objExtension.Name, strExtension) Then
FindExtension = true
Exit Function
End If
Next
FindExtension = false
End Function
'********************************************************************
'*
'* Sub DisableAnExtension(objSnapin, strExtensionName)
'* Purpose: Disables and extension of objSnapin with given name.
'* Input: objSnapin given snapin.
'*
'* Output: Verify if the snapis is disabled.
'*
'********************************************************************
Sub DisableAnExtension(objSnapin, strExtensionName)
Dim Extension
If FindExtension(objSnapin, strExtensionName, Extension) Then
ObjSnapin.EnableAllExtensions(0)
Extension.Enable(0)
message = "Please verify disabling of " & Extension.Name & " extension of " & objSnapin.Name & "."
intRet = MsgBox(message, vbInformation, "Verify test")
Else
message = "Extension for " & objSnapin.Name & " with name " & strExtensionName & " does not exist."
intRet = MsgBox(message, vbInformation, "Verify test")
End If
End Sub
'********************************************************************
'*
'* Sub RemoveSnapinAndEnableExtension(objSnapin, strExtensionName)
'* Purpose: Finds the extension with given name, removes primary &
'* accesses extension. This will fail as primary is gone.
'* Input: objSnapin given snapin.
'*
'* Output: Verify error message is returned on enabling.
'*
'********************************************************************
Sub RemoveSnapinAndEnableExtension(objSnapin, strExtensionName)
ON ERROR RESUME NEXT
Dim Extension
If FindExtension(objSnapin, strExtensionName, Extension) Then
snapins.Remove objSnapin
Extension.Enable(1)
MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description
Err.clear
Else
message = "Extension for " & objSnapin.Name & " with name " & strExtensionName & " does not exist."
intRet = MsgBox(message, vbInformation, "Verify test")
End If
End Sub
|
Sub String_Clone_Copy()
Dim A As String, B$
A = "Hello world!"
'cloning :
B = A
End Sub
|
items = Array("Apple", "Orange", "Banana")
For Each x In items
WScript.Echo x
Next
|
<reponame>npocmaka/Windows-Server-2003<gh_stars>10-100
VERSION 5.00
Begin VB.Form NewFaxDialog
Caption = "New Fax Document"
ClientHeight = 2520
ClientLeft = 6300
ClientTop = 5352
ClientWidth = 6048
LinkTopic = "Form1"
ScaleHeight = 2520
ScaleWidth = 6048
Begin VB.CommandButton Cancel
Caption = "Cancel"
Height = 495
Left = 2880
TabIndex = 3
Top = 1320
Width = 1455
End
Begin VB.CommandButton OK
Caption = "OK"
Height = 495
Left = 600
TabIndex = 2
Top = 1320
Width = 1455
End
Begin VB.TextBox FileName
Height = 375
Left = 2160
TabIndex = 0
Top = 360
Width = 3615
End
Begin VB.Label Label1
Caption = "Enter a Document Name:"
Height = 375
Left = 120
TabIndex = 1
Top = 360
Width = 2055
End
End
Attribute VB_Name = "NewFaxDialog"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Private Sub Cancel_Click()
Unload NewFaxDialog
End Sub
Private Sub Form_Load()
End Sub
Private Sub OK_Click()
If FileName.Text = "" Then
msg = "You must specify a document name"
MsgBox msg, , "Error"
FileName.SetFocus
Exit Sub
End If
Err.Clear
Set FaxDocument = FAX.CreateDocument(FileName.Text)
If Err.Number <> 0 Then
msg = "Could not create new document"
MsgBox msg, , "Error"
Unload NewFaxDialog
Doc = False
Else
Unload NewFaxDialog
Doc = True
End If
End Sub
|
<gh_stars>10-100
VERSION 5.00
Object = "{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0"; "MSCOMCTL.OCX"
Object = "{BDC217C8-ED16-11CD-956C-0000C04E4C0A}#1.1#0"; "TABCTL32.OCX"
Begin VB.Form frmImporter
Caption = "Importer"
ClientHeight = 8955
ClientLeft = 105
ClientTop = 390
ClientWidth = 7710
LinkTopic = "Form1"
ScaleHeight = 8955
ScaleWidth = 7710
Begin VB.Frame fraHelp
Caption = "Help file directory"
Height = 1575
Left = 120
TabIndex = 16
Top = 7320
Width = 4935
Begin VB.OptionButton optHelp
Caption = "%windir%\help (using hcp://)"
Height = 255
Index = 1
Left = 120
TabIndex = 22
Top = 480
Width = 2415
End
Begin VB.TextBox txtSubDir
Height = 285
Left = 1200
TabIndex = 21
Tag = "1"
Top = 1200
Width = 3615
End
Begin VB.OptionButton optHelp
Caption = "%windir%\pchealth\helpctr\vendors\<vendor>"
Height = 255
Index = 3
Left = 120
TabIndex = 19
Top = 960
Width = 3615
End
Begin VB.OptionButton optHelp
Caption = "%windir%\pchealth\helpctr\system"
Height = 255
Index = 2
Left = 120
TabIndex = 18
Top = 720
Width = 2775
End
Begin VB.OptionButton optHelp
Caption = "%windir%\help (using MS-ITS)"
Height = 255
Index = 0
Left = 120
TabIndex = 17
Top = 240
Width = 2415
End
Begin VB.Label lblSubDir
Caption = "Sub directory:"
Height = 255
Left = 120
TabIndex = 20
Top = 1200
Width = 975
End
End
Begin VB.Frame fraSKU
Caption = "SKU"
Height = 1575
Left = 120
TabIndex = 4
Top = 5640
Width = 4935
Begin VB.CheckBox chkSKU
Caption = "32-bit P&ersonal"
Height = 255
Index = 1
Left = 120
TabIndex = 6
Top = 480
Width = 2055
End
Begin VB.CheckBox chkSKU
Caption = "32-bit &Professional"
Height = 255
Index = 2
Left = 120
TabIndex = 7
Top = 720
Width = 2055
End
Begin VB.CheckBox chkSKU
Caption = "32-bit &Server"
Height = 255
Index = 4
Left = 2640
TabIndex = 9
Top = 240
Width = 2055
End
Begin VB.CheckBox chkSKU
Caption = "32-bit &Advanced Server"
Height = 255
Index = 5
Left = 2640
TabIndex = 10
Top = 480
Width = 2055
End
Begin VB.CheckBox chkSKU
Caption = "32-bit Data¢er Server"
Height = 255
Index = 7
Left = 2640
TabIndex = 12
Top = 960
Width = 2055
End
Begin VB.CheckBox chkSKU
Caption = "64-bit Pro&fessional"
Height = 255
Index = 3
Left = 120
TabIndex = 8
Top = 960
Width = 2055
End
Begin VB.CheckBox chkSKU
Caption = "64-bit Ad&vanced Server"
Height = 255
Index = 6
Left = 2640
TabIndex = 11
Top = 720
Width = 2055
End
Begin VB.CheckBox chkSKU
Caption = "64-bit Datac&enter Server"
Height = 255
Index = 8
Left = 2640
TabIndex = 13
Top = 1200
Width = 2055
End
Begin VB.CheckBox chkSKU
Caption = "Windows &Me"
Height = 255
Index = 0
Left = 120
TabIndex = 5
Top = 240
Width = 2055
End
End
Begin VB.CommandButton cmdClose
Caption = "Close"
Height = 375
Left = 6360
TabIndex = 14
Top = 8520
Width = 1215
End
Begin TabDlg.SSTab SSTab
Height = 5415
Left = 120
TabIndex = 0
Top = 120
Width = 7485
_ExtentX = 13203
_ExtentY = 9551
_Version = 393216
Tabs = 4
TabsPerRow = 4
TabHeight = 520
TabCaption(0) = "Table of Contents"
TabPicture(0) = "frmImporter.frx":0000
Tab(0).ControlEnabled= -1 'True
Tab(0).Control(0)= "tre(0)"
Tab(0).Control(0).Enabled= 0 'False
Tab(0).Control(1)= "ilsIcons"
Tab(0).Control(1).Enabled= 0 'False
Tab(0).ControlCount= 2
TabCaption(1) = "Index"
TabPicture(1) = "frmImporter.frx":001C
Tab(1).ControlEnabled= 0 'False
Tab(1).Control(0)= "tre(1)"
Tab(1).ControlCount= 1
TabCaption(2) = "HTM"
TabPicture(2) = "frmImporter.frx":0038
Tab(2).ControlEnabled= 0 'False
Tab(2).Control(0)= "tre(2)"
Tab(2).ControlCount= 1
TabCaption(3) = "Spreadsheet"
TabPicture(3) = "frmImporter.frx":0054
Tab(3).ControlEnabled= 0 'False
Tab(3).Control(0)= "tre(3)"
Tab(3).ControlCount= 1
Begin MSComctlLib.TreeView tre
Height = 4575
Index = 2
Left = -74880
TabIndex = 3
Tag = "1"
Top = 720
Width = 7215
_ExtentX = 12726
_ExtentY = 8070
_Version = 393217
Indentation = 529
Style = 7
Appearance = 1
OLEDropMode = 1
End
Begin MSComctlLib.TreeView tre
Height = 4575
Index = 1
Left = -74880
TabIndex = 2
Tag = "1"
Top = 720
Width = 7215
_ExtentX = 12726
_ExtentY = 8070
_Version = 393217
Indentation = 529
Style = 7
Appearance = 1
OLEDropMode = 1
End
Begin MSComctlLib.ImageList ilsIcons
Left = 6720
Top = 4920
_ExtentX = 1005
_ExtentY = 1005
BackColor = -2147483643
ImageWidth = 16
ImageHeight = 16
MaskColor = 16776960
_Version = 393216
BeginProperty Images {2C247F25-8591-11D1-B16A-00C0F0283628}
NumListImages = 4
BeginProperty ListImage1 {2C247F27-8591-11D1-B16A-00C0F0283628}
Picture = "frmImporter.frx":0070
Key = ""
EndProperty
BeginProperty ListImage2 {2C247F27-8591-11D1-B16A-00C0F0283628}
Picture = "frmImporter.frx":0182
Key = ""
EndProperty
BeginProperty ListImage3 {2C247F27-8591-11D1-B16A-00C0F0283628}
Picture = "frmImporter.frx":0294
Key = ""
EndProperty
BeginProperty ListImage4 {2C247F27-8591-11D1-B16A-00C0F0283628}
Picture = "frmImporter.frx":03A6
Key = ""
EndProperty
EndProperty
End
Begin MSComctlLib.TreeView tre
Height = 4575
Index = 0
Left = 120
TabIndex = 1
Tag = "1"
Top = 720
Width = 7215
_ExtentX = 12726
_ExtentY = 8070
_Version = 393217
Indentation = 529
Style = 7
Appearance = 1
OLEDropMode = 1
End
Begin MSComctlLib.TreeView tre
Height = 4575
Index = 3
Left = -74880
TabIndex = 15
Tag = "1"
Top = 720
Width = 7215
_ExtentX = 12726
_ExtentY = 8070
_Version = 393217
Indentation = 529
Style = 7
Appearance = 1
OLEDropMode = 1
End
End
End
Attribute VB_Name = "frmImporter"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Private WithEvents p_clsImporter As AuthDatabase.Importer
Attribute p_clsImporter.VB_VarHelpID = -1
Private p_dictURIs As Scripting.Dictionary
Private p_clsSizer As Sizer
Private p_strMissingFiles As String
Private p_strCorruptFiles As String
Private Const ROOT_KEY_C As String = "Root"
Private Enum IMAGE_E
IMAGE_LEAF_E = 1
IMAGE_GROUP_E = 2
IMAGE_BAD_LEAF_E = 3
IMAGE_BAD_GROUP_E = 4
End Enum
Private Enum TREEVIEW_INDEX_E
TI_HHC_E = 0
TI_HHK_E = 1
TI_HTM_E = 2
TI_XLS_E = 3
End Enum
Private Enum HELPDIR_INDEX_E
HDI_HELP_MSITS_E = 0
HDI_HELP_HCP_E = 1
HDI_SYSTEM_E = 2
HDI_VENDOR_E = 3
End Enum
Private Const MAX_TREEVIEW_INDEX_C As Long = 3
Private Enum SKU_INDEX_E
SI_WINDOWS_MILLENNIUM_E = 0
SI_STANDARD_E = 1
SI_PROFESSIONAL_E = 2
SI_PROFESSIONAL_64_E = 3
SI_SERVER_E = 4
SI_ADVANCED_SERVER_E = 5
SI_ADVANCED_SERVER_64_E = 6
SI_DATA_CENTER_SERVER_E = 7
SI_DATA_CENTER_SERVER_64_E = 8
End Enum
Private Sub Form_Load()
On Error GoTo LErrorHandler
Dim Node As Node
Dim HHKDomDoc As MSXML2.DOMDocument
Dim HHKDomNode As MSXML2.IXMLDOMNode
Dim Element As MSXML2.IXMLDOMElement
Dim intIndex As Long
Dim clsTaxonomy As AuthDatabase.Taxonomy
Set p_clsImporter = g_AuthDatabase.Importer
Set p_dictURIs = New Scripting.Dictionary
p_dictURIs.CompareMode = TextCompare
Set p_clsSizer = New Sizer
cmdClose.Cancel = True
optHelp(HDI_HELP_MSITS_E).Value = True
For intIndex = 0 To MAX_TREEVIEW_INDEX_C
tre(intIndex).LabelEdit = tvwManual
tre(intIndex).HideSelection = False
Set tre(intIndex).ImageList = ilsIcons
Set Node = tre(intIndex).Nodes.Add(Key:=ROOT_KEY_C, Text:=ROOT_KEY_C)
Node.Expanded = True
Node.Image = IMAGE_GROUP_E
Next
Set HHKDomDoc = New MSXML2.DOMDocument
Set Element = HHKDomDoc.createElement(HHT_TAXONOMY_ENTRIES_C)
Set HHKDomNode = HHKDomDoc.appendChild(Element)
Set tre(TI_HHK_E).Nodes(ROOT_KEY_C).Tag = HHKDomNode
Set clsTaxonomy = g_AuthDatabase.Taxonomy
clsTaxonomy.GetURIs p_dictURIs
p_SetToolTips
SetFontInternal Me
LEnd:
Exit Sub
LErrorHandler:
g_ErrorInfo.SetInfoAndDump "Form_Load"
GoTo LEnd
End Sub
Private Sub Form_Unload(Cancel As Integer)
Set p_clsImporter = Nothing
Set p_dictURIs = Nothing
Set p_clsSizer = Nothing
Set frmImporter = Nothing
End Sub
Private Sub Form_Activate()
On Error GoTo LErrorHandler
p_SetSizingInfo
Exit Sub
LErrorHandler:
g_ErrorInfo.SetInfoAndDump "Form_Activate"
End Sub
Private Sub Form_Resize()
On Error GoTo LErrorHandler
p_clsSizer.Resize
Exit Sub
LErrorHandler:
g_ErrorInfo.SetInfoAndDump "Form_Resize"
End Sub
Private Sub p_clsImporter_CorruptFile(ByVal strFileName As String)
p_strCorruptFiles = p_strCorruptFiles & strFileName & " "
End Sub
Private Sub p_clsImporter_MissingFile(ByVal strFileName As String)
p_strMissingFiles = p_strMissingFiles & strFileName & " "
End Sub
Private Sub tre_OLEDragDrop(Index As Integer, Data As MSComctlLib.DataObject, Effect As Long, Button As Integer, Shift As Integer, x As Single, y As Single)
On Error GoTo LErrorHandler
Dim vntFileName As Variant
If (Data.GetFormat(vbCFFiles)) Then
For Each vntFileName In Data.Files
AddFile vntFileName
Next
End If
LEnd:
Exit Sub
LErrorHandler:
g_ErrorInfo.SetInfoAndDump "tre_OLEDragDrop"
GoTo LEnd
End Sub
Private Sub tre_OLEDragOver(Index As Integer, Data As MSComctlLib.DataObject, Effect As Long, Button As Integer, Shift As Integer, x As Single, y As Single, State As Integer)
On Error GoTo LErrorHandler
Dim vntPathName As Variant
Dim strExtension As String
Effect = vbDropEffectNone
If (Data.GetFormat(vbCFFiles)) Then
For Each vntPathName In Data.Files
strExtension = UCase$(FileExtension(vntPathName))
Select Case strExtension
Case FILE_EXT_HHC_C, FILE_EXT_HHK_C, FILE_EXT_XLS_C, FILE_EXT_CHM_C, _
FILE_EXT_HTM_C
Effect = vbDropEffectCopy
End Select
Next
End If
LEnd:
Exit Sub
LErrorHandler:
g_ErrorInfo.SetInfoAndDump "tre_OLEDragOver"
GoTo LEnd
End Sub
Private Sub tre_MouseDown(Index As Integer, Button As Integer, Shift As Integer, x As Single, y As Single)
tre(Index).SelectedItem = tre(Index).HitTest(x, y)
End Sub
Private Sub tre_MouseMove(Index As Integer, Button As Integer, Shift As Integer, x As Single, y As Single)
Dim Node As Node
Dim blnHHK As Boolean
If Button = vbLeftButton Then
If (Not tre(Index).SelectedItem Is Nothing) Then
Set Node = tre(Index).SelectedItem
If (IsObject(Node.Tag)) Then
If (GetSelectedSKUs() = 0) Then
MsgBox "Please select appropriate SKUs before dragging", vbOKOnly
Exit Sub
End If
tre(Index).DragIcon = Node.CreateDragImage
tre(Index).Drag vbBeginDrag
blnHHK = IIf((Index = TI_HHK_E), True, False)
frmMain.BeginDrag Node.Tag, blnHHK
End If
End If
End If
End Sub
Private Sub cmdClose_Click()
Unload Me
End Sub
Public Sub AddFile( _
ByVal i_strPathName As String, _
Optional ByVal i_strBase As String = "" _
)
On Error GoTo LErrorHandler
Dim strExtension As String
Dim strFileName As String
Dim vntFile As Variant
Dim DOMDoc As MSXML2.IXMLDOMDocument
Dim DOMNode As MSXML2.IXMLDOMNode
Dim Element As MSXML2.IXMLDOMElement
Dim Node As Node
Dim FSO As Scripting.FileSystemObject
Dim WS As IWshShell
Dim strChmDir As String
Dim strBaseDir As String
Dim strCmd As String
Dim strParentNode As String
Dim strHTMLocation As String
Dim enumHelpDir As HELPDIR_E
Dim strSubDir As String
Me.MousePointer = vbHourglass
strExtension = UCase$(FileExtension(i_strPathName))
strFileName = FileNameFromPath(i_strPathName)
enumHelpDir = p_GetHelpDir
strSubDir = Trim$(txtSubDir)
p_clsImporter.SetHelpDir enumHelpDir, strSubDir
Set FSO = New Scripting.FileSystemObject
Select Case strExtension
Case FILE_EXT_HHC_C
If (p_NodeExists(TI_HHC_E, strFileName)) Then
GoTo LEnd
End If
p_strMissingFiles = ""
p_strCorruptFiles = ""
If (i_strBase = "") Then
strHTMLocation = InputBox("For importing HHCs, the directory in which the " & _
"expanded CHM directories are located must be specified so that the " & _
"HTM descriptions can be extracted. In which directory are the expanded CHM " & _
"directories located?")
Else
strHTMLocation = i_strBase
End If
Set DOMDoc = p_clsImporter.Hhc2Hht(i_strPathName, strHTMLocation)
Set Node = tre(TI_HHC_E).Nodes.Add(ROOT_KEY_C, tvwChild, strFileName, strFileName)
Set Node.Tag = XMLFindFirstNode(DOMDoc, HHT_TAXONOMY_ENTRIES_C)
p_CreateTree TI_HHC_E, DOMDoc, Node
If (p_strMissingFiles <> "") Then
MsgBox "The following files couldn't be found: " & p_strMissingFiles
End If
If (p_strCorruptFiles <> "") Then
MsgBox "The following files are corrupt: " & p_strCorruptFiles
End If
Case FILE_EXT_HHK_C
If (p_NodeExists(TI_HHK_E, strFileName)) Then
GoTo LEnd
End If
If (i_strBase = "") Then
strHTMLocation = InputBox("For importing HHKs, the directory in which the " & _
"expanded CHM directories are located must be specified so that the " & _
"HTM titles can be extracted. In which directory are the expanded CHM " & _
"directories located?")
Else
strHTMLocation = i_strBase
End If
Set DOMDoc = p_clsImporter.Hhk2Hht(i_strPathName, strHTMLocation)
Set Node = tre(TI_HHK_E).Nodes(ROOT_KEY_C)
p_CreateTree TI_HHK_E, DOMDoc, Node
Set DOMNode = XMLFindFirstNode(DOMDoc, HHT_TAXONOMY_ENTRY_C)
Node.Tag.appendChild DOMNode
' HHK Nodes are invisible by default
XMLSetAttribute DOMNode, HHT_VISIBLE_C, "FALSE"
Case FILE_EXT_XLS_C
If (p_NodeExists(TI_XLS_E, strFileName)) Then
GoTo LEnd
End If
Set DOMDoc = p_clsImporter.Xls2Hht(i_strPathName)
Set Node = tre(TI_XLS_E).Nodes.Add(ROOT_KEY_C, tvwChild, strFileName, strFileName)
Set Node.Tag = XMLFindFirstNode(DOMDoc, HHT_TAXONOMY_ENTRIES_C)
p_CreateTree TI_XLS_E, DOMDoc, Node
Case FILE_EXT_HTM_C
strParentNode = i_strBase
If (strParentNode = "") Then
strParentNode = "Single HTMs"
End If
If (Not p_NodeExists(TI_HTM_E, strParentNode)) Then
Set Node = tre(TI_HTM_E).Nodes.Add(ROOT_KEY_C, tvwChild, strParentNode, _
strParentNode)
Set DOMDoc = New MSXML2.DOMDocument
Set Element = DOMDoc.createElement(HHT_TAXONOMY_ENTRIES_C)
Set DOMNode = DOMDoc.appendChild(Element)
Set Node.Tag = DOMNode
Else
Set Node = tre(TI_HTM_E).Nodes(strParentNode)
End If
Set DOMDoc = p_clsImporter.Htm2Hht(i_strPathName, i_strBase)
p_CreateTree TI_HTM_E, DOMDoc, Node
Set DOMNode = XMLFindFirstNode(DOMDoc, HHT_TAXONOMY_ENTRY_C)
Node.Tag.appendChild DOMNode
Case FILE_EXT_CHM_C
strBaseDir = Environ$("TEMP") & "\__HSCCHM\"
If (Not FSO.FolderExists(strBaseDir)) Then
FSO.CreateFolder strBaseDir
End If
strChmDir = strBaseDir & strFileName
If (FSO.FolderExists(strChmDir)) Then
FSO.DeleteFolder strChmDir, True
End If
FSO.CreateFolder strChmDir
Set WS = CreateObject("Wscript.Shell")
strCmd = "hh -decompile " & strChmDir & " " & i_strPathName
WS.Run strCmd, , True
For Each vntFile In FSO.GetFolder(strChmDir).Files
If (UCase$(FileExtension(vntFile)) = FILE_EXT_HTM_C) Then
AddFile vntFile, strFileName
ElseIf (UCase$(FileExtension(vntFile)) = FILE_EXT_HHK_C) Then
AddFile vntFile, strBaseDir
Else
AddFile vntFile, strBaseDir
End If
Next
FSO.DeleteFolder strChmDir, True
End Select
LEnd:
Me.MousePointer = vbDefault
Exit Sub
LErrorHandler:
Me.MousePointer = vbDefault
If (strChmDir <> "") Then
FSO.DeleteFolder strChmDir, True
End If
Select Case Err.Number
Case errBadSpreadsheet
MsgBox "The Excel Spreadsheet is probably open or formatted incorrectly. " & _
"Please make sure that the Spreadsheet is closed.", _
vbExclamation Or vbOKOnly
Case errVendorStringNotConfigured
MsgBox "The database is not configured with a vendor string.", _
vbExclamation Or vbOKOnly
Case Else:
g_ErrorInfo.SetInfoAndRaiseError "AddFile"
End Select
End Sub
Private Sub p_CreateTree( _
ByVal i_intIndex As Long, _
ByVal i_DOMNode As MSXML2.IXMLDOMNode, _
ByVal i_Node As Node _
)
On Error GoTo LErrorHandler
Dim DOMNode As MSXML2.IXMLDOMNode
Dim Node As Node
Dim strTitle As String
Dim strURI As String
Dim strHtm As String
Dim intPos As Long
If (i_DOMNode.nodeName = HHT_TAXONOMY_ENTRY_C) Then
strTitle = XMLGetAttribute(i_DOMNode, HHT_TITLE_C)
strURI = Trim$(XMLGetAttribute(i_DOMNode, HHT_URI_C))
If (i_intIndex = TI_HTM_E) Then
intPos = InStrRev(strURI, "/")
strHtm = Mid$(strURI, intPos + 1)
strTitle = strTitle & " (" & strHtm & ")"
End If
Set Node = tre(i_intIndex).Nodes.Add(i_Node, tvwChild, Text:=strTitle)
Set Node.Tag = i_DOMNode
' Color new URIs blue
If (Not p_dictURIs.Exists(strURI)) Then
Node.ForeColor = vbBlue
End If
Else
Set Node = i_Node
End If
If (Not (i_DOMNode.firstChild Is Nothing)) Then
Node.Image = IMAGE_GROUP_E
For Each DOMNode In i_DOMNode.childNodes
p_CreateTree i_intIndex, DOMNode, Node
Next
Else
Node.Image = IMAGE_LEAF_E
End If
LEnd:
Exit Sub
LErrorHandler:
g_ErrorInfo.SetInfoAndRaiseError "p_CreateTree"
GoTo LEnd
End Sub
Public Function GetSelectedSKUs() As SKU_E
Dim enumSelectedSKUs As SKU_E
GetSelectedSKUs = 0
If (chkSKU(SI_WINDOWS_MILLENNIUM_E).Value = 1) Then
enumSelectedSKUs = enumSelectedSKUs Or SKU_WINDOWS_MILLENNIUM_E
End If
If (chkSKU(SI_STANDARD_E).Value = 1) Then
enumSelectedSKUs = enumSelectedSKUs Or SKU_STANDARD_E
End If
If (chkSKU(SI_PROFESSIONAL_E).Value = 1) Then
enumSelectedSKUs = enumSelectedSKUs Or SKU_PROFESSIONAL_E
End If
If (chkSKU(SI_PROFESSIONAL_64_E).Value = 1) Then
enumSelectedSKUs = enumSelectedSKUs Or SKU_PROFESSIONAL_64_E
End If
If (chkSKU(SI_SERVER_E).Value = 1) Then
enumSelectedSKUs = enumSelectedSKUs Or SKU_SERVER_E
End If
If (chkSKU(SI_ADVANCED_SERVER_E).Value = 1) Then
enumSelectedSKUs = enumSelectedSKUs Or SKU_ADVANCED_SERVER_E
End If
If (chkSKU(SI_ADVANCED_SERVER_64_E).Value = 1) Then
enumSelectedSKUs = enumSelectedSKUs Or SKU_ADVANCED_SERVER_64_E
End If
If (chkSKU(SI_DATA_CENTER_SERVER_E).Value = 1) Then
enumSelectedSKUs = enumSelectedSKUs Or SKU_DATA_CENTER_SERVER_E
End If
If (chkSKU(SI_DATA_CENTER_SERVER_64_E).Value = 1) Then
enumSelectedSKUs = enumSelectedSKUs Or SKU_DATA_CENTER_SERVER_64_E
End If
GetSelectedSKUs = enumSelectedSKUs
End Function
Private Function p_GetHelpDir() As HELPDIR_E
If (optHelp(HDI_HELP_MSITS_E).Value) Then
p_GetHelpDir = HELPDIR_HELP_MSITS_E
ElseIf (optHelp(HDI_HELP_HCP_E).Value) Then
p_GetHelpDir = HELPDIR_HELP_HCP_E
ElseIf (optHelp(HDI_SYSTEM_E).Value) Then
p_GetHelpDir = HELPDIR_SYSTEM_E
ElseIf (optHelp(HDI_VENDOR_E).Value) Then
p_GetHelpDir = HELPDIR_VENDOR_E
End If
End Function
Private Function p_NodeExists( _
ByVal i_intIndex As Long, _
ByVal i_strKey As String _
) As Boolean
On Error GoTo LErrorHandler
Dim Node As Node
Set Node = tre(i_intIndex).Nodes(i_strKey)
p_NodeExists = True
Exit Function
LErrorHandler:
p_NodeExists = False
End Function
Private Sub p_SetSizingInfo()
Static blnInfoSet As Boolean
If (blnInfoSet) Then
Exit Sub
End If
p_clsSizer.AddControl SSTab
Set p_clsSizer.ReferenceControl(DIM_HEIGHT_E) = Me
Set p_clsSizer.ReferenceControl(DIM_WIDTH_E) = Me
p_clsSizer.AddControl tre(TI_HHC_E)
Set p_clsSizer.ReferenceControl(DIM_HEIGHT_E) = SSTab
Set p_clsSizer.ReferenceControl(DIM_WIDTH_E) = SSTab
p_clsSizer.AddControl tre(TI_HHK_E)
Set p_clsSizer.ReferenceControl(DIM_HEIGHT_E) = SSTab
Set p_clsSizer.ReferenceControl(DIM_WIDTH_E) = SSTab
p_clsSizer.AddControl tre(TI_HTM_E)
Set p_clsSizer.ReferenceControl(DIM_HEIGHT_E) = SSTab
Set p_clsSizer.ReferenceControl(DIM_WIDTH_E) = SSTab
p_clsSizer.AddControl tre(TI_XLS_E)
Set p_clsSizer.ReferenceControl(DIM_HEIGHT_E) = SSTab
Set p_clsSizer.ReferenceControl(DIM_WIDTH_E) = SSTab
p_clsSizer.AddControl cmdClose
Set p_clsSizer.ReferenceControl(DIM_TOP_E) = Me
p_clsSizer.ReferenceDimension(DIM_TOP_E) = DIM_HEIGHT_E
Set p_clsSizer.ReferenceControl(DIM_LEFT_E) = Me
p_clsSizer.ReferenceDimension(DIM_LEFT_E) = DIM_WIDTH_E
p_clsSizer.AddControl fraSKU
Set p_clsSizer.ReferenceControl(DIM_TOP_E) = SSTab
p_clsSizer.ReferenceDimension(DIM_TOP_E) = DIM_BOTTOM_E
Set p_clsSizer.ReferenceControl(DIM_WIDTH_E) = Me
p_clsSizer.Operation(DIM_WIDTH_E) = OP_MULTIPLY_E
p_clsSizer.AddControl chkSKU(SI_SERVER_E)
Set p_clsSizer.ReferenceControl(DIM_LEFT_E) = fraSKU
p_clsSizer.ReferenceDimension(DIM_LEFT_E) = DIM_WIDTH_E
p_clsSizer.Operation(DIM_LEFT_E) = OP_MULTIPLY_E
p_clsSizer.AddControl chkSKU(SI_ADVANCED_SERVER_E)
Set p_clsSizer.ReferenceControl(DIM_LEFT_E) = chkSKU(SI_SERVER_E)
p_clsSizer.AddControl chkSKU(SI_ADVANCED_SERVER_64_E)
Set p_clsSizer.ReferenceControl(DIM_LEFT_E) = chkSKU(SI_SERVER_E)
p_clsSizer.AddControl chkSKU(SI_DATA_CENTER_SERVER_E)
Set p_clsSizer.ReferenceControl(DIM_LEFT_E) = chkSKU(SI_SERVER_E)
p_clsSizer.AddControl chkSKU(SI_DATA_CENTER_SERVER_64_E)
Set p_clsSizer.ReferenceControl(DIM_LEFT_E) = chkSKU(SI_SERVER_E)
p_clsSizer.AddControl fraHelp
Set p_clsSizer.ReferenceControl(DIM_TOP_E) = SSTab
p_clsSizer.ReferenceDimension(DIM_TOP_E) = DIM_BOTTOM_E
Set p_clsSizer.ReferenceControl(DIM_WIDTH_E) = Me
p_clsSizer.Operation(DIM_WIDTH_E) = OP_MULTIPLY_E
p_clsSizer.AddControl txtSubDir
Set p_clsSizer.ReferenceControl(DIM_WIDTH_E) = fraHelp
blnInfoSet = True
End Sub
Private Sub p_SetToolTips()
tre(TI_HHC_E).ToolTipText = "Imported Table of Content files (.hhc) will be displayed here."
tre(TI_HHK_E).ToolTipText = "Imported Index files (.hhk) will be displayed here."
tre(TI_HTM_E).ToolTipText = "Imported Topic files (.htm) will be displayed here."
tre(TI_XLS_E).ToolTipText = "Imported Excel files (.xls) will be displayed here."
fraSKU.ToolTipText = "Select the appropriate SKU for the files you wish to import."
fraHelp.ToolTipText = "Select the appropriate format for the URI"
lblSubDir.ToolTipText = "Type the subdirectory, if needed, to append to the Help file directory."
txtSubDir.ToolTipText = lblSubDir.ToolTipText
End Sub
|
<filename>Task/Ordered-words/VBA/ordered-words.vba
Public Sub orderedwords(fname As String)
' find ordered words in dict file that have the longest word length
' fname is the name of the input file
' the words are printed in the immediate window
' this subroutine uses boolean function IsOrdered
Dim word As String 'word to be tested
Dim l As Integer 'length of word
Dim wordlength As Integer 'current longest word length
Dim orderedword() As String 'dynamic array holding the ordered words with the current longest word length
Dim wordsfound As Integer 'length of the array orderedword()
On Error GoTo NotFound 'catch incorrect/missing file name
Open fname For Input As #1
On Error GoTo 0
'initialize
wordsfound = 0
wordlength = 0
'process file line per line
While Not EOF(1)
Line Input #1, word
If IsOrdered(word) Then 'found one, is it equal to or longer than current word length?
l = Len(word)
If l >= wordlength Then 'yes, so add to list or start a new list
If l > wordlength Then 'it's longer, we must start a new list
wordsfound = 1
wordlength = l
Else 'equal length, increase the list size
wordsfound = wordsfound + 1
End If
'add the word to the list
ReDim Preserve orderedword(wordsfound)
orderedword(wordsfound) = word
End If
End If
Wend
Close #1
'print the list
Debug.Print "Found"; wordsfound; "ordered words of length"; wordlength
For i = 1 To wordsfound
Debug.Print orderedword(i)
Next
Exit Sub
NotFound:
debug.print "Error: Cannot find or open file """ & fname & """!"
End Sub
Public Function IsOrdered(someWord As String) As Boolean
'true if letters in word are in ascending (ascii) sequence
Dim l As Integer 'length of someWord
Dim wordLcase As String 'the word in lower case
Dim ascStart As Integer 'ascii code of first char
Dim asc2 As Integer 'ascii code of next char
wordLcase = LCase(someWord) 'convert to lower case
l = Len(someWord)
IsOrdered = True
If l > 0 Then 'this skips empty string - it is considered ordered...
ascStart = Asc(Left$(wordLcase, 1))
For i = 2 To l
asc2 = Asc(Mid$(wordLcase, i, 1))
If asc2 < ascStart Then 'failure!
IsOrdered = False
Exit Function
End If
ascStart = asc2
Next i
End If
End Function
|
<filename>Task/Generic-swap/VBScript/generic-swap-2.vb
dim a
a = "woof"
dim b
b = now()
swap a,b
wscript.echo a
wscript.echo b
|
Private Function SumMult3and5(n As Double) As Double
Dim i As Double
For i = 3 To n - 1 Step 3
SumMult3and5 = SumMult3and5 + i
Next
For i = 5 To n - 1 Step 5
If i Mod 15 <> 0 Then SumMult3and5 = SumMult3and5 + i
Next
End Function
|
<filename>basic/examples/a/dim.bas
100 DIM Y$(10)
120 PRINT LEN(Y$)
|
'check if the number is pernicious
Function IsPernicious(n)
IsPernicious = False
bin_num = Dec2Bin(n)
sum = 0
For h = 1 To Len(bin_num)
sum = sum + CInt(Mid(bin_num,h,1))
Next
If IsPrime(sum) Then
IsPernicious = True
End If
End Function
'prime number validation
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
'decimal to binary converter
Function Dec2Bin(n)
q = n
Dec2Bin = ""
Do Until q = 0
Dec2Bin = CStr(q Mod 2) & Dec2Bin
q = Int(q / 2)
Loop
End Function
'display the first 25 pernicious numbers
c = 0
WScript.StdOut.Write "First 25 Pernicious Numbers:"
WScript.StdOut.WriteLine
For k = 1 To 100
If IsPernicious(k) Then
WScript.StdOut.Write k & ", "
c = c + 1
End If
If c = 25 Then
Exit For
End If
Next
WScript.StdOut.WriteBlankLines(2)
'display the pernicious numbers between 888,888,877 to 888,888,888 (inclusive)
WScript.StdOut.Write "Pernicious Numbers between 888,888,877 to 888,888,888 (inclusive):"
WScript.StdOut.WriteLine
For l = 888888877 To 888888888
If IsPernicious(l) Then
WScript.StdOut.Write l & ", "
End If
Next
WScript.StdOut.WriteLine
|
Set NS = GetObject("winmgmts:{impersonationLevel=impersonate}")
while true
for each Service in NS.ExecQuery ("select DisplayName from win32_service")
WScript.Echo Service.DisplayName
next
wend
|
<filename>printscan/faxsrv/com/win2k/vbtest/module.bas
Attribute VB_Name = "FaxModule"
Public Fax As Object
Public FaxDocument As Object
Public Ports As Object
Public Port As Object
Public PortStatus As Object
Public Method As Object
Public Methods As Object
Public MethodIdx As Long
Public Connected As Boolean
Public Doc As Boolean
|
<gh_stars>10-100
'//on error resume next
set objArgs = wscript.Arguments
if objArgs.count < 2 then
wscript.echo "Usage addmountpoint volume mountpoint"
wscript.quit(1)
end if
strVolume = Replace(objArgs(0), "\", "\\")
strDirectory = objArgs(1)
wscript.echo "Volume: " & strVolume
wscript.echo "Directory: " & strDirectory
'// Get the volume
strQuery = "select * from Win32_Volume where Name = '" & strVolume & "'"
set VolumeSet = GetObject("winmgmts:").ExecQuery(strQuery)
for each obj in VolumeSet
set Volume = obj
exit for
next
wscript.echo "Volume: " & Volume.Name
wscript.echo "Directory: " & strDirectory
Result = Volume.AddMountPoint(strDirectory)
strMessage = MapErrorCode("Win32_Volume", "AddMountPoint", Result)
wscript.echo "Volume.AddMountPoint returned: " & Result & " : " & strMessage
Function MapErrorCode(ByRef strClass, ByRef strMethod, ByRef intCode)
set objClass = GetObject("winmgmts:").Get(strClass, &h20000)
set objMethod = objClass.methods_(strMethod)
values = objMethod.qualifiers_("values")
if ubound(values) < intCode then
wscript.echo " FAILURE - no error message found for " & intCode & " : " & strClass & "." & strMethod
f.writeline ("FAILURE - no error message found for " & intCode & " : " & strClass & "." & strMethod)
MapErrorCode = ""
else
MapErrorCode = values(intCode)
end if
End Function
|
Const ForReading = 1
Const ForWriting = 2
strFiles = Array("test1.txt", "test2.txt", "test3.txt")
With CreateObject("Scripting.FileSystemObject")
For i = 0 To UBound(strFiles)
strText = .OpenTextFile(strFiles(i), ForReading).ReadAll()
With .OpenTextFile(strFiles(i), ForWriting)
.Write Replace(strText, "Goodbye London!", "Hello New York!")
.Close
End With
Next
End With
|
<filename>Task/Active-Directory-Connect/VBScript/active-directory-connect.vb<gh_stars>1-10
Set objConn = CreateObject("ADODB.Connection")
Set objCmd = CreateObject("ADODB.Command")
objConn.Provider = "ADsDSOObject"
objConn.Open
|
Private Function SumMult3and5BETTER(n As Double) As Double
Dim i As Double
For i = 3 To n - 1 Step 3
SumMult3and5BETTER = SumMult3and5BETTER + i
Next
For i = 5 To n - 1 Step 5
SumMult3and5BETTER = SumMult3and5BETTER + i
Next
For i = 15 To n - 1 Step 15
SumMult3and5BETTER = SumMult3and5BETTER - i
Next
End Function
|
<filename>admin/wmi/wbem/scripting/test/vbscript/context2.vbs<gh_stars>10-100
set Context = CreateObject("WbemScripting.SWbemNamedValueSet")
Context.Add "InstanceCount", 5
WScript.Echo Context("InstanceCount").Value
|
<filename>Task/Luhn-test-of-credit-card-numbers/VBA/luhn-test-of-credit-card-numbers.vba
Option Explicit
Sub Main()
Debug.Print "Number 49927398716 is "; Luhn("49927398716")
Debug.Print "Number 49927398717 is "; Luhn("49927398717")
Debug.Print "Number 1234567812345678 is "; Luhn("1234567812345678")
Debug.Print "Number 1234567812345670 is "; Luhn("1234567812345670")
End Sub
Private Function Luhn(Nb As String) As String
Dim t$, i&, Summ&, s&
t = StrReverse(Nb)
For i = 1 To Len(t) Step 2
Summ = Summ + CInt(Mid(t, i, 1))
Next i
For i = 2 To Len(t) Step 2
s = 2 * (CInt(Mid(t, i, 1)))
If s >= 10 Then
Summ = Summ - 9
End If
Summ = Summ + s
Next i
If Summ Mod 10 = 0 Then
Luhn = "valid"
Else
Luhn = "invalid"
End If
End Function
|
<reponame>LaudateCorpus1/RosettaCodeData
Dim sieve()
If WScript.Arguments.Count>=1 Then
n = WScript.Arguments(0)
Else
n = 99
End If
ReDim sieve(n)
For i = 1 To n
sieve(i) = True
Next
For i = 2 To n
If sieve(i) Then
For j = i * 2 To n Step i
sieve(j) = False
Next
End If
Next
For i = 2 To n
If sieve(i) Then WScript.Echo i
Next
|
Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function 'small Helper-Function
Sub Main()
Const Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5
Dim P&, I&, G&, A&, M, Cur(Value To Volume)
Dim S As New Collection: S.Add Array(0) '<- init Solutions-Coll.
Const SackW = 25, SackV = 0.25
Dim Panacea: Panacea = Array(3000, 0.3, 0.025)
Dim Ichor: Ichor = Array(1800, 0.2, 0.015)
Dim Gold: Gold = Array(2500, 2, 0.002)
For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume)))
For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume)))
For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume)))
For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next
If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _
S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1
Next G, I, P
Debug.Print "Value", "Weight", "Volume", "PanaceaCount", "IchorCount", "GoldCount"
For Each M In S '<- enumerate the Attributes of the Maxima
If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC)
Next
End Sub
|
Option Explicit
Sub Main_Bulls_and_cows()
Dim strNumber As String, strInput As String, strMsg As String, strTemp As String
Dim boolEnd As Boolean
Dim lngCpt As Long
Dim i As Byte, bytCow As Byte, bytBull As Byte
Const NUMBER_OF_DIGITS As Byte = 4
Const MAX_LOOPS As Byte = 25 'the max of lines supported by MsgBox
strNumber = Create_Number(NUMBER_OF_DIGITS)
Do
bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1
If lngCpt > MAX_LOOPS Then strMsg = "Max of loops... Sorry you loose!": Exit Do
strInput = AskToUser(NUMBER_OF_DIGITS)
If strInput = "Exit Game" Then strMsg = "User abort": Exit Do
For i = 1 To Len(strNumber)
If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then
bytBull = bytBull + 1
ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then
bytCow = bytCow + 1
End If
Next i
If bytBull = Len(strNumber) Then
boolEnd = True: strMsg = "You win in " & lngCpt & " loops!"
Else
strTemp = strTemp & vbCrLf & "With : " & strInput & " ,you have : " & bytBull & " bulls," & bytCow & " cows."
MsgBox strTemp
End If
Loop While Not boolEnd
MsgBox strMsg
End Sub
Function Create_Number(NbDigits As Byte) As String
Dim myColl As New Collection
Dim strTemp As String
Dim bytAlea As Byte
Randomize
Do
bytAlea = Int((Rnd * 9) + 1)
On Error Resume Next
myColl.Add CStr(bytAlea), CStr(bytAlea)
If Err <> 0 Then
On Error GoTo 0
Else
strTemp = strTemp & CStr(bytAlea)
End If
Loop While Len(strTemp) < NbDigits
Create_Number = strTemp
End Function
Function AskToUser(NbDigits As Byte) As String
Dim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte
Do While Not boolGood
strIn = InputBox("Enter your number (" & NbDigits & " digits)", "Number")
If StrPtr(strIn) = 0 Then strIn = "Exit Game": Exit Do
If strIn <> "" Then
If Len(strIn) = NbDigits Then
NbDiff = 0
For i = 1 To Len(strIn)
If Len(Replace(strIn, Mid(strIn, i, 1), "")) < NbDigits - 1 Then
NbDiff = 1
Exit For
End If
Next i
If NbDiff = 0 Then boolGood = True
End If
End If
Loop
AskToUser = strIn
End Function
|
<gh_stars>1-10
Public Function LuhnCheckPassed(ByVal dgts As String) As Boolean
Dim i As Long, s As Long, s1 As Long
dgts = VBA.StrReverse(dgts)
For i = 1 To Len(dgts) Step 2
s = s + CInt(Mid$(dgts, i, 1))
Next i
For i = 2 To Len(dgts) Step 2
s1 = 2 * (CInt(Mid$(dgts, i, 1)))
If s1 >= 10 Then
s = s - 9
End If
s = s + s1
Next i
LuhnCheckPassed = Not CBool(s Mod 10)
End Function
|
<filename>admin/wmi/wbem/scripting/test/vb/method/method.frm
VERSION 5.00
Begin VB.Form Form1
Caption = "Form1"
ClientHeight = 3195
ClientLeft = 60
ClientTop = 345
ClientWidth = 4680
LinkTopic = "Form1"
ScaleHeight = 3195
ScaleWidth = 4680
StartUpPosition = 3 'Windows Default
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Private Sub Form_Load()
Dim MethodSet As SWbemMethodSet
Set MethodSet = GetObject("cim:root/default:m").Methods_
Dim M As SWbemMethod
Dim MM As SWbemMethod
For Each M In MethodSet
Debug.Print M.Name
For Each MM In MethodSet
Debug.Print MM.Name, MM.Origin
Next
Next
End Sub
|
<gh_stars>10-100
'***************************************************************************
'This script tests references methods on ISWbemServices and ISWbemObject
'***************************************************************************
On Error Resume Next
while true
'Do it via a SWbemServices
WScript.Echo
WScript.Echo "Services-based call for all classes associated by instance"
WScript.Echo
Set Service = GetObject("winmgmts:{impersonationLevel=impersonate}")
Set Enumerator = Service.ReferencesTo _
("Win32_DiskPartition.DeviceID=""Disk #0, Partition #1""", "Win32_SystemPartitions",,true)
for each Thingy in Enumerator
WScript.Echo Thingy.Path_.Relpath
next
'Do it via a ISWbemObject
WScript.Echo
WScript.Echo "Object-based call for all classes associated in schema"
WScript.Echo
Set Object = GetObject("winmgmts:{impersonationLevel=impersonate}!Win32_DiskPartition")
for each Thingy in Object.References_ (,,,true)
WScript.Echo Thingy.Path_.Relpath
next
if Err <> 0 Then
WScript.Echo Err.Description
Err.Clear
End if
wend
|
on error resume next
const wbemPrivilegeDebug = 19
'set service = GetObject ("winmgmts:{impersonationLevel=impersonate}!root/scenario26")
set service = GetObject ("winmgmts:root/scenario26")
service.security_.privileges.Add wbemPrivilegeDebug
if err <> 0 then
WScript.Echo "1 ", Hex(Err.Number), Err.Description, Err.Source
end if
set process = service.get ("Scenario26.Key=""xy""")
if err <> 0 then
WScript.Echo "2 ", Err.Number, Err.Description, Err.Source
end if
|
'Copyright (c)<2000>Microsoft Corporation. All rights reserved.
Dim WshShell
Dim te
Set WshShell = WScript.CreateObject("WScript.Shell")
On Error Resume Next
te = WshShell.RegRead("HKLM\Software\Microsoft\ServerAppliance\ApplianceManager\ObjectManagers\Microsoft_SA_TASK\ApplianceInitializationTask\TaskExecutables")
'Remove alloccurances of setalertemail incase there are more
'Append SetChimesettings at the end of the key
te = Replace(te," setalertemail.alertemail.1"," ",1,-1,1)
te = te + " setalertemail.alertemail.1"
WshShell.RegWrite "HKLM\Software\Microsoft\ServerAppliance\ApplianceManager\ObjectManagers\Microsoft_SA_TASK\ApplianceInitializationTask\TaskExecutables",te
|
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\data.txt",1)
bad_readings_total = 0
good_readings_total = 0
data_gap = 0
start_date = ""
end_date = ""
tmp_datax_gap = 0
tmp_start_date = ""
Do Until objFile.AtEndOfStream
bad_readings = 0
good_readings = 0
line_total = 0
line = objFile.ReadLine
token = Split(line,vbTab)
n = 1
Do While n <= UBound(token)
If n + 1 <= UBound(token) Then
If CInt(token(n+1)) < 1 Then
bad_readings = bad_readings + 1
bad_readings_total = bad_readings_total + 1
'Account for bad readings.
If tmp_start_date = "" Then
tmp_start_date = token(0)
End If
tmp_data_gap = tmp_data_gap + 1
Else
good_readings = good_readings + 1
line_total = line_total + CInt(token(n))
good_readings_total = good_readings_total + 1
'Sum up the bad readings.
If (tmp_start_date <> "") And (tmp_data_gap > data_gap) Then
start_date = tmp_start_date
end_date = token(0)
data_gap = tmp_data_gap
tmp_start_date = ""
tmp_data_gap = 0
Else
tmp_start_date = ""
tmp_data_gap = 0
End If
End If
End If
n = n + 2
Loop
line_avg = line_total/good_readings
WScript.StdOut.Write "Date: " & token(0) & vbTab &_
"Bad Reads: " & bad_readings & vbTab &_
"Good Reads: " & good_readings & vbTab &_
"Line Total: " & FormatNumber(line_total,3) & vbTab &_
"Line Avg: " & FormatNumber(line_avg,3)
WScript.StdOut.WriteLine
Loop
WScript.StdOut.WriteLine
WScript.StdOut.Write "Maximum run of " & data_gap &_
" consecutive bad readings from " & start_date & " to " &_
end_date & "."
WScript.StdOut.WriteLine
objFile.Close
Set objFSO = Nothing
|
Debug.Assert i = 42
|
<filename>Task/Greatest-element-of-a-list/Visual-Basic/greatest-element-of-a-list.vb
Public Function ListMax(anArray())
'return the greatest element in array anArray
'use LBound and UBound to find its length
n0 = LBound(anArray)
n = UBound(anArray)
theMax = anArray(n0)
For i = (n0 + 1) To n
If anArray(i) > theMax Then theMax = anArray(i)
Next
ListMax = theMax
End Function
Public Sub ListMaxTest()
Dim b()
'test function ListMax
'fill array b with some numbers:
b = Array(5992424433449#, 4534344439984#, 551344678, 99800000#)
'print the greatest element
Debug.Print "Greatest element is"; ListMax(b())
End Sub
|
Function Cholesky(Mat As Range) As Variant
Dim A() As Double, L() As Double, sum As Double, sum2 As Double
Dim m As Byte, i As Byte, j As Byte, k As Byte
'Ensure matrix is square
If Mat.Rows.Count <> Mat.Columns.Count Then
MsgBox ("Correlation matrix is not square")
Exit Function
End If
m = Mat.Rows.Count
'Initialize and populate matrix A of values and matrix L which will be the lower Cholesky
ReDim A(0 To m - 1, 0 To m - 1)
ReDim L(0 To m - 1, 0 To m - 1)
For i = 0 To m - 1
For j = 0 To m - 1
A(i, j) = Mat(i + 1, j + 1).Value2
L(i, j) = 0
Next j
Next i
'Handle the simple cases explicitly to save time
Select Case m
Case Is = 1
L(0, 0) = Sqr(A(0, 0))
Case Is = 2
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
Case Else
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
For i = 2 To m - 1
sum2 = 0
For k = 0 To i - 1
sum = 0
For j = 0 To k
sum = sum + L(i, j) * L(k, j)
Next j
L(i, k) = (A(i, k) - sum) / L(k, k)
sum2 = sum2 + L(i, k) * L(i, k)
Next k
L(i, i) = Sqr(A(i, i) - sum2)
Next i
End Select
Cholesky = L
End Function
|
<gh_stars>1-10
WScript.Echo StrReverse("asdf")
|
VERSION 5.00
Object = "{F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0"; "Comdlg32.ocx"
Object = "{3B7C8863-D78F-101B-B9B5-04021C009402}#1.2#0"; "RICHTX32.OCX"
Begin VB.Form SomeForm
BorderStyle = 3 'Fixed Dialog
Caption = "Some Form"
ClientHeight = 7950
MaxButton = 0 'False
End
|
<gh_stars>1-10
wscript.echo createobject("scripting.filesystemobject").opentextfile("utf16encoded.txt",1,-1).readall
|
Module VBModule
Sub Main()
Dim a As Integer
Dim b As Integer
a = 1
b = a + a
Console.WriteLine(0)
Console.WriteLine(a)
Console.WriteLine(a)
Console.WriteLine(b)
While a < 1000000
a = a + b
b = a + b
Console.WriteLine(a)
Console.WriteLine(b)
End while
End Sub
End Module
|
data = "foo,bar,baz,quux,quuux,quuuux,bazola,ztesch,foo,bar,thud,grunt," &_
"foo,bar,bletch,foo,bar,fum,fred,jim,sheila,barney,flarp,zxc," &_
"spqr,wombat,shme,foo,bar,baz,bongo,spam,eggs,snork,foo,bar," &_
"zot,blarg,wibble,toto,titi,tata,tutu,pippo,pluto,paperino,aap," &_
"noot,mies,oogle,foogle,boogle,zork,gork,bork"
haystack = Split(data,",")
Do
WScript.StdOut.Write "Word to search for? (Leave blank to exit) "
needle = WScript.StdIn.ReadLine
If needle <> "" Then
found = 0
For i = 0 To UBound(haystack)
If UCase(haystack(i)) = UCase(needle) Then
found = 1
WScript.StdOut.Write "Found " & Chr(34) & needle & Chr(34) & " at index " & i
WScript.StdOut.WriteLine
End If
Next
If found < 1 Then
WScript.StdOut.Write Chr(34) & needle & Chr(34) & " not found."
WScript.StdOut.WriteLine
End If
Else
Exit do
End If
Loop
|
<filename>base/cluster/admin/msclus/vbscript/rename.vbs<gh_stars>10-100
Option Explicit
Main
Sub Main
Dim oCluster
Dim sCluster
Set oCluster = CreateObject("MSCluster.Cluster")
sCluster = InputBox( "Cluster to open?" )
oCluster.Open( sCluster )
oCluster.Name = "YODummy1"
End Sub
|
<reponame>npocmaka/Windows-Server-2003
VERSION 5.00
Begin VB.Form Form1
Caption = "WBEM NT Event Log Sample"
ClientHeight = 3285
ClientLeft = 60
ClientTop = 345
ClientWidth = 10695
LinkTopic = "Form1"
ScaleHeight = 3285
ScaleWidth = 10695
StartUpPosition = 3 'Windows Default
Begin VB.CommandButton Command2
Caption = "Stop Listening"
Height = 375
Left = 5760
TabIndex = 2
Top = 2760
Width = 1575
End
Begin VB.CommandButton Command1
Caption = "Listen for Events"
Height = 375
Left = 3480
TabIndex = 1
Top = 2760
Width = 1575
End
Begin VB.ListBox List
Height = 2010
ItemData = "execnquery.frx":0000
Left = 240
List = "execnquery.frx":0002
TabIndex = 0
Top = 600
Width = 10095
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Dim objServices As SWbemServices
Dim WithEvents objSink As SWbemSink
Attribute objSink.VB_VarHelpID = -1
Dim objEvents As SWbemEventSource
Private Sub Command1_Click()
Dim objEvent As SWbemObject
Command1.Enabled = False
Command2.Enabled = True
On Error Resume Next
objServices.ExecNotificationQueryAsync objSink, "select * from __instancecreationevent where targetinstance isa 'Win32_NTLogEvent'"
End Sub
Private Sub Command2_Click()
Command2.Enabled = False
Command1.Enabled = True
objSink.Cancel
End Sub
Private Sub Form_Load()
' The following sample registers to be informed whenever an instance
' of the class MyClass is created
Command1.Enabled = False
Command2.Enabled = False
Set objSink = New SWbemSink
Set objServices = GetObject("winmgmts:{impersonationLevel=impersonate,(Security)}")
Command1.Enabled = True
End Sub
Private Sub objSink_OnCompleted(ByVal iHResult As WbemScripting.WbemErrorEnum, ByVal objWbemErrorObject As WbemScripting.ISWbemObject, ByVal objWbemAsyncContext As WbemScripting.ISWbemNamedValueSet)
Debug.Print "Cancelled"
End Sub
Private Sub objSink_OnObjectReady(ByVal objWbemObject As WbemScripting.ISWbemObject, ByVal objWbemAsyncContext As WbemScripting.ISWbemNamedValueSet)
Debug.Print "Got event"
List.AddItem objWbemObject.TargetInstance.Message
List.Refresh
End Sub
|
10 DIM LL10
20 FOR I=0 TO 10
30 LLI=-1
40 NEXT
50 P.$21
60 F.I=0 TO 1
70 P=#3A00
80[
90 LDA @0
100 STA #84
110 JSR LL5
120 LDA @#00
130 STA #80
140 STA #82
150 LDA @#82
160 STA #81
170 LDA @#A0
180 STA #83
190 LDY @#00
200:LL0
210 JSR LL4
220 LDA @#05
230 STA #BFFF
240 LDA @#A0
250 STA #A555
260 LDA #84
270 STA #BFFF
280 LDA (#80),Y
290 STA (#82),Y
300 LDX @#08
310:LL1
320 DEX
330 BNE LL1
340 INY
350 BNE LL0
360 INC #81
370 INC #83
380 LDA #83
390 CMP @#B0
400 BNE LL0
410 RTS
420:LL4
430 LDA @#05
440 STA #BFFF
450 LDA @#AA
460 STA #A555
470 LDA @#02
480 STA #BFFF
490 LDA @#55
500 STA #AAAA
510 RTS
520:LL5
530 PHA
540 JSR LL4
550 LDA @#05
560 STA #BFFF
570 LDA @#80
580 STA #A555
590 JSR LL4
600 PLA
610 STA #BFFF
620 LDA @#30
630 STA #A000
640 LDY @#00
650:LL6
660 LDX @#00
670:LL7
680 DEX
690 BNE LL7
700 DEY
710 BNE LL6
720 RTS
730]
740 N.
750 P.$6
760 INPUT "WHICH BANK ",A
770 LINK #3A00
780 END
|
'****************************************************************
'* MMC automation / com event test script
'*
'* Copyright (C) Microsoft Corporation, 2000 - 2000
'****************************************************************
Option Explicit ' Force explicit variable declaration.
'****************************************************************
'* Event Handlers : Application
'****************************************************************
Dim ErrorInEvent
ErrorInEvent = False
'---------------------------------------------
' Occurs when application is closed
'---------------------------------------------
Dim AppEvent_OnQuit_Application
Dim AppEvent_OnQuit_IsExpected
Sub AppEvent_OnQuit( Application )
if Not AppEvent_OnQuit_IsExpected Then
ErrorInEvent = True
Err.Raise 100, "AppEvent_OnQuit", "Event occured when not expected"
End if
Set AppEvent_OnQuit_Application = Application
Err.Raise 222, "--Not a bug--", "Returning error to test if script does not break MMC"
End Sub
'---------------------------------------------
' Occurs when document is opened
'---------------------------------------------
Dim AppEvent_OnDocumentOpen_Document
Dim AppEvent_OnDocumentOpen_bNew
Dim AppEvent_OnDocumentOpen_IsExpected
Sub AppEvent_OnDocumentOpen( Document, bNew )
if Not AppEvent_OnDocumentOpen_IsExpected Then
ErrorInEvent = True
Err.Raise 100, "AppEvent_OnDocumentOpen", "Event occured when not expected"
End if
Set AppEvent_OnDocumentOpen_Document = Document
AppEvent_OnDocumentOpen_bNew = bNew
Err.Raise 222, "--Not a bug--", "Returning error to test if script does not break MMC"
End Sub
'****************************************************************
'* Event Handlers : Document
'****************************************************************
'---------------------------------------------
' Occurs before the document is destroyed
'---------------------------------------------
Dim AppEvent_OnDocumentClose_Document
Dim AppEvent_OnDocumentClose_IsExpected
Sub AppEvent_OnDocumentClose( Document)
if Not AppEvent_OnDocumentClose_IsExpected Then
ErrorInEvent = True
Err.Raise 100, "AppEvent_OnDocumentClose", "Event occured when not expected"
End if
Set AppEvent_OnDocumentClose_Document = Document
Err.Raise 222, "--Not a bug--", "Returning error to test if script does not break MMC"
End Sub
'---------------------------------------------
' Occurs when a snapin is added
'---------------------------------------------
Dim AppEvent_OnSnapInAdded_Document
Dim AppEvent_OnSnapInAdded_SnapIn
Dim AppEvent_OnSnapInAdded_IsExpected
Sub AppEvent_OnSnapInAdded( Document, SnapIn )
if Not AppEvent_OnSnapInAdded_IsExpected Then
ErrorInEvent = True
Err.Raise 100, "AppEvent_OnSnapInAdded", "Event occured when not expected"
End if
Set AppEvent_OnSnapInAdded_Document = Document
Set AppEvent_OnSnapInAdded_SnapIn = SnapIn
Err.Raise 222, "--Not a bug--", "Returning error to test if script does not break MMC"
End Sub
'---------------------------------------------
' Occurs when the snapin is removed
'---------------------------------------------
Dim AppEvent_OnSnapInRemoved_Document
Dim AppEvent_OnSnapInRemoved_SnapIn
Dim AppEvent_OnSnapInRemoved_IsExpected
Sub AppEvent_OnSnapInRemoved( Document, SnapIn )
if Not AppEvent_OnSnapInRemoved_IsExpected Then
ErrorInEvent = True
Err.Raise 100, "AppEvent_OnSnapInRemoved", "Event occured when not expected"
End if
Set AppEvent_OnSnapInRemoved_Document = Document
Set AppEvent_OnSnapInRemoved_SnapIn = SnapIn
Err.Raise 222, "--Not a bug--", "Returning error to test if script does not break MMC"
End Sub
'---------------------------------------------
' Occurs when a view is added
'---------------------------------------------
Dim AppEvent_OnNewView_View
Dim AppEvent_OnNewView_IsExpected
Sub AppEvent_OnNewView( View )
if Not AppEvent_OnNewView_IsExpected Then
ErrorInEvent = True
Err.Raise 100, "AppEvent_OnNewView", "Event occured when not expected"
End if
Set AppEvent_OnNewView_View = View
Err.Raise 222, "--Not a bug--", "Returning error to test if script does not break MMC"
End Sub
'---------------------------------------------
' Occurs when the view is destroyed
'---------------------------------------------
Dim AppEvent_OnViewClose_View
Dim AppEvent_OnViewClose_IsExpected
Sub AppEvent_OnViewClose( View )
if Not AppEvent_OnViewClose_IsExpected Then
ErrorInEvent = True
Err.Raise 100, "AppEvent_OnViewClose", "Event occured when not expected"
End if
Set AppEvent_OnViewClose_View = View
Err.Raise 222, "--Not a bug--", "Returning error to test if script does not break MMC"
End Sub
'---------------------------------------------
' Occurs when the view is changed, for instance by a scope node selection change
'---------------------------------------------
Dim AppEvent_OnViewChange_View
Dim AppEvent_OnViewChange_NewOwnerNode
Dim AppEvent_OnViewChange_IsExpected
Sub AppEvent_OnViewChange( View, NewOwnerNode )
if Not AppEvent_OnViewChange_IsExpected Then
ErrorInEvent = True
Err.Raise 100, "AppEvent_OnViewChange", "Event occured when not expected"
End if
Set AppEvent_OnViewChange_View = View
Set AppEvent_OnViewChange_NewOwnerNode = NewOwnerNode
Err.Raise 222, "--Not a bug--", "Returning error to test if script does not break MMC"
End Sub
'---------------------------------------------
' Occurs when the result item selection for a view is changed
'---------------------------------------------
Dim AppEvent_OnSelectionChange_View
Dim AppEvent_OnSelectionChange_NewNodes
Dim AppEvent_OnSelectionChange_IsExpected
Sub AppEvent_OnSelectionChange( View, NewNodes )
if Not AppEvent_OnSelectionChange_IsExpected Then
ErrorInEvent = True
Err.Raise 100, "AppEvent_OnSelectionChange", "Event occured when not expected"
End if
Set AppEvent_OnSelectionChange_View = View
Set AppEvent_OnSelectionChange_NewNodes = NewNodes
Err.Raise 222, "--Not a bug--", "Returning error to test if script does not break MMC"
End Sub
'---------------------------------------------
' Occurs when a context menu for a selection is created
'---------------------------------------------
Dim AppEvent_OnCreateContextMenu_View
Dim AppEvent_OnCreateContextMenu_Nodes
Dim AppEvent_OnCreateContextMenu_Menu
Dim AppEvent_OnCreateContextMenu_IsExpected
Sub AppEvent_OnCreateContextMenu( View, Nodes, Menu )
if Not AppEvent_OnCreateContextMenu_IsExpected Then
ErrorInEvent = True
Err.Raise 100, "AppEvent_OnCreateContextMenu", "Event occured when not expected"
End if
Set AppEvent_OnCreateContextMenu_View = View
Set AppEvent_OnCreateContextMenu_Nodes = Nodes
Set AppEvent_OnCreateContextMenu_Menu = Menu
Err.Raise 222, "--Not a bug--", "Returning error to test if script does not break MMC"
End Sub
'---------------------------------------------
' Occurs when a context menu item is executed
'---------------------------------------------
Dim AppEvent_OnContextMenuExecuted_IsExpected
Sub AppEvent_OnContextMenuExecuted( )
if Not AppEvent_OnContextMenuExecuted_IsExpected Then
ErrorInEvent = True
Err.Raise 100, "AppEvent_OnContextMenuExecuted", "Event occured when not expected"
End if
Err.Raise 222, "--Not a bug--", "Returning error to test if script does not break MMC"
End Sub
'****************************************************************
'* Test Steps
'****************************************************************
'---------------------------------------------
' test step 1: Document open/save/new/close operations
'---------------------------------------------
Sub TestStep1 (app)
WScript.Echo "test step 1: Document operations"
'- - - - - - - - - - - - - - - - - - - - - - -
' save the document
'- - - - - - - - - - - - - - - - - - - - - - -
Dim console_path
console_path = "c:\mmc_test_console.msc"
app.Document.SaveAs console_path
If 0 <> StrComp(app.Document.Name, console_path, 1) Then '**BUGBUG** Or Not app.Document.IsSaved Then
Err.Raise 100, "TestStep1", "Failed save document: " + app.Document.Name
End If
'- - - - - - - - - - - - - - - - - - - - - - -
' close the document
'- - - - - - - - - - - - - - - - - - - - - - -
Dim doc
Set doc = app.Document
Set AppEvent_OnDocumentClose_Document = Nothing
AppEvent_OnDocumentClose_IsExpected = True
AppEvent_OnSelectionChange_IsExpected = True
doc.Close False
AppEvent_OnSelectionChange_IsExpected = False
AppEvent_OnDocumentClose_IsExpected = False
'- - - - - - - - - - - - - - - - - - - - - - -
' see if we've got a close event
'- - - - - - - - - - - - - - - - - - - - - - -
If Not AppEvent_OnDocumentClose_Document Is doc Then
Err.Raise 100, "TestStep1", "Failed to catch close event"
End If
'- - - - - - - - - - - - - - - - - - - - - - -
' create a new document
'- - - - - - - - - - - - - - - - - - - - - - -
Set AppEvent_OnDocumentOpen_Document = Nothing
AppEvent_OnDocumentOpen_IsExpected = True
'**BUGBUG** "No method to create the new document" app.NewDocument
AppEvent_OnDocumentOpen_IsExpected = False
'if doc Is app.Document Then
' Err.Raise 100, "TestStep1", "Failed to create a new document"
'End If
'if Not AppEvent_OnDocumentOpen_Document Is app.Document Then
' Err.Raise 100, "TestStep1", "Failed to catch open event"
'End If
'if Not AppEvent_OnDocumentOpen_bNew then
' Err.Raise 100, "TestStep1", "Document incorrectly reported as loaded from file"
'End If
'- - - - - - - - - - - - - - - - - - - - - - -
' close the document again
'- - - - - - - - - - - - - - - - - - - - - - -
'Set doc = app.Document
'Set AppEvent_OnDocumentClose_Document = Nothing
'AppEvent_OnDocumentClose_IsExpected = True
'doc.Close False
'AppEvent_OnDocumentClose_IsExpected = False
'- - - - - - - - - - - - - - - - - - - - - - -
' see if we've got a close event
'- - - - - - - - - - - - - - - - - - - - - - -
'If Not AppEvent_OnDocumentClose_Document Is doc Then
' Err.Raise 100, "TestStep1", "Failed to catch close event"
'End If
'- - - - - - - - - - - - - - - - - - - - - - -
' open a document
'- - - - - - - - - - - - - - - - - - - - - - -
Set AppEvent_OnDocumentOpen_Document = Nothing
AppEvent_OnDocumentOpen_IsExpected = True
AppEvent_OnSelectionChange_IsExpected = True '**BUGBUG**
AppEvent_OnViewChange_IsExpected = True '**BUGBUG**
AppEvent_OnNewView_IsExpected = True '**BUGBUG**
app.Load console_path
AppEvent_OnNewView_IsExpected = False
AppEvent_OnViewChange_IsExpected = False
AppEvent_OnSelectionChange_IsExpected = False
AppEvent_OnDocumentOpen_IsExpected = False
if doc Is app.Document Then
Err.Raise 100, "TestStep1", "Failed to open a document"
End If
if Not AppEvent_OnDocumentOpen_Document Is app.Document Then
Err.Raise 100, "TestStep1", "Failed to catch open event"
End If
if AppEvent_OnDocumentOpen_Document Is doc Then
Err.Raise 100, "TestStep1", "Wrong document cought in Open event"
End If
if AppEvent_OnDocumentOpen_bNew then
Err.Raise 100, "TestStep1", "Document incorrectly reported as new"
End If
'- - - - - - - - - - - - - - - - - - - - - - -
' small cleanup
'- - - - - - - - - - - - - - - - - - - - - - -
Set AppEvent_OnDocumentClose_Document = Nothing
Set AppEvent_OnDocumentOpen_Document = Nothing
WScript.Echo "test step 1: complete"
End Sub
'---------------------------------------------
' test step 2: Snapin add/remove operations
'---------------------------------------------
Sub TestStep2 (app)
WScript.Echo "test step 2: Snapin operations"
'- - - - - - - - - - - - - - - - - - - - - - -
' add the snapin
'- - - - - - - - - - - - - - - - - - - - - - -
Set AppEvent_OnSnapInAdded_Document = Nothing
Set AppEvent_OnSnapInAdded_SnapIn = Nothing
Dim FolderSnapin
FolderSnapin = "{C96401CC-0E17-11D3-885B-00C04F72C717}"
Dim Snapin1
AppEvent_OnSnapInAdded_IsExpected = True
AppEvent_OnSelectionChange_IsExpected = True '**BUGBUG**
AppEvent_OnViewChange_IsExpected = True '**BUGBUG**
set Snapin1 = app.Document.Snapins.Add(FolderSnapin)
AppEvent_OnViewChange_IsExpected = False
AppEvent_OnSelectionChange_IsExpected = False
AppEvent_OnSnapInAdded_IsExpected = False
if IsNull(Snapin1) Then
Err.Raise 100, "TestStep2", "Failed to create snapin"
End If
if Not AppEvent_OnSnapInAdded_Document is app.Document Or Not AppEvent_OnSnapInAdded_SnapIn Is Snapin1 Then
Err.Raise 100, "TestStep2", "Failed to catch AddSnapin event"
End If
'- - - - - - - - - - - - - - - - - - - - - - -
' add the snapin #2
'- - - - - - - - - - - - - - - - - - - - - - -
Set AppEvent_OnSnapInAdded_Document = Nothing
Set AppEvent_OnSnapInAdded_SnapIn = Nothing
Dim Snapin2
AppEvent_OnSnapInAdded_IsExpected = True
AppEvent_OnSelectionChange_IsExpected = True '**BUGBUG**
AppEvent_OnViewChange_IsExpected = True '**BUGBUG**
set Snapin2 = app.Document.Snapins.Add(FolderSnapin) '**BUGBUG** Snapin1) ' as child of Snapin1
AppEvent_OnViewChange_IsExpected = False
AppEvent_OnSelectionChange_IsExpected = False
AppEvent_OnSnapInAdded_IsExpected = False
if IsNull(Snapin2) Then
Err.Raise 100, "TestStep2", "Failed to create snapin #2"
End If
if Not AppEvent_OnSnapInAdded_Document is app.Document Or Not AppEvent_OnSnapInAdded_SnapIn Is Snapin2 Then
Err.Raise 100, "TestStep2", "Failed to catch AddSnapin #2 event"
End If
'- - - - - - - - - - - - - - - - - - - - - - -
' remove the snapin #2
'- - - - - - - - - - - - - - - - - - - - - - -
Set AppEvent_OnSnapInRemoved_Document = Nothing
Set AppEvent_OnSnapInRemoved_SnapIn = Nothing
AppEvent_OnSnapInRemoved_IsExpected = True
AppEvent_OnSelectionChange_IsExpected = True '**BUGBUG**
AppEvent_OnViewChange_IsExpected = True '**BUGBUG**
app.Document.Snapins.Remove Snapin2
AppEvent_OnViewChange_IsExpected = False
AppEvent_OnSelectionChange_IsExpected = False
AppEvent_OnSnapInRemoved_IsExpected = False
if Not AppEvent_OnSnapInRemoved_Document is app.Document Or Not AppEvent_OnSnapInRemoved_SnapIn Is Snapin2 Then
Err.Raise 100, "TestStep2", "Failed to catch RemoveSnapin #2 event"
End If
set Snapin2 = Nothing
'- - - - - - - - - - - - - - - - - - - - - - -
' remove the snapin #1
'- - - - - - - - - - - - - - - - - - - - - - -
Set AppEvent_OnSnapInRemoved_Document = Nothing
Set AppEvent_OnSnapInRemoved_SnapIn = Nothing
AppEvent_OnSnapInRemoved_IsExpected = True
AppEvent_OnSelectionChange_IsExpected = True '**BUGBUG**
AppEvent_OnViewChange_IsExpected = True '**BUGBUG**
app.Document.Snapins.Remove Snapin1
AppEvent_OnViewChange_IsExpected = False
AppEvent_OnSelectionChange_IsExpected = False
AppEvent_OnSnapInRemoved_IsExpected = False
if Not AppEvent_OnSnapInRemoved_Document is app.Document Or Not AppEvent_OnSnapInRemoved_SnapIn Is Snapin1 Then
Err.Raise 100, "TestStep2", "Failed to catch RemoveSnapin event"
End If
'- - - - - - - - - - - - - - - - - - - - - - -
' re-add them to have test something to run test on
'- - - - - - - - - - - - - - - - - - - - - - -
AppEvent_OnSnapInAdded_IsExpected = True
AppEvent_OnSelectionChange_IsExpected = True '**BUGBUG**
AppEvent_OnViewChange_IsExpected = True '**BUGBUG**
set Snapin1 = app.Document.Snapins.Add(FolderSnapin)
set Snapin2 = app.Document.Snapins.Add(FolderSnapin) '**BUGBUG** Snapin1) ' as child of Snapin1
AppEvent_OnViewChange_IsExpected = False
AppEvent_OnSelectionChange_IsExpected = False
AppEvent_OnSnapInAdded_IsExpected = False
set Snapin1 = Nothing
set Snapin2 = Nothing
Set AppEvent_OnSnapInRemoved_Document = Nothing
Set AppEvent_OnSnapInRemoved_SnapIn = Nothing
Set AppEvent_OnSnapInAdded_Document = Nothing
Set AppEvent_OnSnapInAdded_SnapIn = Nothing
WScript.Echo "test step 2: complete"
End Sub
'---------------------------------------------
' test step 3: View open/close operations
'---------------------------------------------
Sub TestStep3 (app)
WScript.Echo "test step 3: View operations"
'- - - - - - - - - - - - - - - - - - - - - - -
' add the new view
'- - - - - - - - - - - - - - - - - - - - - - -
Set AppEvent_OnNewView_View = Nothing
dim child
set child = app.Document.ScopeNamespace.GetChild(app.Document.ScopeNamespace.GetRoot)
'**BUGBUG** app.Document.Views.Add app.Document.ScopeNamespace.GetChild(child)
AppEvent_OnNewView_IsExpected = True
AppEvent_OnSelectionChange_IsExpected = True '**BUGBUG**
AppEvent_OnViewChange_IsExpected = True '**BUGBUG**
app.Document.Views.Add app.Document.ScopeNamespace.GetNext(child)
AppEvent_OnViewChange_IsExpected = False
AppEvent_OnSelectionChange_IsExpected = False
AppEvent_OnNewView_IsExpected = False
'- - - - - - - - - - - - - - - - - - - - - - -
' see if we've got an event
'- - - - - - - - - - - - - - - - - - - - - - -
if Not AppEvent_OnNewView_View is app.Document.Views(2) Then
Err.Raise 100, "TestStep3", "Failed to catch NewView event"
End If
'- - - - - - - - - - - - - - - - - - - - - - -
' close the view
'- - - - - - - - - - - - - - - - - - - - - - -
Set AppEvent_OnViewClose_View = Nothing
AppEvent_OnViewClose_IsExpected = True
AppEvent_OnSelectionChange_IsExpected = True '**BUGBUG**
AppEvent_OnNewView_View.Close
AppEvent_OnSelectionChange_IsExpected = False
AppEvent_OnViewClose_IsExpected = False
if Not AppEvent_OnNewView_View is AppEvent_OnViewClose_View Then
Err.Raise 100, "TestStep3", "Failed to catch CloseView event"
End If
Set AppEvent_OnViewClose_View = Nothing
Set AppEvent_OnNewView_View = Nothing
WScript.Echo "test step 3: complete"
End Sub
'---------------------------------------------
' test step final:
'---------------------------------------------
Sub TestStepFinal (app)
WScript.Echo "test step final: Closing MMC"
'- - - - - - - - - - - - - - - - - - - - - - -
' close the application
'- - - - - - - - - - - - - - - - - - - - - - -
Set AppEvent_OnQuit_Application = Nothing
AppEvent_OnDocumentClose_IsExpected = True
AppEvent_OnQuit_IsExpected = True
AppEvent_OnSelectionChange_IsExpected = True '**BUGBUG**
app.Quit
AppEvent_OnSelectionChange_IsExpected = False
AppEvent_OnQuit_IsExpected = False
AppEvent_OnDocumentClose_IsExpected = False
'- - - - - - - - - - - - - - - - - - - - - - -
' see if we've got a close event
'- - - - - - - - - - - - - - - - - - - - - - -
If Not AppEvent_OnQuit_Application Is app Then
Err.Raise 100, "TestStepFinal", "Failed to catch application close event"
End If
Set AppEvent_OnQuit_Application = Nothing
WScript.Echo "test step final: complete"
End Sub
'****************************************************************
'* Main
'****************************************************************
Sub main
WScript.Echo "Starting test pass for MMC events."
AppEvent_OnQuit_IsExpected = False
AppEvent_OnDocumentOpen_IsExpected = False
AppEvent_OnDocumentClose_IsExpected = False
AppEvent_OnSnapInAdded_IsExpected = False
AppEvent_OnSnapInRemoved_IsExpected = False
AppEvent_OnNewView_IsExpected = False
AppEvent_OnViewClose_IsExpected = False
AppEvent_OnViewChange_IsExpected = False
AppEvent_OnSelectionChange_IsExpected = False
AppEvent_OnCreateContextMenu_IsExpected = False
AppEvent_OnContextMenuExecuted_IsExpected = False
'- - - - - - - - - - - - - - - - - - - - - - -
' start mmc
'- - - - - - - - - - - - - - - - - - - - - - -
Dim mmc
set mmc = wscript.CreateObject("MMC20.Application")
'- - - - - - - - - - - - - - - - - - - - - - -
' connect objects to events
'- - - - - - - - - - - - - - - - - - - - - - -
wscript.ConnectObject mmc , "AppEvent_"
'- - - - - - - - - - - - - - - - - - - - - - -
' persform testing...
'- - - - - - - - - - - - - - - - - - - - - - -
TestStep1 mmc
If ErrorInEvent Then
Err.Raise 100, "Test", "Failed due to error in event handler"
End If
TestStep2 mmc
If ErrorInEvent Then
Err.Raise 100, "Test", "Failed due to error in event handler"
End If
TestStep3 mmc
If ErrorInEvent Then
Err.Raise 100, "Test", "Failed due to error in event handler"
End If
'**commented to test exit on releasing all refs** TestStepFinal mmc
If ErrorInEvent Then
Err.Raise 100, "Test", "Failed due to error in event handler"
End If
WScript.Echo ""
WScript.Echo "Test pass completed without errors"
WScript.Echo ""
'- - - - - - - - - - - - - - - - - - - - - - -
' take a nap
'- - - - - - - - - - - - - - - - - - - - - - -
wscript.sleep 500
'- - - - - - - - - - - - - - - - - - - - - - -
' cleanup
'- - - - - - - - - - - - - - - - - - - - - - -
Set mmc = Nothing
Set AppEvent_OnQuit_Application = Nothing
Set AppEvent_OnDocumentOpen_Document = Nothing
Set AppEvent_OnDocumentOpen_bNew = Nothing
Set AppEvent_OnDocumentClose_Document = Nothing
Set AppEvent_OnSnapInAdded_Document = Nothing
Set AppEvent_OnSnapInAdded_SnapIn = Nothing
Set AppEvent_OnSnapInRemoved_Document = Nothing
Set AppEvent_OnSnapInRemoved_SnapIn = Nothing
Set AppEvent_OnNewView_View = Nothing
Set AppEvent_OnViewClose_View = Nothing
Set AppEvent_OnViewChange_View = Nothing
Set AppEvent_OnViewChange_NewOwnerNode = Nothing
Set AppEvent_OnSelectionChange_View = Nothing
Set AppEvent_OnSelectionChange_NewNodes = Nothing
Set AppEvent_OnCreateContextMenu_View = Nothing
Set AppEvent_OnCreateContextMenu_Nodes = Nothing
Set AppEvent_OnCreateContextMenu_Menu = Nothing
End Sub
'---------------------------------------------
' startup: call main
'---------------------------------------------
main
|
Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean
'Returns true if the observed frequencies pass the Pearson Chi-squared test at the required significance level.
Dim Total As Long, Ei As Long, i As Integer
Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double
Debug.Print "[1] ""Data set:"" ";
For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
Total = Total + ObservationFrequencies(i)
Debug.Print ObservationFrequencies(i); " ";
Next i
DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)
'This is exactly the number of different categories minus 1
Ei = Total / (DegreesOfFreedom + 1)
For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei
Next i
p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)
Debug.Print
Debug.Print "Chi-squared test for given frequencies"
Debug.Print "X-squared ="; Format(ChiSquared, "0.0000"); ", ";
Debug.Print "df ="; DegreesOfFreedom; ", ";
Debug.Print "p-value = "; Format(p_value, "0.0000")
Test4DiscreteUniformDistribution = p_value > Significance
End Function
Private Function Dice5() As Integer
Dice5 = Int(5 * Rnd + 1)
End Function
Private Function Dice7() As Integer
Dim i As Integer
Do
i = 5 * (Dice5 - 1) + Dice5
Loop While i > 21
Dice7 = i Mod 7 + 1
End Function
Sub TestDice7()
Dim i As Long, roll As Integer
Dim Bins(1 To 7) As Variant
For i = 1 To 1000000
roll = Dice7
Bins(roll) = Bins(roll) + 1
Next i
Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(Bins, 0.05); """"
End Sub
|
'***************************************************************************
'This script tests the enumeration of subclasses
'***************************************************************************
On Error Resume Next
Dim objLocator
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
' Replace the first argument to this function with the URL of your WMI XML/HTTP
server
' For the local machine, use the URL as below
Dim objService
Set objService = objLocator.ConnectServer("[http://localhost/cimom]", "root\cimv2")
if err <> 0 then
WScript.Echo ErrNumber, Err.Source, Err.Description
else
WScript.Echo "ConnectServer Succeeded"
end if
Set parentClass = objService.Get("")
if err <> 0 then
WScript.Echo ErrNumber, Err.Source, Err.Description
else
WScript.Echo "Get Succeeded"
end if
Set DiskSubclass = parentClass.SpawnDerivedClass_()
'Set the name of the subclass
DiskSubClass.Path_.Class = "NewClass4"
'Add a property to the subclass
Set NewProperty = DiskSubClass.Properties_.Add ("MyNewProperty", 19)
NewProperty.Value = 12
'Persist the subclass in CIMOM
DiskSubclass.Put_ ()
if Err <> 0 Then
WScript.Echo Err.Description
Err.Clear
End if
|
<filename>inetsrv/iis/utils/vbme/frmdata.frm
VERSION 5.00
Begin VB.Form frmMetaData
Caption = "Edit"
ClientHeight = 4650
ClientLeft = 60
ClientTop = 345
ClientWidth = 5940
LinkTopic = "Form1"
ScaleHeight = 4650
ScaleWidth = 5940
StartUpPosition = 3 'Windows Default
Begin VB.CommandButton Cancel
Cancel = -1 'True
Caption = "Cancel"
Height = 495
Left = 4560
TabIndex = 17
Top = 4080
Width = 1095
End
Begin VB.CommandButton OK
Caption = "OK"
Default = -1 'True
Height = 495
Left = 3120
TabIndex = 16
Top = 4080
Width = 1095
End
Begin VB.CheckBox CheckRefAttr
Caption = "By Reference"
Height = 375
Left = 2760
TabIndex = 15
Top = 1920
Width = 3255
End
Begin VB.CheckBox CheckSecureAttr
Caption = "Secure"
Height = 375
Left = 2760
TabIndex = 14
Top = 1440
Width = 3255
End
Begin VB.CheckBox CheckInheritAttr
Caption = "Inherited"
Height = 375
Left = 2760
TabIndex = 13
Top = 960
Width = 3015
End
Begin VB.TextBox UserTypeLabel
Height = 375
Left = 3600
TabIndex = 11
Text = "Text3"
Top = 360
Width = 2295
End
Begin VB.TextBox StringLabel
Height = 375
Left = 720
TabIndex = 9
Text = "Text1"
Top = 2880
Width = 5055
End
Begin VB.TextBox DwordHexLabel
Enabled = 0 'False
Height = 375
Left = 720
TabIndex = 5
Text = "Text2"
Top = 3600
Width = 2295
End
Begin VB.TextBox DwordDecLabel
Height = 375
Left = 720
TabIndex = 4
Text = "Text1"
Top = 2880
Width = 2295
End
Begin VB.OptionButton RadioBinary
Caption = "Binary"
Enabled = 0 'False
Height = 375
Left = 360
TabIndex = 3
Top = 2160
Width = 1935
End
Begin VB.OptionButton RadioMultiSz
Caption = "Multi-String"
Enabled = 0 'False
Height = 375
Left = 360
TabIndex = 2
Top = 1680
Width = 1935
End
Begin VB.OptionButton RadioString
Caption = "String"
Enabled = 0 'False
Height = 375
Left = 360
TabIndex = 1
Top = 1200
Width = 1935
End
Begin VB.OptionButton RadioDword
Caption = "DWORD"
Enabled = 0 'False
Height = 375
Left = 360
TabIndex = 0
Top = 720
Width = 1935
End
Begin VB.Frame Frame1
Caption = "Data Type"
Height = 2415
Left = 120
TabIndex = 10
Top = 240
Width = 2415
End
Begin VB.Label LabelUserType
Caption = "User Type"
Height = 375
Left = 2760
TabIndex = 12
Top = 360
Width = 1215
End
Begin VB.Label LabelString
Caption = "String"
Height = 255
Left = 120
TabIndex = 8
Top = 2880
Width = 855
End
Begin VB.Label LabelHex
Caption = "Hex"
Height = 375
Left = 120
TabIndex = 7
Top = 3600
Width = 615
End
Begin VB.Label LabelDecimal
Caption = "Decimal"
Height = 255
Left = 120
TabIndex = 6
Top = 2880
Width = 615
End
End
Attribute VB_Name = "frmMetaData"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Private Path As String ' Path of the item
Private ID As Long ' Metabase property ID
Option Explicit
Public Sub SetData(strPath As String, strItem As String)
Dim mb As IMSMetaBase
Set mb = CreateObject("IISAdmin.Object")
Dim key As IMSMetaKey
Dim NewHandle As Long
Dim NullPath() As Byte
Dim bytePath() As Byte
Dim MetaData As IMSMetaDataItem
Dim NewDataValue As Long
ID = Val(strItem)
Path = strPath
' Open the selected node
NullPath = StrConv("" & Chr(0), vbFromUnicode)
Debug.Print ("Showing " & strPath)
Err.Clear
bytePath = StrConv(strPath & Chr(0), vbFromUnicode)
Set key = mb.OpenKey(1, 100, bytePath)
Set MetaData = key.DataItem
If (Err.Number <> 0) Then
Debug.Print ("Open Meta Object Error Code = " & Err.Number)
Err.Clear
Exit Sub
End If
' Enumerate the properties on this node
MetaData.UserType = 0
MetaData.DataType = 0
MetaData.Attributes = 0
MetaData.Identifier = ID
key.GetData MetaData
'mb.AutoADMGetMetaData NewHandle, NullPath, MetaData
If (Err.Number <> 0) Then
MsgBox "GetMetaData Error Code = " & Err.Number & " (" & Err.Description & ")"
Err.Clear
GoTo CloseMb
End If
strItem = MetaData.Identifier
' Add the user type
If (MetaData.UserType = 1) Then
UserTypeLabel.Text = "IIS_MD_UT_SERVER"
ElseIf (MetaData.UserType = 2) Then
UserTypeLabel.Text = "IIS_MD_UT_FILE"
Else
UserTypeLabel.Text = Str(MetaData.UserType)
End If
' Do the appropriate datatype conversion
NewDataValue = MetaData.DataType
If (NewDataValue = 1) Then
RadioDword.Value = True
DwordDecLabel.Text = MetaData.Value
DwordHexLabel.Text = Hex(MetaData.Value)
' Hide the string control and move it to the back
LabelString.Visible = False
StringLabel.Visible = False
LabelString.ZOrder (1)
ElseIf (NewDataValue = 2) Then
Dim j As Long
Dim tmpStr As String
RadioString.Value = True
j = 0
tmpStr = ""
Do While (MetaData.Value(j) <> 0)
tmpStr = tmpStr & Chr(MetaData.Value(j))
j = j + 1
Loop
StringLabel.Text = tmpStr
' Hide the DWORD controls
DwordDecLabel.Visible = False
DwordDecLabel.ZOrder (1)
LabelDecimal.ZOrder (1)
DwordHexLabel.Visible = False
LabelHex.Visible = False
LabelDecimal.Visible = False
End If
' Set the attributes checkboxes
If MetaData.Attributes And 1 Then
CheckInheritAttr.Value = Checked
Else
CheckInheritAttr.Value = Unchecked
End If
If MetaData.Attributes And 4 Then
CheckSecureAttr.Value = Checked
Else
CheckSecureAttr.Value = Unchecked
End If
If MetaData.Attributes And 8 Then
CheckRefAttr.Value = Checked
Else
CheckRefAttr.Value = Unchecked
End If
CloseMb:
End Sub
Private Sub Cancel_Click()
Unload Me
End Sub
Private Sub OK_Click()
Dim mb As MSAdmin
Set mb = CreateObject("IISAdmin.Object")
Dim key As IMSMetaKey
Dim NewHandle As Long
Dim NullPath() As Byte
Dim bytePath() As Byte
Dim MetaData As IMSMetaDataItem
Dim NewDataValue As Long
' Open the selected node
NullPath = StrConv("" & Chr(0), vbFromUnicode)
Err.Clear
bytePath = StrConv(Path & Chr(0), vbFromUnicode)
Set key = mb.OpenKey(2, , bytePath)
If (Err.Number <> 0) Then
Debug.Print ("Open Meta Object Error Code = " & Err.Number)
Err.Clear
Exit Sub
End If
Set MetaData = key.DataItem
MetaData.Identifier = ID
' Add the user type
If (UserTypeLabel.Text = "IIS_MD_UT_SERVER") Then
MetaData.UserType = 1
ElseIf UserTypeLabel.Text = "IIS_MD_UT_FILE" Then
MetaData.UserType = 2
Else
MetaData.UserType = Val(UserTypeLabel.Text)
End If
' Do the appropriate datatype conversion
Dim Value As Long
If (RadioDword.Value = True) Then
MetaData.DataType = 1
Value = Val(DwordDecLabel.Text)
MetaData.Value = Value 'Val(DwordDecLabel.Text)
ElseIf (RadioString.Value = True) Then
bytePath = StrConv(StringLabel.Text & Chr(0), vbFromUnicode)
MetaData.DataType = 2
MetaData.Value = bytePath
Else
MsgBox ("Type is not supported")
End If
' Set the attributes checkboxes
MetaData.Attributes = 0
If (CheckInheritAttr.Value = Checked) Then
MetaData.Attributes = MetaData.Attributes + 1
End If
If (CheckSecureAttr.Value = Checked) Then
MetaData.Attributes = MetaData.Attributes + 4
End If
If (CheckRefAttr.Value = Checked) Then
MetaData.Attributes = MetaData.Attributes + 8
End If
key.SetData MetaData
If (Err.Number <> 0) Then
MsgBox "GetMetaData Error Code = " & Err.Number & " (" & Err.Description & ")"
Err.Clear
GoTo CloseMb
End If
CloseMb:
Unload Me
' Refresh the listbox and dismiss the dialog
End Sub
|
Option Explicit
Dim objFSO, DBSource
Set objFSO = CreateObject("Scripting.FileSystemObject")
DBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\postal_address.accdb"
With CreateObject("ADODB.Connection")
.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBSource
.Execute "CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL," &_
"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)"
.Close
End With
|
Public x As TinyInt
Private Sub Form_Click()
'0-11, to give chance of errors; also not integers, because VB massages data to fit, if possible.
x = Rnd * 12
Me.Print x
End Sub
Private Sub Form_Load()
Randomize Timer
Set x = New TinyInt '"Set = New" REQUIRED
End Sub
|
dead dead dead
|
<reponame>mullikine/RosettaCodeData<filename>Task/Higher-order-functions/VBA/higher-order-functions.vba<gh_stars>1-10
Sub HigherOrder()
Dim result As Single
result = first("second")
MsgBox result
End Sub
Function first(f As String) As Single
first = Application.Run(f, 1) + 2
End Function
Function second(x As Single) As Single
second = x / 2
End Function
|
<filename>admin/pchealth/authtools/prodtools/authdatabase/globals.bas
Attribute VB_Name = "Globals"
Option Explicit
Public g_cnn As ADODB.Connection
Public g_clsParameters As Parameters
Public g_strUserName As String
Public Enum LOCK_TABLE_E
LOCK_TABLE_KEYWORDS = 1
LOCK_TABLE_STOP_SIGNS = 2
LOCK_TABLE_STOP_WORDS = 3
LOCK_TABLE_SYNONYMS = 4
LOCK_TABLE_SYNONYM_SETS = 5
LOCK_TABLE_TAXONOMY = 6
LOCK_TABLE_TYPES = 7
End Enum
Public Sub CheckDatabaseVersion( _
)
Dim strVersion1 As String
Dim strVersion2 As String
strVersion1 = g_clsParameters.Value(DB_VERSION_C) & ""
strVersion2 = App.Major & "." & App.Minor
If (strVersion1 <> strVersion2) Then
Err.Raise errDatabaseVersionIncompatible
End If
End Sub
Public Sub CheckAuthoringGroupAccess( _
)
Dim intAG As Long
intAG = g_clsParameters.AuthoringGroup
If (intAG > AG_CORE_MAX_C) Then
Err.Raise errNotPermittedForAuthoringGroup
End If
End Sub
Public Sub CheckForSameAuthoringGroup( _
ByVal i_intAG As Long, _
Optional ByVal i_intAuthoringGroup As Long = INVALID_ID_C _
)
Dim intAG As Long
If (i_intAuthoringGroup = INVALID_ID_C) Then
intAG = g_clsParameters.AuthoringGroup
Else
intAG = i_intAuthoringGroup
End If
If (intAG <> i_intAG) Then
Err.Raise errAuthoringGroupDiffers
End If
End Sub
Private Function p_NewerDatabase( _
ByVal i_strVersion As String _
) As Boolean
Dim arrVersion() As String
arrVersion = Split(i_strVersion, ".")
If (arrVersion(0) < App.Major) Then
p_NewerDatabase = False
ElseIf (arrVersion(0) > App.Major) Then
p_NewerDatabase = True
ElseIf (arrVersion(1) < App.Minor) Then
p_NewerDatabase = False
ElseIf (arrVersion(1) > App.Minor) Then
p_NewerDatabase = True
Else
p_NewerDatabase = False
End If
End Function
' If you wish to modify the Taxonomy table, call LockTable(LOCK_TABLE_TAXONOMY, rs)
' at the beginning of the function. If this convention is always followed, then
' functions that just read the Taxonomy table will succeed. But those that modify
' the Taxonomy table (and hence call LockTable) will throw an exception (E_FAIL).
' When rs goes out of scope in the calling function, the lock is released. If the
' process is killed, then also the lock is released.
' It may be sufficient to call this function in only the Public functions of a
' module. However, then we have to worry about whether the Public function or any
' of its descendents will ever modify the database.
' Be very careful with functions like Keywords.Delete, which modify 2 tables:
' Keywords and Synonyms.
' Do a findstr LockTable * in the Authdatabase directory to make sure that you don't
' call LockTable(A) and LockTable(B), when both should have locked table A.
Public Sub LockTable( _
ByVal i_enumTable As LOCK_TABLE_E, _
ByRef o_rs As ADODB.Recordset _
)
Dim strQuery As String
Dim strTable As String
Set o_rs = New ADODB.Recordset
Select Case i_enumTable
Case LOCK_TABLE_KEYWORDS
strTable = LOCK_KEYWORDS_C
Case LOCK_TABLE_STOP_SIGNS
strTable = LOCK_STOP_SIGNS_C
Case LOCK_TABLE_STOP_WORDS
strTable = LOCK_STOP_WORDS_C
Case LOCK_TABLE_SYNONYMS
strTable = LOCK_SYNONYMS_C
Case LOCK_TABLE_SYNONYM_SETS
strTable = LOCK_SYNONYM_SETS_C
Case LOCK_TABLE_TAXONOMY
strTable = LOCK_TAXONOMY_C
Case LOCK_TYPES_C
strTable = LOCK_TYPES_C
End Select
strQuery = "SELECT * FROM DBParameters WHERE (Name = """ & strTable & """)"
o_rs.Open strQuery, g_cnn, adOpenStatic, adLockPessimistic
o_rs("Value") = True
End Sub
|
<gh_stars>10-100
'******************************************************************************
'
' THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
' WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
'
' Copyright (C) 1999- 2002. Microsoft Corporation. All rights reserved.
'
'******************************************************************************
'
' CStore.vbs
'
' This is a sample script to illustrate how to use the CAPICOM's Store and
' Certificate objects to manage certificate(s) in a specified store with
' filtering options.
'
' Note: For simplicity, this script does not handle exception.
'
'******************************************************************************
Option Explicit
' Command.
Const Unknown = 0
Const View = 1
Const Import = 2
Const Export = 3
Const Delete = 4
Const Archive = 5
Const Activate = 6
' Verbose level.
Const Normal = 0
Const Detail = 1
Const UI = 2
' CAPICOM constants.
Const CAPICOM_MEMORY_STORE = 0
Const CAPICOM_LOCAL_MACHINE_STORE = 1
Const CAPICOM_CURRENT_USER_STORE = 2
Const CAPICOM_ACTIVE_DIRECTORY_USER_STORE = 3
Const CAPICOM_SMART_CARD_USER_STORE = 4
Const CAPICOM_STORE_OPEN_READ_ONLY = 0
Const CAPICOM_STORE_OPEN_READ_WRITE = 1
Const CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED = 2
Const CAPICOM_STORE_OPEN_EXISTING_ONLY = 128
Const CAPICOM_STORE_OPEN_INCLUDE_ARCHIVED = 256
Const CAPICOM_CERTIFICATE_FIND_SHA1_HASH = 0
Const CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME = 1
Const CAPICOM_CERTIFICATE_FIND_ISSUER_NAME = 2
Const CAPICOM_CERTIFICATE_FIND_ROOT_NAME = 3
Const CAPICOM_CERTIFICATE_FIND_TEMPLATE_NAME = 4
Const CAPICOM_CERTIFICATE_FIND_EXTENSION = 5
Const CAPICOM_CERTIFICATE_FIND_EXTENDED_PROPERTY = 6
Const CAPICOM_CERTIFICATE_FIND_APPLICATION_POLICY = 7
Const CAPICOM_CERTIFICATE_FIND_CERTIFICATE_POLICY = 8
Const CAPICOM_CERTIFICATE_FIND_TIME_VALID = 9
Const CAPICOM_CERTIFICATE_FIND_TIME_NOT_YET_VALID = 10
Const CAPICOM_CERTIFICATE_FIND_TIME_EXPIRED = 11
Const CAPICOM_CERTIFICATE_FIND_KEY_USAGE = 12
Const CAPICOM_KEY_STORAGE_DEFAULT = 0
Const CAPICOM_KEY_STORAGE_EXPORTABLE = 1
Const CAPICOM_KEY_STORAGE_USER_PROTECTED = 2
Const CAPICOM_STORE_SAVE_AS_SERIALIZED = 0
Const CAPICOM_STORE_SAVE_AS_PKCS7 = 1
Const CAPICOM_STORE_SAVE_AS_PFX = 2
Const CAPICOM_EXPORT_DEFAULT = 0
Const CAPICOM_EXPORT_IGNORE_PRIVATE_KEY_NOT_EXPORTABLE_ERROR = 1
' Globlas.
Dim StoreLocationNames(4)
StoreLocationNames(0) = "Certificate File"
StoreLocationNames(1) = "Local Machine"
StoreLocationNames(2) = "Current User"
StoreLocationNames(3) = "Active Directory"
StoreLocationNames(4) = "Smart Card"
' Command line arguments.
Dim Command : Command = Unknown
Dim OpenMode : OpenMode = CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED OR CAPICOM_STORE_OPEN_EXISTING_ONLY
Dim StoreLocation : StoreLocation = NULL
Dim StoreName : StoreName = "MY"
Dim CertFile : CertFile = Null
Dim Password : Password = ""
Dim SaveAs : SaveAs = CAPICOM_STORE_SAVE_AS_SERIALIZED
Dim ExportFlag : ExportFlag = CAPICOM_EXPORT_DEFAULT
Dim ValidOnly : ValidOnly = False
Dim DelKey : DelKey = False
Dim KeyStorageFlag : KeyStorageFlag = CAPICOM_KEY_STORAGE_DEFAULT
Dim NoPrompt : NoPrompt = False
Dim VerboseLevel : VerboseLevel = Normal
Dim ExtendedHelp : ExtendedHelp = False
' Filters (some can be multiples).
Dim SHA1 : SHA1 = Null
Dim Subjects()
Dim Issuers()
Dim Roots()
Dim Templates()
Dim Extensions()
Dim Properties()
Dim Usages()
Dim Policies()
Dim Times()
Dim KeyUsages()
' Parse the command line.
ParseCommandLine
' Open the store.
Dim Store
Set Store = CreateObject("CAPICOM.Store")
Store.Open StoreLocation, StoreName, OpenMode
' Carry out the requested command.
Select Case Command
Case View
DoViewCommand
Case Import
DoImportCommand
Case Export
DoExportCommand
Case Delete
DoDeleteCommand
Case Archive
DoArchiveCommand
Case Activate
DoActivateCommand
Case Else
' This can't happen!
Wscript.Stdout.Writeline "Internal script error: Unknown command state (Command = " & CStr(Command) & ")."
Wscript.Quit(-2)
End Select
' Free resources.
Set Store = Nothing
' We are all done.
WScript.Quit(0)
' End Main
'******************************************************************************
'
' Subroutine: DoViewCommand
'
' Synopsis : View certificates of a store or certificate file.
'
' Parameter : None
'
'******************************************************************************
Sub DoViewCommand
Dim Certificate
Dim Certificates
Dim cIndex : cIndex = 0
' Load the specified certificate file if specified.
If Not IsNull(CertFile) Then
Store.Load CertFile, Password, CAPICOM_KEY_STORAGE_DEFAULT
End If
' Perform filter(s) requested.
Set Certificates = FilterCertificates(Store.Certificates)
' Display main title.
Dim cCerts : cCerts = Certificates.Count
WScript.StdOut.Writeline "Viewing " & StoreLocationNames(StoreLocation) & " " & StoreName & " store - " & CStr(cCerts) & " certificate(s)"
WScript.StdOut.Writeline
' Now display all the certificates.
For Each Certificate In Certificates
cIndex = cIndex + 1
DisplayCertificate Certificate, "=== Certificate " & CStr(cIndex) & " of " & CStr(cCerts) & " ==="
Next
' Free resources.
Set Certificates = Nothing
End Sub ' End DoViewCommand
'******************************************************************************
'
' Subroutine: DoImportCommand
'
' Synopsis : Import certificates from a certificate file to store.
'
' Parameter :
'
'******************************************************************************
Sub DoImportCommand
Dim Certificate
Dim Certificates
' Display main title.
Wscript.Stdout.Writeline "Importing " & CertFile & " to " & StoreLocationNames(StoreLocation) & " " & StoreName & " store, please wait..."
Wscript.Stdout.Writeline
' Take a snapshot of the current certificates colletion.
Set Certificates = Store.Certificates
' Import the certificate(s) to the store.
Store.Load CertFile, Password, KeyStorageFlag
' Now display all imported certificates.
Dim cIndex : cIndex = 0
For Each Certificate In Store.Certificates
' Try to find this certificate in the snapshot we grabbed previously.
Dim FoundCerts
Set FoundCerts = Certificates.Find(CAPICOM_CERTIFICATE_FIND_SHA1_HASH, Certificate.Thumbprint)
' Skip it if we were able to find it, which means not added by us.
If FoundCerts.Count = 0 Then
' Display the imported certificate.
cIndex = cIndex + 1
DisplayCertificate Certificate, "=== Certificate " & CStr(cIndex) & " ==="
End If
Set FoundCerts = Nothing
Next
' Display total certificates(s) imported.
Wscript.Stdout.Writeline CStr(cIndex) & " certificate(s) successfully imported."
' Free resources.
Set Certificates = Nothing
End Sub ' End DoImportCommand
'******************************************************************************
'
' Subroutine: DoExportCommand
'
' Synopsis : Export certificates from a store to certificate file.
'
' Parameter : None.
'
'******************************************************************************
Sub DoExportCommand
Dim Certificate
Dim Certificates
Dim cIndex : cIndex = 0
' Perform filter(s) requested.
Set Certificates = FilterCertificates(Store.Certificates)
' Display main title.
Dim cCerts : cCerts = Certificates.Count
Wscript.Stdout.Writeline "Exporting from " & StoreLocationNames(StoreLocation) & " " & StoreName & " store to " & CertFile & ", please wait..."
Wscript.Stdout.Writeline
' Save the certificate(s) to file.
If Certificates.Count > 0 Then
Certificates.Save CertFile, Password, SaveAs, ExportFlag
' Now display all exported certificates.
For Each Certificate In Certificates
cIndex = cIndex + 1
DisplayCertificate Certificate, "=== Certificate " & CStr(cIndex) & " of " & CStr(cCerts) & " ==="
Next
End If
' Display total certificates(s) exported.
Wscript.Stdout.Writeline CStr(cCerts) & " certificate(s) successfully exported."
' Free resources.
Set Certificates = Nothing
End Sub ' End DoExportCommand
'******************************************************************************
'
' Subroutine: DoDeleteCommand
'
' Synopsis : Delete certificates from a store.
'
' Parameter : None
'
'******************************************************************************
Sub DoDeleteCommand
Dim Certificate
Dim Certificates
Dim cIndex : cIndex = 0
Dim cDeleted : cDeleted = 0
' Perform filter(s) requested.
Set Certificates = FilterCertificates(Store.Certificates)
' Display main title.
Dim cCerts : cCerts = Certificates.Count
WScript.StdOut.Writeline "Deleting " & StoreLocationNames(StoreLocation) & " " & StoreName & " store, please wait... "
WScript.StdOut.Writeline
' Now delete all certificates(s).
For Each Certificate In Certificates
cIndex = cIndex + 1
' Display certificate to be deleted.
DisplayCertificate Certificate, "=== Certificate " & CStr(cIndex) & " of " & CStr(cCerts) & " ==="
' Prompt user for permission.
If DelKey Then
If UserAgreed("Delete this certificate and its key container (No/Yes/All)? ") Then
Certificate.PrivateKey.Delete
Store.Remove Certificate
cDeleted = cDeleted + 1
End If
Else
If UserAgreed("Delete this certificate (No/Yes/All)? ") Then
Store.Remove Certificate
cDeleted = cDeleted + 1
End If
End If
Next
' Display total certificates(s) deleted.
Wscript.Stdout.Writeline CStr(cDeleted) & " certificate(s) successfully deleted."
' Free resources.
Set Certificates = Nothing
End Sub ' End DoDeleteCommand
'******************************************************************************
'
' Subroutine: DoArchiveCommand
'
' Synopsis : Archive certificates.
'
' Parameter : None
'
'******************************************************************************
Sub DoArchiveCommand
Dim Certificate
Dim Certificates
Dim cIndex : cIndex = 0
Dim cArchived : cArchived = 0
' Perform filter(s) requested.
Set Certificates = FilterCertificates(Store.Certificates)
' Display main title.
Dim cCerts : cCerts = Certificates.Count
WScript.StdOut.Writeline "Archiving " & StoreLocationNames(StoreLocation) & " " & StoreName & " store, please wait... "
WScript.StdOut.Writeline
' Now archive all certificates(s).
For Each Certificate In Certificates
cIndex = cIndex + 1
' Skip it if already archived.
If Not Certificate.Archived Then
' Display certificate to be archived.
DisplayCertificate Certificate, "=== Certificate " & CStr(cIndex) & " of " & CStr(cCerts) & " ==="
' Prompt user for permission.
If UserAgreed("Archive this certificate (No/Yes/All)? ") Then
Certificate.Archived = True
cArchived = cArchived + 1
End If
End If
Next
' Display total certificates(s) archived.
Wscript.Stdout.Writeline CStr(cArchived) & " certificate(s) successfully archived."
' Free resources.
Set Certificates = Nothing
End Sub ' End DoArchiveCommand
'******************************************************************************
'
' Subroutine: DoActivateCommand
'
' Synopsis : Activate archived certificates.
'
' Parameter : None
'
'******************************************************************************
Sub DoActivateCommand
Dim Certificate
Dim Certificates
Dim cIndex : cIndex = 0
Dim cActivated : cActivated = 0
' Perform filter(s) requested.
Set Certificates = FilterCertificates(Store.Certificates)
' Display main title.
Dim cCerts : cCerts = Certificates.Count
WScript.StdOut.Writeline "Activating " & StoreLocationNames(StoreLocation) & " " & StoreName & " store, please wait... "
WScript.StdOut.Writeline
' Now activate all certificates(s).
For Each Certificate In Certificates
cIndex = cIndex + 1
' Skip it if not archived.
If Certificate.Archived Then
' Display certificate to be activated.
DisplayCertificate Certificate, "=== Certificate " & CStr(cIndex) & " of " & CStr(cCerts) & " ==="
' Prompt user for permission.
If UserAgreed("Activate this certificate (No/Yes/All)? ") Then
Certificate.Archived = False
cActivated = cActivated + 1
End If
End If
Next
' Display total certificates(s) activated.
Wscript.Stdout.Writeline CStr(cActivated) & " certificate(s) successfully activated."
' Free resources.
Set Certificates = Nothing
End Sub ' End DoActivateCommand
'******************************************************************************
'
' Function : UserAgreed
'
' Synopsis : Prompt user for permission to proceed with an operation.
'
' Parameter : Title - The prompt string.
'
' Return : True if OK, else False.
'
'******************************************************************************
Function UserAgreed (Title)
Dim Result : Result = NoPrompt
' If NoPrompt is not turned off, then prompt user for permission.
If Result = False Then
Dim Answer : Answer = ""
Wscript.Stdout.Write Title
Answer = Wscript.Stdin.Readline
Wscript.Stdout.Writeline
Select Case UCase(Answer)
Case "N", "NO"
Result = False
Case "Y", "YES"
Result = True
Case "A", "ALL"
NoPrompt = True
Result = True
End Select
End If
UserAgreed = Result
End Function ' End UserAgreed
'******************************************************************************
'
' Function : FilterCertificates
'
' Synopsis : Filter the set of certificates based on the filtering options.
'
' Parameter : Certificates - The certificates collection to be filtered.
'
' Return : The filtered certificates collection.
'
'******************************************************************************
Function FilterCertificates (Certificates)
Dim iIndex
Dim Filtered
Set Filtered = Certificates
If Filtered.Count > 0 AND Not IsNull(SHA1) Then
Set Filtered = Filtered.Find(CAPICOM_CERTIFICATE_FIND_SHA1_HASH, SHA1)
End If
If Filtered.Count > 0 AND IsReDimed(Subjects) Then
For iIndex = LBound(Subjects) To UBound(Subjects)
Set Filtered = Filtered.Find(CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME, Subjects(iIndex))
Next
End If
If Filtered.Count > 0 AND IsReDimed(Issuers) Then
For iIndex = LBound(Issuers) To UBound(Issuers)
Set Filtered = Filtered.Find(CAPICOM_CERTIFICATE_FIND_ISSUER_NAME, Issuers(iIndex))
Next
End If
If Filtered.Count > 0 AND IsReDimed(Roots) Then
For iIndex = LBound(Roots) To UBound(Roots)
Set Filtered = Filtered.Find(CAPICOM_CERTIFICATE_FIND_ROOT_NAME, Roots(iIndex))
Next
End If
If Filtered.Count > 0 AND IsReDimed(Templates) Then
For iIndex = LBound(Templates) To UBound(Templates)
Set Filtered = Filtered.Find(CAPICOM_CERTIFICATE_FIND_TEMPLATE_NAME, Templates(iIndex))
Next
End If
If Filtered.Count > 0 AND IsReDimed(Extensions) Then
For iIndex = LBound(Extensions) To UBound(Extensions)
Set Filtered = Filtered.Find(CAPICOM_CERTIFICATE_FIND_EXTENSION, Extensions(iIndex))
Next
End If
If Filtered.Count > 0 AND IsReDimed(Properties) Then
For iIndex = LBound(Properties) To UBound(Properties)
Set Filtered = Filtered.Find(CAPICOM_CERTIFICATE_FIND_EXTENDED_PROPERTY, Properties(iIndex))
Next
End If
If Filtered.Count > 0 AND IsReDimed(Usages) Then
For iIndex = LBound(Usages) To UBound(Usages)
Set Filtered = Filtered.Find(CAPICOM_CERTIFICATE_FIND_APPLICATION_POLICY, Usages(iIndex))
Next
End If
If Filtered.Count > 0 AND IsReDimed(Policies) Then
For iIndex = LBound(Policies) To UBound(Policies)
Set Filtered = Filtered.Find(CAPICOM_CERTIFICATE_FIND_CERTIFICATE_POLICY, Policies(iIndex))
Next
End If
If Filtered.Count > 0 AND IsReDimed(Times) Then
For iIndex = LBound(Times) To UBound(Times)
Set Filtered = Filtered.Find(Times(iIndex)) ', Now)
Next
End If
If Filtered.Count > 0 AND IsReDimed(KeyUsages) Then
For iIndex = LBound(KeyUsages) To UBound(KeyUsages)
Set Filtered = Filtered.Find(CAPICOM_CERTIFICATE_FIND_KEY_USAGE, KeyUsages(iIndex))
Next
End If
If Filtered.Count > 0 AND ValidOnly = True Then
' Use the time valid find with valid flag set.
Set Filtered = Filtered.Find(CAPICOM_CERTIFICATE_FIND_TIME_VALID, Now, True)
End If
Set FilterCertificates = Filtered
End Function ' End FilterCertificates
'******************************************************************************
'
' Subroutine: DisplayCertificate
'
' Synopsis : Display the certificate.
'
' Parameter : Certificate - The certificate object to be displayed.
' Title - Display title.
'
'******************************************************************************
Sub DisplayCertificate (Certificate, Title)
' Turn on exception handling, since some methods, such as
' Certificate.Template and PrivateKey.IsExportable, are not available
' in some down level platforms.
On Error Resume Next
Const CAPICOM_CERT_INFO_SUBJECT_EMAIL_NAME = 2
Const CAPICOM_CERT_INFO_SUBJECT_UPN = 4
Const CAPICOM_CERT_INFO_SUBJECT_DNS_NAME = 6
Const CAPICOM_ENCODED_DATA_FORMAT_MULTI_LINES = 1
Const CAPICOM_CERT_POLICIES_OID = "172.16.31.10"
Dim KeySpecStrings(2)
KeySpecStrings(0) = "Unknown"
KeySpecStrings(1) = "Exchange"
KeySpecStrings(2) = "Signature"
Dim ProviderTypes(24)
ProviderTypes(0) = "Unknown"
ProviderTypes(1) = "PROV_RSA_FULL"
ProviderTypes(2) = "PROV_RSA_SIG"
ProviderTypes(3) = "PROV_DSS"
ProviderTypes(4) = "PROV_FORTEZZA"
ProviderTypes(5) = "PROV_MS_EXCHANGE"
ProviderTypes(6) = "PROV_SSL"
ProviderTypes(7) = "PROV_STT_MER"
ProviderTypes(8) = "PROV_STT_ACQ"
ProviderTypes(9) = "PROV_STT_BRND"
ProviderTypes(10) = "PROV_STT_ROOT"
ProviderTypes(11) = "PROV_STT_ISS"
ProviderTypes(12) = "PROV_RSA_SCHANNEL"
ProviderTypes(13) = "PROV_DSS_DH"
ProviderTypes(14) = "PROV_EC_ECDSA_SIG"
ProviderTypes(15) = "PROV_EC_ECNRA_SIG"
ProviderTypes(16) = "PROV_EC_ECDSA_FULL"
ProviderTypes(17) = "PROV_EC_ECNRA_FULL"
ProviderTypes(18) = "PROV_DH_SCHANNEL"
ProviderTypes(20) = "PROV_SPYRUS_LYNKS"
ProviderTypes(21) = "PROV_RNG"
ProviderTypes(22) = "PROV_INTEL_SEC"
ProviderTypes(23) = "PROV_REPLACE_OWF"
ProviderTypes(24) = "PROV_RSA_AES"
Dim iIndex : iIndex = 0
Wscript.StdOut.Writeline Title
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Subject Name:"
WScript.StdOut.Writeline " Simple name = " & Certificate.SubjectName
WScript.StdOut.Writeline " Email name = " & Certificate.GetInfo(CAPICOM_CERT_INFO_SUBJECT_EMAIL_NAME)
WScript.StdOut.Writeline " UPN name = " & Certificate.GetInfo(CAPICOM_CERT_INFO_SUBJECT_UPN)
WScript.StdOut.Writeline " DNS name = " & Certificate.GetInfo(CAPICOM_CERT_INFO_SUBJECT_DNS_NAME)
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Issuer Name: " & Certificate.IssuerName
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Serial Number: " & Certificate.SerialNumber
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Not Before: " & Certificate.ValidFromDate
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Not After: " & Certificate.ValidToDate
WScript.StdOut.Writeline
WScript.StdOut.Writeline "SHA1 Hash: " & Certificate.Thumbprint
WScript.StdOut.Writeline
WScript.StdOut.Writeline "IsValid: " & Certificate.IsValid()
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Archived: " & Certificate.Archived
WScript.StdOut.Writeline
If Certificate.BasicConstraints.IsPresent Then
Wscript.stdout.Writeline "Basic Constraints:"
Wscript.stdout.Writeline " Critical = " & Certificate.BasicConstraints.IsCritical
Wscript.stdout.Writeline " CA = " & Certificate.BasicConstraints.IsCertificateAuthority
Wscript.stdout.Write " PathLenConstraint = "
If Certificate.BasicConstraints.IsPathLenConstraintPresent Then
Wscript.stdout.Writeline CStr(Certificate.BasicConstraints.PathLenConstraint)
Else
Wscript.stdout.Writeline "Not present."
End If
Else
Wscript.stdout.Writeline "Basic Constraints: Not present."
End If
WScript.StdOut.Writeline
If Certificate.KeyUsage.IsPresent Then
Wscript.stdout.Writeline "Key Usage:"
Wscript.stdout.Writeline " Critical = "& Certificate.KeyUsage.IsCritical
Wscript.stdout.Writeline " IsDigitalSignatureEnabled = " & Certificate.KeyUsage.IsDigitalSignatureEnabled
Wscript.stdout.Writeline " IsNonRepudiationEnabled = " & Certificate.KeyUsage.IsNonRepudiationEnabled
Wscript.stdout.Writeline " IsKeyEnciphermentEnabled = " & Certificate.KeyUsage.IsKeyEnciphermentEnabled
Wscript.stdout.Writeline " IsDataEnciphermentEnabled = " & Certificate.KeyUsage.IsDataEnciphermentEnabled
Wscript.stdout.Writeline " IsKeyAgreementEnabled = " & Certificate.KeyUsage.IsKeyAgreementEnabled
Wscript.stdout.Writeline " IsKeyCertSignEnabled = " & Certificate.KeyUsage.IsKeyCertSignEnabled
Wscript.stdout.Writeline " IsCRLSignEnabled = " & Certificate.KeyUsage.IsCRLSignEnabled
Wscript.stdout.Writeline " IsEncipherOnlyEnabled = " & Certificate.KeyUsage.IsEncipherOnlyEnabled
Wscript.stdout.Writeline " IsDecipherOnlyEnabled = " & Certificate.KeyUsage.IsDecipherOnlyEnabled
Else
Wscript.stdout.Writeline "Key Usage: Not present."
End If
WScript.StdOut.Writeline
If Certificate.ExtendedKeyUsage.IsPresent Then
If Certificate.ExtendedKeyUsage.EKUs.Count > 0 Then
Dim OID
Set OID = CreateObject("CAPICOM.OID")
Wscript.stdout.Writeline "Extended Key Usage:"
Wscript.stdout.Writeline " Critical = " & Certificate.ExtendedKeyUsage.IsCritical
Dim EKU
For Each EKU In Certificate.ExtendedKeyUsage.EKUs
OID.Value = EKU.OID
Wscript.stdout.Writeline " " & OID.FriendlyName & " (" & OID.Value & ")"
Next
Set OID = Nothing
Else
Wscript.stdout.Writeline "Extended Key Usage: Not valid for any usage."
Wscript.stdout.Writeline " Critical = " & Certificate.ExtendedKeyUsage.IsCritical
End If
Else
Wscript.stdout.Writeline "Extended Key Usage: Not present (valid for all usages)."
End If
WScript.StdOut.Writeline
If Certificate.Template.IsPresent Then
Wscript.stdout.Writeline "Template:"
Wscript.stdout.Writeline " Critical = " & Certificate.Template.IsCritical
Wscript.stdout.Writeline " Name = " & Certificate.Template.Name
Wscript.stdout.Writeline " OID = " & Certificate.Template.OID.FriendlyName & "(" & Certificate.Template.OID.Value & ")"
Wscript.stdout.Writeline " Major = " & CStr(Certificate.Template.MajorVersion)
Wscript.stdout.Writeline " Minor = " & CStr(Certificate.Template.MinorVersion)
Else
Wscript.stdout.Writeline "Template: Not present."
End If
WScript.StdOut.Writeline
Wscript.StdOut.Writeline "Public Key:"
Wscript.StdOut.Writeline " Algorithm = " & Certificate.PublicKey.Algorithm.FriendlyName & "(" & Certificate.PublicKey.Algorithm.Value & ")"
Wscript.StdOut.Writeline " Length = " & CStr(Certificate.PublicKey.Length) & " bits"
Wscript.StdOut.Writeline " Key blob = " & Certificate.PublicKey.EncodedKey.Value
Wscript.StdOut.Writeline " Parameters = " & Certificate.PublicKey.EncodedParameters.Value
If Certificate.HasPrivateKey Then
Wscript.StdOut.Writeline "Private Key:"
Wscript.StdOut.Writeline " Container name = " & Certificate.PrivateKey.ContainerName
' Don't display unique container name for hardware token because it may cause UI to be displayed.
If StoreLocation = CAPICOM_SMART_CARD_USER_STORE OR Not Certificate.PrivateKey.IsHardwareDevice Then
Wscript.StdOut.Writeline " Unique name = " & Certificate.PrivateKey.UniqueContainerName
End If
Wscript.StdOut.Writeline " Provider name = " & Certificate.PrivateKey.ProviderName
Wscript.StdOut.Write " Provider type = "
If Certificate.PrivateKey.ProviderType > UBound(ProviderTypes) Then
Wscript.StdOut.Writeline ProviderTypes(0) & " (" & CStr(Certificate.PrivateKey.ProviderType) & ")"
Else
Wscript.StdOut.Writeline ProviderTypes(Certificate.PrivateKey.ProviderType) & " (" & CStr(Certificate.PrivateKey.ProviderType) & ")"
End If
Wscript.StdOut.Write " Key spec = "
If Certificate.PrivateKey.KeySpec > UBound(KeySpecStrings) Then
Wscript.StdOut.Writeline KeySpecStrings(0) & " (" & CStr(Certificate.PrivateKey.KeySpec) & ")"
Else
Wscript.StdOut.Writeline KeySpecStrings(Certificate.PrivateKey.KeySpec) & " (" & CStr(Certificate.PrivateKey.KeySpec) & ")"
End If
Wscript.StdOut.Writeline " Accessible = " & Certificate.PrivateKey.IsAccessible
Wscript.StdOut.Writeline " Protected = " & Certificate.PrivateKey.IsProtected
Wscript.StdOut.Writeline " Exportable = " & Certificate.PrivateKey.IsExportable
Wscript.StdOut.Writeline " Removable = " & Certificate.PrivateKey.IsRemovable
Wscript.StdOut.Writeline " Machine keyset = " & Certificate.PrivateKey.IsMachineKeyset
Wscript.StdOut.Writeline " Hardware storage = " & Certificate.PrivateKey.IsHardwareDevice
Else
Wscript.StdOut.Writeline "Private Key: Not found."
End If
Wscript.StdOut.Writeline
If VerboseLevel = Detail Then
iIndex = 0
Dim Extension
For Each Extension In Certificate.Extensions
iIndex = iIndex + 1
Wscript.StdOut.Writeline "Extension #" & CStr(iIndex) & ": " & Extension.OID.FriendlyName & "(" & Extension.OID.Value & ")"
Wscript.StdOut.Writeline " " & Extension.EncodedData.Format(CAPICOM_ENCODED_DATA_FORMAT_MULTI_LINES)
If Not Extension.EncodedData.Decoder Is Nothing Then
Select Case Extension.OID.Value
Case CAPICOM_CERT_POLICIES_OID
Dim CertPolicies
Set CertPolicies = Extension.EncodedData.Decoder
Wscript.StdOut.Writeline "Decoded Certificate Policies: " & CStr(CertPolicies.Count) & " PolicyInformation(s)"
Dim pIndex : pIndex = 0
Dim PolicyInformation
For Each PolicyInformation In CertPolicies
pIndex = pIndex + 1
Wscript.Stdout.Writeline " PolicyInformation #" & CStr(pIndex) & ": " & CStr(PolicyInformation.Qualifiers.Count) & " Qualifier(s)"
Wscript.Stdout.Writeline " OID = " & PolicyInformation.OID.FriendlyName & "(" & PolicyInformation.OID.Value & ")"
Dim qIndex : qIndex = 0
Dim Qualifier
For Each Qualifier In PolicyInformation.Qualifiers
qIndex = qIndex + 1
Wscript.Stdout.Writeline " Qualifier #" & CStr(qIndex) & ":"
Wscript.Stdout.Writeline " OID = " & Qualifier.OID.FriendlyName & "(" & Qualifier.OID.Value & ")"
Wscript.Stdout.Writeline " CPS URI = " & Qualifier.CPSPointer
Wscript.Stdout.Writeline " Organization name = " & Qualifier.OrganizationName
Wscript.Stdout.Write " Notice number(s) = "
If Not Qualifier.NoticeNumbers Is Nothing Then
Dim nIndex
For nIndex = 1 to Qualifier.NoticeNumbers.Count
If nIndex > 1 Then
Wscript.Stdout.Write ", "
End If
Wscript.Stdout.Write CStr(Qualifier.NoticeNumbers.Item(nIndex))
Next
End If
Wscript.Stdout.Writeline
Wscript.Stdout.Writeline " Explicit text = " & Qualifier.ExplicitText
Next
Wscript.Stdout.Writeline
Next
Case Else
' We don't have the decoder, so can't do much.
End Select
End If
Next
If iIndex = 0 Then
Wscript.StdOut.Writeline "Extension: None."
Wscript.StdOut.Writeline
End If
iIndex = 0
Dim ExtendedProperty
For Each ExtendedProperty In Certificate.ExtendedProperties
iIndex = iIndex + 1
Wscript.StdOut.Writeline "Property #" & CStr(iIndex) & " (ID = " & ExtendedProperty.PropID & "):"
Wscript.StdOut.Writeline " " & ExtendedProperty.Value
Next
If iIndex = 0 Then
Wscript.StdOut.Writeline "Property: None."
Wscript.StdOut.Writeline
End If
Elseif VerboseLevel = UI Then
' Display the certificate UI.
Certificate.Display
End If
On Error Goto 0
End Sub ' End DisplayCertificate
'******************************************************************************
'
' Function : IsReDimed
'
' Synopsis : Check to see if an array has any element.
'
' Parameter : Array - array to check.
'
' Return : True if contains element, else False.
'
'******************************************************************************
Function IsReDimed (Array)
On Error Resume Next
Dim i : i = LBound(Array)
If Err.Number = 0 Then
IsReDimed = True
Else
IsReDimed = False
End If
On Error Goto 0
End Function ' End IsReDimed
'******************************************************************************
'
' Subroutine: ParseCommandLine
'
' Synopsis : Parse the command line, and set the options accordingly. Quit
' with an exit code of either -1 or -2 if error is encountered.
'
' Parameter : None
'
'******************************************************************************
Sub ParseCommandLine
' Constants for command line parsing states.
Const ARG_STATE_COMMAND = 0
Const ARG_STATE_OPTIONS = 1
Const ARG_STATE_LOCATION = 2
Const ARG_STATE_STORENAME = 3
Const ARG_STATE_CERTFILE = 4
Const ARG_STATE_PASSWORD = 5
Const ARG_STATE_SHA1 = 6
Const ARG_STATE_SUBJECT = 7
Const ARG_STATE_ISSUER = 8
Const ARG_STATE_ROOT = 9
Const ARG_STATE_TEMPLATE = 10
Const ARG_STATE_EXTENSION = 11
Const ARG_STATE_PROPERTY = 12
Const ARG_STATE_USAGE = 13
Const ARG_STATE_POLICY = 14
Const ARG_STATE_TIME = 15
Const ARG_STATE_KEYUSAGE = 16
Const ARG_STATE_SAVEAS = 17
Const ARG_STATE_IGNORE_ERROR = 18
Const ARG_STATE_VERBOSE = 19
Const ARG_STATE_END = 20
' Parse command line.
Dim Arg
Dim ArgState : ArgState = ARG_STATE_COMMAND
For Each Arg In Wscript.Arguments
Select Case ArgState
Case ARG_STATE_COMMAND
Select Case UCase(Arg)
Case "VIEW"
Command = View
Case "IMPORT"
Command = Import
Case "EXPORT"
Command = Export
Case "DELETE"
Command = Delete
Case "ARCHIVE"
Command = Archive
Case "ACTIVATE"
OpenMode = OpenMode OR CAPICOM_STORE_OPEN_INCLUDE_ARCHIVED
Command = Activate
Case Else
DisplayUsage
End Select
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_OPTIONS
Select Case UCase(Arg)
Case "-L", "/L"
ArgState = ARG_STATE_LOCATION
Case "-S", "/S"
ArgState = ARG_STATE_STORENAME
Case "-CERTFILE", "/CERTFILE"
ArgState = ARG_STATE_CERTFILE
Case "-PWD", <PASSWORD>"
ArgState = ARG_STATE_PASSWORD
Case "-A", "/A"
OpenMode = OpenMode OR CAPICOM_STORE_OPEN_INCLUDE_ARCHIVED
Case "-SHA1", "/SHA1"
ArgState = ARG_STATE_SHA1
Case "-SUBJECT", "/SUBJECT"
ArgState = ARG_STATE_SUBJECT
Case "-ISSUER", "/ISSUER"
ArgState = ARG_STATE_ISSUER
Case "-ROOT", "/ROOT"
ArgState = ARG_STATE_ROOT
Case "-TEMPLATE", "/TEMPLATE"
ArgState = ARG_STATE_TEMPLATE
Case "-EXTENSION", "/EXTENSION"
ArgState = ARG_STATE_EXTENSION
Case "-PROPERTY", "/PROPERTY"
ArgState = ARG_STATE_PROPERTY
Case "-EKU", "/EKU"
ArgState = ARG_STATE_USAGE
Case "-POLICY", "/POLICY"
ArgState = ARG_STATE_POLICY
Case "-TIME", "/TIME"
ArgState = ARG_STATE_TIME
Case "-KEYUSAGE", "/KEYUSAGE"
ArgState = ARG_STATE_KEYUSAGE
Case "-VALIDONLY", "/VALIDONLY"
ValidOnly = True
Case "-SAVEAS", "/SAVEAS"
ArgState = ARG_STATE_SAVEAS
Case "-DELKEY", "/DELKEY"
DelKey = True
Case "-NOPROMPT", "/NOPROMPT"
NoPrompt = True
Case "-IGNOREERROR", "/IGNOREERROR"
ExportFlag = CAPICOM_EXPORT_IGNORE_PRIVATE_KEY_NOT_EXPORTABLE_ERROR
Case "-E", "/E"
KeyStorageFlag = KeyStorageFlag OR CAPICOM_KEY_STORAGE_EXPORTABLE
Case "-P", "/P"
KeyStorageFlag = KeyStorageFlag OR CAPICOM_KEY_STORAGE_USER_PROTECTED
Case "-V", "/V"
ArgState = ARG_STATE_VERBOSE
Case "-?", "/?"
DisplayUsage
Case "~?"
ExtendedHelp = True
DisplayUsage
Case Else
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
Select Case Command
Case View, Delete, Archive, Activate
StoreName = UCase(Arg)
ArgState = ARG_STATE_END
Case Else ' Import, Export
CertFile = Arg
ArgState = ARG_STATE_PASSWORD
End Select
End If
End Select
Case ARG_STATE_LOCATION
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
Select Case UCase(Arg)
Case "CU"
StoreLocation = CAPICOM_CURRENT_USER_STORE
Case "LM"
StoreLocation = CAPICOM_LOCAL_MACHINE_STORE
Case "AD"
StoreLocation = CAPICOM_ACTIVE_DIRECTORY_USER_STORE
Case "SC"
StoreLocation = CAPICOM_SMART_CARD_USER_STORE
Case Else
DisplayUsage
End Select
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_STORENAME
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
StoreName = UCase(Arg)
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_CERTFILE
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
CertFile = Arg
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_PASSWORD
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
Password = Arg
End If
If Command = Import OR Command = Export Then
ArgState = ARG_STATE_END
Else
ArgState = ARG_STATE_OPTIONS
End If
Case ARG_STATE_SHA1
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
SHA1 = Arg
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_SUBJECT
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
If IsReDimed(Subjects) Then
ReDim Preserve Subjects(UBound(Subjects) + 1)
Else
ReDim Subjects(0)
End If
Subjects(UBound(Subjects)) = Arg
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_ISSUER
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
If IsReDimed(Issuers) Then
ReDim Preserve Issuers(UBound(Issuers) + 1)
Else
ReDim Issuers(0)
End If
Issuers(UBound(Issuers)) = Arg
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_ROOT
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
If IsReDimed(Roots) Then
ReDim Preserve Roots(UBound(Roots) + 1)
Else
ReDim Roots(0)
End If
Roots(UBound(Roots)) = Arg
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_TEMPLATE
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
If IsReDimed(Templates) Then
ReDim Preserve Templates(UBound(Templates) + 1)
Else
ReDim Templates(0)
End If
Templates(UBound(Templates)) = Arg
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_EXTENSION
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
If IsReDimed(Extensions) Then
ReDim Preserve Extensions(UBound(Extensions) + 1)
Else
ReDim Extensions(0)
End If
Extensions(UBound(Extensions)) = Arg
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_PROPERTY
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
If IsReDimed(Properties) Then
ReDim Preserve Properties(UBound(Properties) + 1)
Else
ReDim Properties(0)
End If
If IsNumeric(Arg) Then
Properties(UBound(Properties)) = CLng(Arg)
Else
DisplayUsage
End If
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_USAGE
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
If IsReDimed(Usages) Then
ReDim Preserve Usages(UBound(Usages) + 1)
Else
ReDim Usages(0)
End If
Usages(UBound(Usages)) = Arg
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_POLICY
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
If IsReDimed(Policies) Then
ReDim Preserve Policies(UBound(Policies) + 1)
Else
ReDim Policies(0)
End If
Policies(UBound(Policies)) = Arg
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_TIME
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
If IsReDimed(Times) Then
ReDim Preserve Times(UBound(Times) + 1)
Else
ReDim Times(0)
End If
Select Case Arg
Case "-1"
Times(UBound(Times)) = CAPICOM_CERTIFICATE_FIND_TIME_NOT_YET_VALID
Case "0"
Times(UBound(Times)) = CAPICOM_CERTIFICATE_FIND_TIME_VALID
Case "1"
Times(UBound(Times)) = CAPICOM_CERTIFICATE_FIND_TIME_EXPIRED
Case Else
DisplayUsage
End Select
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_KEYUSAGE
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
If IsReDimed(KeyUsages) Then
ReDim Preserve KeyUsages(UBound(KeyUsages) + 1)
Else
ReDim KeyUsages(0)
End If
If IsNumeric(Arg) Then
KeyUsages(UBound(KeyUsages)) = CLng(Arg)
Else
KeyUsages(UBound(KeyUsages)) = Arg
End If
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_SAVEAS
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
Select Case UCase(Arg)
Case "SST"
SaveAs = CAPICOM_STORE_SAVE_AS_SERIALIZED
Case "PKCS7"
SaveAs = CAPICOM_STORE_SAVE_AS_PKCS7
Case "PFX"
SaveAs = CAPICOM_STORE_SAVE_AS_PFX
Case Else
DisplayUsage
End Select
End If
ArgState = ARG_STATE_OPTIONS
Case ARG_STATE_VERBOSE
If Left(Arg, 1) = "-" OR Left(Arg, 1) = "/" Then
DisplayUsage
Else
VerboseLevel = CLng(Arg)
If VerboseLevel > UI Then
DisplayUsage
End If
End If
ArgState = ARG_STATE_OPTIONS
Case Else
DisplayUsage
End Select
Next
' Make sure we are in good state.
If ArgState <> ARG_STATE_OPTIONS AND ArgState <> ARG_STATE_PASSWORD AND ArgState <> ARG_STATE_END Then
DisplayUsage
End If
' Make sure all required options are valid.
' Note: As stated in the help screen, non-fatal invalid options for
' the specific command is ignore. You can add the logic here
' to further handle these invalid options if desired.
Select Case Command
Case View
' -l and -certfile are exclusive.
If Not IsNull(CertFile) Then
If Not IsNull(StoreLocation) Then
DisplayUsage
Else
StoreName = CertFile
StoreLocation = CAPICOM_MEMORY_STORE
End If
End If
Case Import
' Make sure we do have a certificate file name.
If IsNull(CertFile) Then
DisplayUsage
End If
' -validonly option not allowed.
If ValidOnly = True Then
DisplayUsage
End If
Case Export
' Make sure we do have a certificate file name.
If IsNull(CertFile) Then
DisplayUsage
End If
Case Delete, Archive
' -file option not allowed.
If Not IsNull(CertFile) Then
DisplayUsage
End If
' -validonly option not allowed.
If ValidOnly = True Then
DisplayUsage
End If
Case Activate
' -file option not allowed.
If Not IsNull(CertFile) Then
DisplayUsage
End If
Case Else
Wscript.Stdout.Writeline "Internal script error: Unknown command state (Command = " & CStr(Command) & ")."
Wscript.Quit(-2)
End Select
' Set default store location if both -l and -certfile are not specified.
If IsNull(StoreLocation) Then
StoreLocation = CAPICOM_CURRENT_USER_STORE
End If
End Sub ' ParseCommandLine
'******************************************************************************
'
' Subroutine: DisplayUsage
'
' Synopsis : Display the usage screen, and then exit with a negative error
' code.
'
' Parameter : None.
'
' Remark : Display example usages if the global variable ExtendedHelp is set
' to True.
'
'******************************************************************************
Sub DisplayUsage
Select Case Command
Case Unknown
Wscript.Stdout.Writeline "Usage: CStore Command [Options] <[Store] | CertFile [Password]>"
Wscript.Stdout.Writeline
Wscript.Stdout.Writeline "Command:"
Wscript.Stdout.Writeline
Wscript.Stdout.Writeline " View -- View certificate(s) of store or file"
Wscript.Stdout.Writeline " Import -- Import certificate(s) from file to store"
Wscript.Stdout.Writeline " Export -- Export certificate(s) from store to file"
Wscript.Stdout.Writeline " Delete -- Delete certificate(s) from store"
Wscript.Stdout.Writeline " Archive -- Archive certificate(s) in store"
Wscript.Stdout.Writeline " Activate -- Activate (de-archive) certificate(s) in store"
Wscript.Stdout.Writeline
Wscript.Stdout.Writeline "For help on a specific command, enter ""CStore Command -?"""
Case View
WScript.StdOut.Writeline "Usage: CStore View [Options] [Store]"
WScript.StdOut.Writeline
Wscript.Stdout.Writeline "The View command is used to view certificate(s) of a certificate store or file."
Wscript.Stdout.Writeline "You can use the filtering option(s) to narrow down the set of certificate(s) to"
Wscript.Stdout.Writeline "be displayed."
Wscript.Stdout.Writeline
WScript.StdOut.Writeline "Options:"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " -l <location> -- CU, LM, AD, or SC (default to CU)"
WScript.StdOut.Writeline " -certfile <certfile> -- Certificate file, CER, SST, P7B, PFX,"
WScript.StdOut.Writeline " etc. (exclusive with -l)"
Wscript.Stdout.Writeline " -pwd <password> -- Password for the PFX file (requires -file)."
WScript.StdOut.Writeline " -a -- Include archived certificates"
Wscript.Stdout.Writeline " -sha1 <hash> -- SHA1 hash of the signing certificate"
Wscript.Stdout.Writeline " -subject <name> ** Subject Name of the signing certificate must"
Wscript.Stdout.Writeline " contain this name"
Wscript.Stdout.Writeline " -issuer <name> ** Issuer Name of the signing certificate must"
Wscript.Stdout.Writeline " contain this name"
Wscript.Stdout.Writeline " -root <name> ** Subject Name of the root certificate must"
Wscript.Stdout.Writeline " contain this name"
WScript.StdOut.Writeline " -template <name | oid> ** Template name or OID"
WScript.StdOut.Writeline " -extension <name | oid> ** Extension name or OID"
WScript.StdOut.Writeline " -property <id> ** Property ID"
WScript.StdOut.Writeline " -eku <name | oid> ** EKU name or OID"
WScript.StdOut.Writeline " -policy <name | oid> ** Certificate policy name or OID"
WScript.StdOut.Writeline " -time <-1 | 0 | 1> ** Time validity, -1 for not yet valid, 0 for"
WScript.StdOut.Writeline " valid, 1 for expired (default to all)"
WScript.StdOut.Writeline " -keyusage <key usage> ** Key usage bit flag or name"
WScript.StdOut.Writeline " -validonly -- Display valid certificates only."
WScript.StdOut.Writeline " -v <level> -- Verbose level, 0 for normal, 1 for detail"
WScript.StdOut.Writeline " 2 for UI mode (default to level 0)"
WScript.StdOut.Writeline " -? -- This help screen"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " Store -- My, CA, AddressBook, Root, etc. (default to My)"
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Note: All non-fatal invalid options for this specific command will be ignored,"
WScript.StdOut.Writeline " and the ** symbol indicates option can be listed multiple times."
Wscript.Stdout.Writeline
If ExtendedHelp Then
WScript.StdOut.Writeline "Examples:"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -a -validonly ca"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -l lm root"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -time 1 -v 2 addressbook"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -l ad ""cn=john smith"""
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -v 2 -l sc"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -certfile mystore.sst"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -certfile mypfx.pfx -pwd mypwd"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -sha1 277969B46F5603AD7719F63AC66EF0179CCD9E47"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -l lm -subject john -subject smith -root microsoft -root developer"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -template AutoEnrollSmartcardUser"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -template 1.3.6.1.4.1.311.21.8.3692315854.1256661383.1690418588.4201632533.2654958950.1091409178"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -extension ""Application Policies"""
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -extension 1.3.6.1.4.1.311.21.10"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -extension ""Application Policies"" -extension ""Certificate Policies"""
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -property 2"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -eku ""Code Signing"""
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -eku 1.3.6.1.5.5.7.3.3 -validonly"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -policy ""Medium Assurance"""
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -policy 1.3.6.1.4.1.311.21.8.3692315854.1256661383.1690418588.4201632533.1.401"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore view -keyusage ""&H00000080"" -keyusage DecipherOnly"
End If
Case Import
WScript.StdOut.Writeline "Usage: CStore Import [Options] CertFile [Password]"
WScript.StdOut.Writeline
Wscript.Stdout.Writeline "The Import command is used to import certificate(s) from a certificate file"
Wscript.Stdout.Writeline "(.CER, .SST, .P7B, .PFX, etc.) to a store. You can use the filtering option(s)"
Wscript.Stdout.Writeline "to narrow down the set of certificate(s) to be imported."
Wscript.Stdout.Writeline
WScript.StdOut.Writeline "Options:"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " -l <location> -- CU or LM (default to CU)"
WScript.StdOut.Writeline " -s <store> -- My, CA, AddressBook, Root, etc. (default to My)"
WScript.StdOut.Writeline " -e -- Mark private key as exportable (PFX only)"
WScript.StdOut.Writeline " -p -- Mark private key as user protected (PFX only)"
WScript.StdOut.Writeline " Note: The DPAPI dialog will be displayed"
WScript.StdOut.Writeline " -v <level> -- Verbose level, 0 for normal, 1 for detail"
WScript.StdOut.Writeline " 2 for UI mode (default to level 0)"
WScript.StdOut.Writeline " -? -- This help screen"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " CertFile -- Certificate file to be imported"
WScript.StdOut.Writeline
Wscript.Stdout.Writeline " Password -- Password for PFX file"
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Note: All non-fatal invalid options for this specific command will be ignored."
WScript.StdOut.Writeline
If ExtendedHelp Then
WScript.StdOut.Writeline "Examples:"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore import mycer.cer"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore import mysst.sst"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore import -s root myroot.cer"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore import -l lm -s root -v myroot.cer"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore import -v 2 myp7b.p7b"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore import -e -p mypfx.pfx mypwd"
WScript.StdOut.Writeline
End If
Case Export
WScript.StdOut.Writeline "Usage: CStore Export [Options] CertFile [Password]>"
WScript.StdOut.Writeline
Wscript.Stdout.Writeline "The Export command is used to export certificate(s) from a certificate store to"
Wscript.Stdout.Writeline "file (.SST, .P7B, or .PFX). You can use the filtering option(s) to narrow down"
Wscript.Stdout.Writeline "the set of certificate(s) to be exported."
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Options:"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " -l <location> -- CU, LM, AD, or SC (default to CU)"
WScript.StdOut.Writeline " -s <store> -- My, CA, AddressBook, Root, etc. (default to My)"
WScript.StdOut.Writeline " -a -- Include archived certificates"
Wscript.Stdout.Writeline " -sha1 <hash> -- SHA1 hash of the signing certificate"
Wscript.Stdout.Writeline " -subject <name> ** Subject Name of the signing certificate must"
Wscript.Stdout.Writeline " contain this name"
Wscript.Stdout.Writeline " -issuer <name> ** Issuer Name of the signing certificate must"
Wscript.Stdout.Writeline " contain this name"
Wscript.Stdout.Writeline " -root <name> ** Subject Name of the root certificate must"
Wscript.Stdout.Writeline " contain this name"
WScript.StdOut.Writeline " -template <name | oid> ** Template name or OID"
WScript.StdOut.Writeline " -extension <name | oid> ** Extension name or OID"
WScript.StdOut.Writeline " -property <id> ** Property ID"
WScript.StdOut.Writeline " -eku <name | oid> ** EKU name or OID"
WScript.StdOut.Writeline " -policy <name | oid> ** Certificate policy name or OID"
WScript.StdOut.Writeline " -time <-1 | 0 | 1> ** Time validity, -1 for not yet valid, 0 for"
WScript.StdOut.Writeline " valid, 1 for expired (default to all)"
WScript.StdOut.Writeline " -keyusage <key usage> ** Key usage bit flag or name"
WScript.StdOut.Writeline " -validonly -- Export valid certificates only."
WScript.StdOut.Writeline " -saveas <type> -- SST, PKCS7, or PFX (default to SST)"
WScript.StdOut.Writeline " -ignoreerror -- Ignore private key not exportable error for PFX"
WScript.StdOut.Writeline " -v <level> -- Verbose level, 0 for normal, 1 for detail"
WScript.StdOut.Writeline " 2 for UI mode (default to level 0)"
WScript.StdOut.Writeline " -? -- This help screen"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " CertFile -- Certificate file to be exported to"
WScript.StdOut.Writeline
Wscript.Stdout.Writeline " Password -- Password for PFX file"
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Note: All non-fatal invalid options for this specific command will be ignored,"
WScript.StdOut.Writeline " and the ** symbol indicates option can be listed multiple times."
WScript.StdOut.Writeline
If ExtendedHelp Then
WScript.StdOut.Writeline "Examples:"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore export cumystore.sst"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore export -l lm -subject marketing lmmy.sst"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore export -saveas pfx -property 2 lmmy.pfx mypwd"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore export -s ca -root microsoft -v cuca.sst"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore export -l sc -validonly -v 2 scmy.sst"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore export -l lm -s root -saveas pkcs7 lmroot.p7b"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore export -l ad -s ""cn=john smith"" adjs.sst"
WScript.StdOut.Writeline
End If
Case Delete
WScript.StdOut.Writeline "Usage: CStore Delete [Options] [Store]"
WScript.StdOut.Writeline
Wscript.Stdout.Writeline "The Delete command is used to delete certificate(s) from a certificate store."
Wscript.Stdout.Writeline "You can use the filtering option(s) to narrow down the set of certificate(s) to"
WScript.StdOut.Writeline "be deleted."
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Options:"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " -l <location> -- CU or LM (default to CU)"
WScript.StdOut.Writeline " -a -- Include archived certificates"
Wscript.Stdout.Writeline " -sha1 <hash> -- SHA1 hash of the signing certificate"
Wscript.Stdout.Writeline " -subject <name> ** Subject Name of the signing certificate must"
Wscript.Stdout.Writeline " contain this name"
Wscript.Stdout.Writeline " -issuer <name> ** Issuer Name of the signing certificate must"
Wscript.Stdout.Writeline " contain this name"
Wscript.Stdout.Writeline " -root <name> ** Subject Name of the root certificate must"
Wscript.Stdout.Writeline " contain this name"
WScript.StdOut.Writeline " -template <name | oid> ** Template name or OID"
WScript.StdOut.Writeline " -extension <name | oid> ** Extension name or OID"
WScript.StdOut.Writeline " -property <id> ** Property ID"
WScript.StdOut.Writeline " -eku <name | oid> ** EKU name or OID"
WScript.StdOut.Writeline " -policy <name | oid> ** Certificate policy name or OID"
WScript.StdOut.Writeline " -time <-1 | 0 | 1> ** Time validity, -1 for not yet valid, 0 for"
WScript.StdOut.Writeline " valid, 1 for expired (default to all)"
WScript.StdOut.Writeline " -keyusage <key usage> ** Key usage bit flag or name"
WScript.StdOut.Writeline " -delkey -- Delete key container if exists"
WScript.StdOut.Writeline " -noprompt -- Do not prompt (always delete)"
WScript.StdOut.Writeline " -v <level> -- Verbose level, 0 for normal, 1 for detail"
WScript.StdOut.Writeline " 2 for UI mode (default to level 0)"
WScript.StdOut.Writeline " -? -- This help screen"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " Store -- My, CA, AddressBook, Root, etc. (default to My)"
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Note: All non-fatal invalid options for this specific command will be ignored,"
WScript.StdOut.Writeline " and the ** symbol indicates option can be listed multiple times."
WScript.StdOut.Writeline
If ExtendedHelp Then
WScript.StdOut.Writeline "Examples:"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore delete"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore delete -l lm -delkey"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore delete -noprompt addressbook"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore delete -v 2 -time 1 -delkey -noprompt"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore delete -eku ""secure email"" -eku ""client authentication"" ca"
WScript.StdOut.Writeline
End If
Case Archive
WScript.StdOut.Writeline "Usage: CStore Archive [Options] [Store]"
WScript.StdOut.Writeline
Wscript.Stdout.Writeline "The Archive command is used to archive certificate(s) in a certificate store."
Wscript.Stdout.Writeline "You can use the filtering option(s) to narrow down the set of certificate(s) to"
WScript.StdOut.Writeline "be archived."
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Options:"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " -l <location> -- CU or LM (default to CU)"
Wscript.Stdout.Writeline " -sha1 <hash> -- SHA1 hash of the signing certificate"
Wscript.Stdout.Writeline " -subject <name> ** Subject Name of the signing certificate must"
Wscript.Stdout.Writeline " contain this name"
Wscript.Stdout.Writeline " -issuer <name> ** Issuer Name of the signing certificate must"
Wscript.Stdout.Writeline " contain this name"
Wscript.Stdout.Writeline " -root <name> ** Subject Name of the root certificate must"
Wscript.Stdout.Writeline " contain this name"
WScript.StdOut.Writeline " -template <name | oid> ** Template name or OID"
WScript.StdOut.Writeline " -extension <name | oid> ** Extension name or OID"
WScript.StdOut.Writeline " -property <id> ** Property ID"
WScript.StdOut.Writeline " -eku <name | oid> ** EKU name or OID"
WScript.StdOut.Writeline " -policy <name | oid> ** Certificate policy name or OID"
WScript.StdOut.Writeline " -time <-1 | 0 | 1> ** Time validity, -1 for not yet valid, 0 for"
WScript.StdOut.Writeline " valid, 1 for expired (default to all)"
WScript.StdOut.Writeline " -keyusage <key usage> ** Key usage bit flag or name"
WScript.StdOut.Writeline " -noprompt -- Do not prompt (always archive)"
WScript.StdOut.Writeline " -v <level> -- Verbose level, 0 for normal, 1 for detail"
WScript.StdOut.Writeline " 2 for UI mode (default to level 0)"
WScript.StdOut.Writeline " -? -- This help screen"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " Store -- My, CA, AddressBook, Root, etc. (default to My)"
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Note: All non-fatal invalid options for this specific command will be ignored,"
WScript.StdOut.Writeline " and the ** symbol indicates option can be listed multiple times."
WScript.StdOut.Writeline
If ExtendedHelp Then
WScript.StdOut.Writeline "Examples:"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore archive"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore archive -time 1"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore archive -l lm addressbook"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore archive -noprompt -subject ""<NAME>"" addressbook"
WScript.StdOut.Writeline
End If
Case Activate
WScript.StdOut.Writeline "Usage: CStore Activate [Options] [Store]"
WScript.StdOut.Writeline
Wscript.Stdout.Writeline "The Activate command is used to activate archived certificate(s) in a"
Wscript.Stdout.Writeline "certificate store. You can use the filtering option(s) to narrow down the set"
WScript.StdOut.Writeline "of certificate(s) to be activated (de-archived)."
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Options:"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " -l <location> -- CU or LM (default to CU)"
Wscript.Stdout.Writeline " -sha1 <hash> -- SHA1 hash of the signing certificate"
Wscript.Stdout.Writeline " -subject <name> ** Subject Name of the signing certificate must"
Wscript.Stdout.Writeline " contain this name"
Wscript.Stdout.Writeline " -issuer <name> ** Issuer Name of the signing certificate must"
Wscript.Stdout.Writeline " contain this name"
Wscript.Stdout.Writeline " -root <name> ** Subject Name of the root certificate must"
Wscript.Stdout.Writeline " contain this name"
WScript.StdOut.Writeline " -template <name | oid> ** Template name or OID"
WScript.StdOut.Writeline " -extension <name | oid> ** Extension name or OID"
WScript.StdOut.Writeline " -property <id> ** Property ID"
WScript.StdOut.Writeline " -eku <name | oid> ** EKU name or OID"
WScript.StdOut.Writeline " -policy <name | oid> ** Certificate policy name or OID"
WScript.StdOut.Writeline " -time <-1 | 0 | 1> ** Time validity, -1 for not yet valid, 0 for"
WScript.StdOut.Writeline " valid, 1 for expired (default to all)"
WScript.StdOut.Writeline " -keyusage <key usage> ** Key usage bit flag or name"
WScript.StdOut.Writeline " -validonly -- Activate valid certificates only."
WScript.StdOut.Writeline " -noprompt -- Do not prompt (always activate)"
WScript.StdOut.Writeline " -v <level> -- Verbose level, 0 for normal, 1 for detail"
WScript.StdOut.Writeline " 2 for UI mode (default to level 0)"
WScript.StdOut.Writeline " -? -- This help screen"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " Store -- My, CA, AddressBook, Root, etc. (default to My)"
WScript.StdOut.Writeline
WScript.StdOut.Writeline "Note: All non-fatal invalid options for this specific command will be ignored,"
WScript.StdOut.Writeline " and the ** symbol indicates option can be listed multiple times."
WScript.StdOut.Writeline
If ExtendedHelp Then
WScript.StdOut.Writeline "Examples:"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore activate"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore activate -property 2 -time 0"
WScript.StdOut.Writeline
WScript.StdOut.Writeline " cstore activate -l lm -validonly -noprompt addressbook"
WScript.StdOut.Writeline
End If
Case Else
Wscript.Stdout.Writeline "Internal script error: Unknown help state (Command = " & CStr(Command) & ")."
End Select
Wscript.Quit(-1)
End Sub ' End DisplayUsage
|
<reponame>LaudateCorpus1/RosettaCodeData<filename>Task/Function-definition/Visual-Basic/function-definition-2.vb
Multiply(6, 111)
|
Dim PlusInfinity as Double
Dim MinusInfinity as Double
Dim IndefiniteNumber as Double
On Error Resume Next
PlusInfinity = 1 / 0
MinusInfinity = -1 / 0
IndefiniteNumber = 0 / 0
|
dim twosquared
twosquared = multiply(2, 2)
|
Sub Main()
' in the "references" dialog of the IDE, check
' "Microsoft WinHTTP Services, version 5.1" (winhttp.dll)
Dim HttpReq As WinHttp.WinHttpRequest
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 As Long = &H80&
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 As Long = &H200&
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 As Long = &H800&
Const HTTPREQUEST_PROXYSETTING_PROXY As Long = 2
#Const USE_PROXY = 1
Set HttpReq = New WinHttp.WinHttpRequest
HttpReq.Open "GET", "https://www.abc.com/xyz/index.html"
HttpReq.Option(WinHttpRequestOption_SecureProtocols) = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 Or _
WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 Or _
WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2
HttpReq.SetCredentials "<username>", "<password>", 0&
#If USE_PROXY Then
HttpReq.SetProxy HTTPREQUEST_PROXYSETTING_PROXY, "10.167.1.1:80"
#End If
HttpReq.SetTimeouts 1000, 1000, 1000, 1000
HttpReq.Send
Debug.Print HttpReq.ResponseText
End Sub
|
<gh_stars>1-10
Function cocktail_sort(ByVal s As Variant) As Variant
Dim swapped As Boolean
Dim f As Integer, t As Integer, d As Integer, tmp As Integer
swapped = True
f = 1
t = UBound(s) - 1
d = 1
Do While swapped
swapped = 0
For i = f To t Step d
If Val(s(i)) > Val(s(i + 1)) Then
tmp = s(i)
s(i) = s(i + 1)
s(i + 1) = tmp
swapped = True
End If
Next i
'-- swap to and from, and flip direction.
'-- additionally, we can reduce one element to be
'-- examined, depending on which way we just went.
tmp = f
f = t + (d = 1)
t = tmp + (d = -1)
d = -d
Loop
cocktail_sort = s
End Function
Public Sub main()
Dim s(9) As Variant
For i = 0 To 9
s(i) = CStr(Int(1000 * Rnd))
Next i
Debug.Print Join(s, ", ")
Debug.Print Join(cocktail_sort(s), ", ")
End Sub
|
<filename>base/pnp/tools/devcon2/scripts/test4.vbs
'
' test4.vbs
'
' hardware id's
'
Dim WshSHell
Dim DevCon
Dim Devs
Dim Dev
Dim HwIds
Dim HwId
SET WshShell = WScript.CreateObject("WScript.Shell")
SET DevCon = WScript.CreateObject("DevCon.DeviceConsole")
SET Devs = DevCon.DevicesBySetupClasses("{4D36E96A-E325-11CE-BFC1-08002BE10318}")
Count = Devs.Count
Wscript.Echo "hdc: Count="+CStr(Count)
FOR EACH Dev IN Devs
WScript.Echo Dev + ": " + Dev.Description
set HwIds = Dev.HardwareIds
FOR EACH HwId IN HwIds
WScript.Echo "HWID: " + HwId
NEXT
set HwIds = Dev.CompatibleIds
FOR EACH HwId IN HwIds
WScript.Echo "Compat: " + HwId
NEXT
NEXT
|
Option Explicit
Declare Sub GetMem1 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Byte)
Declare Sub GetMem2 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Integer)
Declare Sub GetMem4 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Long)
Declare Sub PutMem1 Lib "msvbvm60" (ByVal ptr As Long, ByVal x As Byte)
Declare Sub PutMem2 Lib "msvbvm60" (ByVal ptr As Long, ByVal x As Integer)
Declare Sub PutMem4 Lib "msvbvm60" (ByVal ptr As Long, ByVal x As Long)
Sub Test()
Dim a As Long, ptr As Long, s As Long
a = 12345678
'Get and print address
ptr = VarPtr(a)
Debug.Print ptr
'Peek
Call GetMem4(ptr, s)
Debug.Print s
'Poke
Call PutMem4(ptr, 87654321)
Debug.Print a
End Sub
|
Type Tuple
Priority As Integer
Data As String
End Type
Dim a() As Tuple
Dim n As Integer 'number of elements in array, last element is n-1
Private Function Left(i As Integer) As Integer
Left = 2 * i + 1
End Function
Private Function Right(i As Integer) As Integer
Right = 2 * i + 2
End Function
Private Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Private Sub Add(fPriority As Integer, fData As String)
n = n + 1
If n > UBound(a) Then ReDim Preserve a(2 * n)
a(n - 1).Priority = fPriority
a(n - 1).Data = fData
bubbleUp (n - 1)
End Sub
Private Sub Swap(i As Integer, j As Integer)
Dim t As Tuple
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Private Sub bubbleUp(i As Integer)
Dim p As Integer
p = Parent(i)
Do While i > 0 And a(i).Priority < a(p).Priority
Swap i, p
i = p
p = Parent(i)
Loop
End Sub
Private Function Remove() As Tuple
Dim x As Tuple
x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < UBound(a) Then ReDim Preserve a(UBound(a) \ 2)
Remove = x
End Function
Private Sub trickleDown(i As Integer)
Dim j As Integer, l As Integer, r As Integer
Do
j = -1
r = Right(i)
If r < n And a(r).Priority < a(i).Priority Then
l = Left(i)
If a(l).Priority < a(r).Priority Then
j = l
Else
j = r
End If
Else
l = Left(i)
If l < n And a(l).Priority < a(i).Priority Then j = l
End If
If j >= 0 Then Swap i, j
i = j
Loop While i >= 0
End Sub
Public Sub PQ()
ReDim a(4)
Add 3, "Clear drains"
Add 4, "Feed cat"
Add 5, "Make tea"
Add 1, "Solve RC tasks"
Add 2, "Tax return"
Dim t As Tuple
Do While n > 0
t = Remove
Debug.Print t.Priority, t.Data
Loop
End Sub
|
<gh_stars>10-100
'
' Copyright (c) Microsoft Corporation. All rights reserved.
'
' VBScript Source File
'
' Script Name: IIsFtp.vbs
'
Option Explicit
On Error Resume Next
' Error codes
Const ERR_OK = 0
Const ERR_GENERAL_FAILURE = 1
'''''''''''''''''''''
' Messages
Const L_BindingConflict_ErrorMessage = "(ERROR: BINDING CONFLICT)"
Const L_SitesNotFound_ErrorMessage = "Site(s) not found."
Const L_IsAlready_Message = "Server %1 is already %2"
Const L_HasBeen_Message = "Server %1 has been %2"
Const L_GetAD_Message = "The value of %1 for user %2 is:"
Const L_SetAD_Message = "The value of %1 for user %2 has been set to %3"
Const L_All_Text = "ALL"
Const L_AllUnassigned_Text = "ALL UNASSIGNED"
Const L_NotSpecified_Text = "NOT SPECIFIED"
Const L_NoISO_Text = "None"
Const L_Server_Text = "Server"
Const L_SiteName_Text = "Site Name"
Const L_MetabasePath_Message = "Metabase Path"
Const L_IP_Text = "IP"
Const L_Port_Text = "Port"
Const L_Root_Text = "Root"
Const L_ISO_Text = "IsoMode"
Const L_Status_Text = "Status"
Const L_NA_Text = "N/A"
Const L_UnexpectedState_ErrorMessage = "Unexpected state"
Const L_Error_ErrorMessage = "Error &H%1: %2"
Const L_GetRoot_ErrorMessage = "Could not obtaing ROOT virtual dir of site"
Const L_SiteGet_ErrorMessage = "Could not obtain ftp site %1"
Const L_Stop_ErrorMessage = "Could not stop ftp site %1"
Const L_SiteDel_ErrorMessage = "Could not delete ftp site %1"
Const L_GetFtpServer_ErrorMessage = "Error trying to obtain FtpServer object."
Const L_CannotCreateDir_ErrorMessage = "Could not create root directory"
Const L_CmdLib_ErrorMessage = "Could not create an instance of the CmdLib object."
Const L_ChkCmdLibReg_ErrorMessage = "Please register the Microsoft.CmdLib component."
Const L_DirFormat_ErrorMessage = "Root directory format unknown. Please use the"
Const L_DirFormat2_ErrorMessage = "'<drive>:\<path>' format."
Const L_CannotStart_Message = "%1: Server cannot be started in its current state"
Const L_CannotStart2_Message = "(%1 server is %2)"
Const L_CannotStop_Message = "Server cannot be stopped in its current state"
Const L_CannotStop2_Message = "(%1 server is %2)"
Const L_CannotPause_Message = "Server cannot be paused in its current state"
Const L_CannotPause2_Message = "(%1 server is %2)"
Const L_CannotControl_ErrorMessage = "Server cannot be controled in its current state"
Const L_FailChange_ErrorMessage = "Failed to change status of server %1"
Const L_OperationRequired_ErrorMessage = "Please specify an operation before the arguments."
Const L_MinInfoNeeded_ErrorMessage = "Need at least <root> to create a site."
Const L_NotEnoughParams_ErrorMessage = "Not enough parameters."
Const L_Query_ErrorMessage = "Error occurred while querying WMI provider."
Const L_OnlyOneOper_ErrorMessage = "Please specify only one operation at a time."
Const L_ServerInstance_ErrorMessage = "Error trying to create a new ftp server instance."
Const L_ServerPut_ErrorMessage = "Error trying to save new ftp server instance."
Const L_VDirInstance_ErrorMessage = "Error trying to create a new virtual directory instance."
Const L_VDirPut_ErrorMessage = "Error trying to save new virtual directory instance."
Const L_ScriptHelper_ErrorMessage = "Could not create an instance of the IIsScriptHelper object."
Const L_ChkScpHelperReg_ErrorMessage = "Please register the Microsoft.IIsScriptHelper component."
Const L_InvalidIP_ErrorMessage = "Invalid IP Address. Please check if it is well formated and"
Const L_InvalidIP2_ErrorMessage = "belongs to this machine."
Const L_InvalidPort_ErrorMessage = "Invalid port number."
Const L_InvalidArg_ErrorMessage = "Invalid argument: %1"
Const L_MapDrive_ErrorMessage = "Could not map network drive."
Const L_PassWithoutUser_ErrorMessage = "Please specify /u switch before using /p."
Const L_WMIConnect_ErrorMessage = "Could not connect to WMI provider."
Const L_InvalidSwitch_ErrorMessage = "Invalid switch: %1"
Const L_Admin_ErrorMessage = "You cannot run this command because you are not an"
Const L_Admin2_ErrorMessage = "administrator on the server you are trying to configure."
Const L_ADUserNotFound_ErrorMessage = "User %1 was not found in Active Directory."
'''''''''''''''''''''
' Help
' General help messages
Const L_SeeHelp_Message = "Type IIsFtp /? for help."
Const L_SeeStartHelp_Message = "Type IIsFtp /start /? for help."
Const L_SeeStopHelp_Message = "Type IIsFtp /stop /? for help."
Const L_SeePauseHelp_Message = "Type IIsFtp /pause /? for help."
Const L_SeeCreateHelp_Message = "Type IIsFtp /create /? for help."
Const L_SeeDeleteHelp_Message = "Type IIsFtp /delete /? for help."
Const L_SeeGetADPropHelp_Message = "Type IIsFtp /getadprop /? for help."
Const L_SeeSetADPropHelp_Message = "Type IIsFtp /setadprop /? for help."
Const L_SeeQueryHelp_Message = "Type IIsFtp /query /? for help."
Const L_Help_HELP_General01_Text = "Description: Start, Stop, Pause, Delete, Query, or Create"
Const L_Help_HELP_General01a_Text = " a Ftp Site"
Const L_Help_HELP_General02_Text = "Syntax: IIsFtp [/s <server> [/u <username> [/p <password>]]]"
Const L_Help_HELP_General03_Text = " /<operation> [arguments]"
Const L_Help_HELP_General04_Text = "Parameters:"
Const L_Help_HELP_General05_Text = ""
Const L_Help_HELP_General06_Text = "Value Description"
Const L_Help_HELP_General07_Text = "/s <server> Connect to machine <server>"
Const L_Help_HELP_General07a_Text = " [Default: this system]"
Const L_Help_HELP_General08_Text = "/u <username> Connect as <domain>\<username> or"
Const L_Help_HELP_General09_Text = " <username> [Default: current user]"
Const L_Help_HELP_General10_Text = "/p <password> Password for the <username> user"
Const L_Help_HELP_General11_Text = "<operation> /start Starts a site(s) on"
Const L_Help_HELP_General11a_Text = " given IIS Server."
Const L_Help_HELP_General12_Text = " /stop Stops a site(s) from"
Const L_Help_HELP_General13_Text = " running on a given IIS"
Const L_Help_HELP_General13a_Text = " Server."
Const L_Help_HELP_General14_Text = " /pause Pauses a site(s) that is"
Const L_Help_HELP_General15_Text = " running on a given IIS"
Const L_Help_HELP_General15a_Text = " Server."
Const L_Help_HELP_General18_Text = " /delete Deletes IIS configuration"
Const L_Help_HELP_General19_Text = " from an existing Ftp Site."
Const L_Help_HELP_General19a_Text = " Content will not be"
Const L_Help_HELP_General19b_Text = " deleted."
Const L_Help_HELP_General20_Text = " /create Creates a Ftp Site."
Const L_Help_HELP_General21_Text = " /query Queries existing Ftp Sites."
Const L_Help_HELP_General21a_Text = " /SetADProp Sets FTPRoot and FTPDir"
Const L_Help_HELP_General21b_Text = " values in Active Directory."
Const L_Help_HELP_General21c_Text = " /GetADProp Queries FTPRoot and FTPDir"
Const L_Help_HELP_General21d_Text = " values from Active Directory."
Const L_Help_HELP_General22_Text = "For detailed usage:"
Const L_Help_HELP_General23_Text = "IIsFtp /start /?"
Const L_Help_HELP_General24_Text = "IIsFtp /stop /?"
Const L_Help_HELP_General25_Text = "IIsFtp /pause /?"
Const L_Help_HELP_General27_Text = "IIsFtp /delete /?"
Const L_Help_HELP_General28_Text = "IIsFtp /create /?"
Const L_Help_HELP_General29_Text = "IIsFtp /query /?"
Const L_Help_HELP_General30_Text = "IIsFtp /SetADProp /?"
Const L_Help_HELP_General31_Text = "IIsFtp /GetADProp /?"
' Common to all status change commands
Const L_Help_HELP_Status03_Text = "Parameters:"
Const L_Help_HELP_Status09_Text = "<ftpsite> Use either the site name or metabase"
Const L_Help_HELP_Status09p1_Text = " path to specify the site"
Const L_Help_HELP_Status10_Text = "Examples:"
' Start help messages
Const L_Help_HELP_Start01_Text = "Description: Starts a site(s) on a given IIS Server."
Const L_Help_HELP_Start02_Text = "Syntax: IIsFtp [/s <server> [/u <username> [/p <password>]]]"
Const L_Help_HELP_Start02p1_Text = " /start <ftpsite> [<ftpsite> ...]"
Const L_Help_HELP_Start11_Text = "IIsFtp /start ""Default Ftp Site"""
Const L_Help_HELP_Start12_Text = "IIsFtp /start msftpsvc/1"
Const L_Help_HELP_Start13_Text = "IIsFtp /start w3svc/2 ""Default Ftp Site"" w3svc/10"
Const L_Help_HELP_Start14_Text = "IIsFtp /s Server1 /u Administrator /p p@ssWOrd /start msftpsvc/4"
' Stop help messages
Const L_Help_HELP_Stop01_Text = "Description: Stops a site(s) on a given IIS Server."
Const L_Help_HELP_Stop02_Text = "Syntax: IIsFtp [/s <server> [/u <username> [/p <password>]]] /stop"
Const L_Help_HELP_Stop02p1_Text = " <ftpsite> [<ftpsite> ...]"
Const L_Help_HELP_Stop11_Text = "IIsFtp /stop ""Default Ftp Site"""
Const L_Help_HELP_Stop12_Text = "IIsFtp /stop msftpsvc/1"
Const L_Help_HELP_Stop13_Text = "IIsFtp /stop w3svc/2 ""Default Ftp Site"" w3svc/10"
Const L_Help_HELP_Stop14_Text = "IIsFtp /s Server1 /u Administrator /p p@ssWOrd /stop msftpsvc/4"
' GetADProp help messages
Const L_Help_HELP_GetADProp01_Text = "Description: Queries properties from Active Directory."
Const L_Help_HELP_GetADProp02_Text = "Syntax: IIsFtp [/s <server> [/u <username> [/p <password>]]]"
Const L_Help_HELP_GetADProp02p1_Text = " /GetADProp <UserID> FTPDir | FTPRoot"
Const L_Help_HELP_GetADProp10_Text = "<UserID> The logon id of the Active Directory"
Const L_Help_HELP_GetADProp10a_Text = " user to grab the property from."
Const L_Help_HELP_GetADProp11_Text = "IIsFtp /GetADProp billsmith FTPDir"
Const L_Help_HELP_GetADProp12_Text = "IIsFtp /GetADProp marysmith FTPRoot"
' SetADProp help messages
Const L_Help_HELP_SetADProp01_Text = "Description: Sets properties in Active Directory."
Const L_Help_HELP_SetADProp02_Text = "Syntax: IIsFtp [/s <server> [/u <username> [/p <password>]]]"
Const L_Help_HELP_SetADProp02p1_Text = " /SetADProp <UserID> FTPDir | FTPRoot <propval>"
Const L_Help_HELP_SetADProp10_Text = "<UserID> The logon id of the Active Directory"
Const L_Help_HELP_SetADProp10a_Text = " user to set the property at."
Const L_Help_HELP_SetADProp11_Text = "IIsFtp /SetADProp billsmith FTPDir billsdir"
Const L_Help_HELP_SetADProp12_Text = "IIsFtp /SetADProp marysmith FTPRoot c:\foo"
' Pause help messages
Const L_Help_HELP_Pause01_Text = "Description: Pauses a site(s) on a given IIS Server."
Const L_Help_HELP_Pause02_Text = "Syntax: IIsFtp [/s <server> [/u <username> [/p <password>]]]"
Const L_Help_HELP_Pause02p1_Text = " /pause <ftpsite> [<ftpsite> ...]"
Const L_Help_HELP_Pause11_Text = "IIsFtp /pause ""Default Ftp Site"""
Const L_Help_HELP_Pause12_Text = "IIsFtp /pause msftpsvc/1"
Const L_Help_HELP_Pause13_Text = "IIsFtp /pause w3svc/2 ""Default Ftp Site"" w3svc/10"
Const L_Help_HELP_Pause14_Text = "IIsFtp /s Server1 /u Administrator /p p@ssWOrd /pause msftpsvc/4"
' Delete help messages
Const L_Help_HELP_Delete01_Text = "Description: Deletes IIS configuration for an existing ftp"
Const L_Help_HELP_Delete01p1_Text = " site. Content will not be deleted."
Const L_Help_HELP_Delete02_Text = "Syntax: IIsFtp [/s <server> [/u <username> [/p <password>]]]"
Const L_Help_HELP_Delete02p1_Text = " /delete <ftpsite> [<ftpsite> ...]"
Const L_Help_HELP_Delete11_Text = "IIsFtp /delete ""Default Ftp Site"""
Const L_Help_HELP_Delete12_Text = "IIsFtp /delete msftpsvc/1"
Const L_Help_HELP_Delete13_Text = "IIsFtp /delete w3svc/2 ""Default Ftp Site"" w3svc/10"
Const L_Help_HELP_Delete14_Text = "IIsFtp /s Server1 /u Administrator /p p@ssWOrd /delete msftpsvc/4"
' Create help messages
Const L_Help_HELP_Create01_Text = "Description: Creates a ftp site."
Const L_Help_HELP_Create02_Text = "Syntax: IIsFtp [/s <server> [/u <username> [/p <password>]]]"
Const L_Help_HELP_Create02p1_Text = " /create <root> <name> [/b <port>] [/i <ip>] [/dontstart]"
Const L_Help_HELP_Create03_Text = " [/isolation <isomode> [/ADDomain <domain>"
Const L_Help_HELP_Create03a_Text = " /ADAdmin <admin> /ADPass <password>]]"
Const L_Help_HELP_Create09_Text = "<root> Root directory for the new server."
Const L_Help_HELP_Create09p1_Text = " If this directory does not exist, it"
Const L_Help_HELP_Create09p2_Text = " will be created."
Const L_Help_HELP_Create10_Text = "<name> The name that appears in the Microsoft"
Const L_Help_HELP_Create10p1_Text = " Management Console (MMC)."
Const L_Help_HELP_Create12_Text = "/b <port> The number of the port to which the"
Const L_Help_HELP_Create12p1_Text = " new server should bind. [Default: 21]"
Const L_Help_HELP_Create13_Text = "/i <ip> The IP address to assign to the new"
Const L_Help_HELP_Create13p1_Text = " server. [Default: All Unassigned]"
Const L_Help_HELP_Create15_Text = "/dontstart Don't start this site after it is created."
Const L_Help_HELP_Create16_Text = "/isolation Set isolation mode to either Local or AD."
Const L_Help_HELP_Create17_Text = "/AD* Set ActiveDirectory credentials for"
Const L_Help_HELP_Create17a_Text = " AD isolation mode."
Const L_Help_HELP_Create22_Text = "IIsFtp /create c:\inetpub\ftproot ""My Site"" /b 21"
Const L_Help_HELP_Create23_Text = "IIsFtp /s Server1 /u Administrator /p p@assWOrd /create c:\inetpub\ftproot"
Const L_Help_HELP_Create23p1_Text = " ""My Site"""
Const L_Help_HELP_Create24_Text = "IIsFtp /create c:\inetpub\ftproot ""My Site"" /i 172.30.163.244 /b 21"
' Query help messages
Const L_Help_HELP_Query01_Text = "Description: Queries existing ftp sites."
Const L_Help_HELP_Query02_Text = "Syntax: IIsFtp [/s <server> [/u <username> [/p <password>]]]"
Const L_Help_HELP_Query02p1_Text = " /query [<ftpsite> ...]"
Const L_Help_HELP_Query11_Text = "IIsFtp /query ""Default Ftp Site"""
Const L_Help_HELP_Query12_Text = "IIsFtp /query msftpsvc/1"
Const L_Help_HELP_Query13_Text = "IIsFtp /query"
Const L_Help_HELP_Query14_Text = "IIsFtp /query ""Default Ftp Site"" ""Sample Site"" msftpsvc/1"
Const L_Help_HELP_Query15_Text = "IIsFtp /s Server1 /u Administrator /p p@ssW0rd /query ""Default Ftp Site"""
' Status
Const L_Started_Text = "started"
Const L_Stopped_Text = "stopped"
Const L_Paused_Text = "paused"
Const L_Continued_Text = "continued"
Const L_Deleted_Text = "deleted"
''''''''''''''''''''''''
Dim SiteStatus
SiteStatus = Array("", "", L_Started_Text, "", L_Stopped_Text, "", L_Paused_Text, L_Continued_Text, L_Deleted_Text)
' Operation codes
Const OPER_START = 1
Const OPER_STOP = 2
Const OPER_PAUSE = 3
Const OPER_DELETE = 4
Const OPER_CREATE = 5
Const OPER_QUERY = 6
Const OPER_GETADPROP= 7
Const OPER_SETADPROP= 8
' ServerState codes
Const SERVER_STARTING = 1
Const SERVER_STARTED = 2
Const SERVER_STOPPING = 3
Const SERVER_STOPPED = 4
Const SERVER_PAUSING = 5
Const SERVER_PAUSED = 6
Const SERVER_CONTINUING = 7
'
' Main block
'
Dim oScriptHelper, oCmdLib
Dim strServer, strUser, strPassword, strSite
Dim intOperation, intResult
Dim strRoot, strName, strPort, strIP, strISO, strADDomain, strADAdmin, strADPass
Dim bDontStart
Dim aArgs, arg
Dim strCmdLineOptions
Dim oError
' Default values
strServer = "."
strUser = ""
strPassword = ""
intOperation = 0
strSite = ""
strName = ""
bDontStart = False
' Instantiate the CmdLib for output string formatting
Set oCmdLib = CreateObject("Microsoft.CmdLib")
If Err.Number <> 0 Then
WScript.Echo L_CmdLib_ErrorMessage
WScript.Echo L_ChkCmdLibReg_ErrorMessage
WScript.Quit(ERR_GENERAL_FAILURE)
End If
Set oCmdLib.ScriptingHost = WScript.Application
' Instantiate script helper object
Set oScriptHelper = CreateObject("Microsoft.IIsScriptHelper")
If Err.Number <> 0 Then
WScript.Echo L_ScriptHelper_ErrorMessage
WScript.Echo L_ChkScpHelperReg_ErrorMessage
WScript.Quit(ERR_GENERAL_FAILURE)
End If
Set oScriptHelper.ScriptHost = WScript
' Check if we are being run with cscript.exe instead of wscript.exe
oScriptHelper.CheckScriptEngine
' Minimum number of parameters must exist
If WScript.Arguments.Count < 1 Then
WScript.Echo L_NotEnoughParams_ErrorMessage
WScript.Echo L_SeeHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
strCmdLineOptions = "[server:s:1;user:u:1;password:p:1];start::n;stop::n;pause::n;delete::n;" & _
"[create:c:1;port:b:1;ip:i:1;dontstart::0;isolation::1;addomain::1;adadmin::1;adpass::1];query:q:n;" & _
"getadprop::n;setadprop::n"
Set oError = oScriptHelper.ParseCmdLineOptions(strCmdLineOptions)
If Not oError Is Nothing Then
If oError.ErrorCode = oScriptHelper.ERROR_NOT_ENOUGH_ARGS Then
' Not enough arguments for a specified switch
WScript.Echo L_NotEnoughParams_ErrorMessage
If oError.SwitchName = "create" Then
WScript.Echo L_SeeCreateHelp_Message
Else
WScript.Echo L_SeeHelp_Message
End If
Else
' Invalid switch
oCmdLib.vbPrintf L_InvalidSwitch_ErrorMessage, Array(oError.SwitchName)
WScript.Echo L_SeeHelp_Message
End If
WScript.Quit(ERR_GENERAL_FAILURE)
End If
If oScriptHelper.GlobalHelpRequested Then
DisplayHelpMessage
WScript.Quit(ERR_OK)
End If
For Each arg In oScriptHelper.Switches
Select Case arg
Case "server"
' Server information
strServer = oScriptHelper.GetSwitch(arg)
Case "user"
' User information
strUser = oScriptHelper.GetSwitch(arg)
Case "password"
' Password information
strPassword = oScriptHelper.GetSwitch(arg)
Case "start"
If (intOperation <> 0) Then
WScript.Echo L_OnlyOneOper_ErrorMessage
WScript.Echo L_SeeHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
intOperation = OPER_START
If oScriptHelper.IsHelpRequested(arg) Then
DisplayStartHelpMessage
WScript.Quit(ERR_OK)
End If
aArgs = oScriptHelper.GetSwitch(arg)
If UBound(aArgs) = -1 Then
WScript.Echo L_NotEnoughParams_ErrorMessage
WScript.Echo L_SeeStartHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
Case "stop"
If (intOperation <> 0) Then
WScript.Echo L_OnlyOneOper_ErrorMessage
WScript.Echo L_SeeHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
intOperation = OPER_STOP
If oScriptHelper.IsHelpRequested(arg) Then
DisplayStopHelpMessage
WScript.Quit(ERR_OK)
End If
aArgs = oScriptHelper.GetSwitch(arg)
If UBound(aArgs) = -1 Then
WScript.Echo L_NotEnoughParams_ErrorMessage
WScript.Echo L_SeeStopHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
Case "pause"
If (intOperation <> 0) Then
WScript.Echo L_OnlyOneOper_ErrorMessage
WScript.Echo L_SeeHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
intOperation = OPER_PAUSE
If oScriptHelper.IsHelpRequested(arg) Then
DisplayPauseHelpMessage
WScript.Quit(ERR_OK)
End If
aArgs = oScriptHelper.GetSwitch(arg)
If UBound(aArgs) = -1 Then
WScript.Echo L_NotEnoughParams_ErrorMessage
WScript.Echo L_SeePauseHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
Case "create"
If (intOperation <> 0) Then
WScript.Echo L_OnlyOneOper_ErrorMessage
WScript.Echo L_SeeHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
intOperation = OPER_CREATE
If oScriptHelper.IsHelpRequested(arg) Then
DisplayCreateHelpMessage
WScript.Quit(ERR_OK)
End If
strRoot = oScriptHelper.GetSwitch(arg)
aArgs = oScriptHelper.NamedArguments
If strRoot = "" Or UBound(aArgs) = -1 Then
WScript.Echo L_NotEnoughParams_ErrorMessage
WScript.Echo L_SeeCreateHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
strName = aArgs(0)
strPort = oScriptHelper.GetSwitch("port")
strIP = oScriptHelper.GetSwitch("ip")
If oScriptHelper.Switches.Exists("dontstart") Then
bDontStart = True
End If
strISO = oScriptHelper.GetSwitch("isolation")
strADDomain= oScriptHelper.GetSwitch("addomain")
strADAdmin = oScriptHelper.GetSwitch("adadmin")
strADPass = oScriptHelper.GetSwitch("adpass")
If UCase(strISO) = "AD" Then
strRoot = ""
End If
Case "delete"
If (intOperation <> 0) Then
WScript.Echo L_OnlyOneOper_ErrorMessage
WScript.Echo L_SeeHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
intOperation = OPER_DELETE
If oScriptHelper.IsHelpRequested(arg) Then
DisplayDeleteHelpMessage
WScript.Quit(ERR_OK)
End If
aArgs = oScriptHelper.GetSwitch(arg)
If UBound(aArgs) = -1 Then
WScript.Echo L_NotEnoughParams_ErrorMessage
WScript.Echo L_SeeDeleteHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
Case "query"
If (intOperation <> 0) Then
WScript.Echo L_OnlyOneOper_ErrorMessage
WScript.Echo L_SeeHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
intOperation = OPER_QUERY
If oScriptHelper.IsHelpRequested(arg) Then
DisplayQueryHelpMessage
WScript.Quit(ERR_OK)
End If
aArgs = oScriptHelper.GetSwitch(arg)
Case "getadprop"
If (intOperation <> 0) Then
WScript.Echo L_OnlyOneOper_ErrorMessage
WScript.Echo L_SeeHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
intOperation = OPER_GETADPROP
If oScriptHelper.IsHelpRequested(arg) Then
DisplayGetADPropHelpMessage
WScript.Quit(ERR_OK)
End If
aArgs = oScriptHelper.GetSwitch(arg)
If UBound(aArgs) = -1 Then
WScript.Echo L_NotEnoughParams_ErrorMessage
WScript.Echo L_SeeGetADPropHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
Case "setadprop"
If (intOperation <> 0) Then
WScript.Echo L_OnlyOneOper_ErrorMessage
WScript.Echo L_SeeHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
intOperation = OPER_SETADPROP
If oScriptHelper.IsHelpRequested(arg) Then
DisplaySetADPropHelpMessage
WScript.Quit(ERR_OK)
End If
aArgs = oScriptHelper.GetSwitch(arg)
If UBound(aArgs) = -1 Then
WScript.Echo L_NotEnoughParams_ErrorMessage
WScript.Echo L_SeeSetADPropHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
End Select
Next
' Check Parameters
If intOperation = 0 Then
WScript.Echo L_OperationRequired_ErrorMessage
WScript.Echo L_SeeHelp_Message
WScript.Quit(ERR_GENERAL_FAILURE)
End If
' Check if /p is specified but /u isn't. In this case, we should bail out with an error
If oScriptHelper.Switches.Exists("password") And Not oScriptHelper.Switches.Exists("user") Then
WScript.Echo L_PassWithoutUser_ErrorMessage
WScript.Quit(ERR_GENERAL_FAILURE)
End If
' Check if /u is specified but /p isn't. In this case, we should ask for a password
If oScriptHelper.Switches.Exists("user") And Not oScriptHelper.Switches.Exists("password") Then
strPassword = oCmdLib.GetPassword
End If
' Initializes authentication with remote machine
' This initialization applies only for IIS operations. We skip it for AD operations
If intOperation <> OPER_GETADPROP And intOperation <> OPER_SETADPROP Then
intResult = oScriptHelper.InitAuthentication(strServer, strUser, strPassword)
If intResult <> 0 Then
WScript.Quit(intResult)
End If
End If
' Choose operation
Select Case intOperation
Case OPER_START
intResult = ChangeFtpSiteStatus(aArgs, SERVER_STARTED)
Case OPER_STOP
intResult = ChangeFtpSiteStatus(aArgs, SERVER_STOPPED)
Case OPER_PAUSE
intResult = ChangeFtpSiteStatus(aArgs, SERVER_PAUSED)
Case OPER_DELETE
intResult = DeleteFtpSite(aArgs)
Case OPER_CREATE
intResult = CreateFtpSite(strRoot, strName, strPort, strIP, bDontStart, strISO, strADDomain, strADAdmin, strADPass)
Case OPER_QUERY
intResult = QueryFtpSite(aArgs)
Case OPER_GETADPROP
intResult = GetADProp(strServer, strUser, strPassword, aArgs)
Case OPER_SETADPROP
intResult = SetADProp(strServer, strUser, strPassword, aArgs)
End Select
' Return value to command processor
WScript.Quit(intResult)
'''''''''''''''''''''''''
' End Of Main Block
'''''''''''''''''''''
'''''''''''''''''''''''''''
' DisplayHelpMessage
'''''''''''''''''''''''''''
Sub DisplayHelpMessage()
WScript.Echo L_Help_HELP_General01_Text
WScript.Echo L_Help_HELP_General01a_Text
WScript.Echo
WScript.Echo L_Help_HELP_General02_Text
WScript.Echo L_Help_HELP_General03_Text
WScript.Echo
WScript.Echo L_Help_HELP_General04_Text
WScript.Echo L_Help_HELP_General05_Text
WScript.Echo L_Help_HELP_General06_Text
WScript.Echo L_Help_HELP_General07_Text
WScript.Echo L_Help_HELP_General07a_Text
WScript.Echo L_Help_HELP_General08_Text
WScript.Echo L_Help_HELP_General09_Text
WScript.Echo L_Help_HELP_General10_Text
WScript.Echo L_Help_HELP_General11_Text
WScript.Echo L_Help_HELP_General11a_Text
WScript.Echo L_Help_HELP_General12_Text
WScript.Echo L_Help_HELP_General13_Text
WScript.Echo L_Help_HELP_General13a_Text
WScript.Echo L_Help_HELP_General14_Text
WScript.Echo L_Help_HELP_General15_Text
WScript.Echo L_Help_HELP_General15a_Text
WScript.Echo L_Help_HELP_General18_Text
WScript.Echo L_Help_HELP_General19_Text
WScript.Echo L_Help_HELP_General19a_Text
WScript.Echo L_Help_HELP_General19b_Text
WScript.Echo L_Help_HELP_General20_Text
WScript.Echo L_Help_HELP_General21_Text
WScript.Echo L_Help_HELP_General21a_Text
WScript.Echo L_Help_HELP_General21b_Text
WScript.Echo L_Help_HELP_General21c_Text
WScript.Echo L_Help_HELP_General21d_Text
WScript.Echo
WScript.Echo L_Help_HELP_General22_Text
WScript.Echo
WScript.Echo L_Help_HELP_General23_Text
WScript.Echo L_Help_HELP_General24_Text
WScript.Echo L_Help_HELP_General25_Text
WScript.Echo L_Help_HELP_General27_Text
WScript.Echo L_Help_HELP_General28_Text
WScript.Echo L_Help_HELP_General29_Text
WScript.Echo L_Help_HELP_General30_Text
WScript.Echo L_Help_HELP_General31_Text
End Sub
Sub DisplayStartHelpMessage()
WScript.Echo L_Help_HELP_Start01_Text
WScript.Echo
WScript.Echo L_Help_HELP_Start02_Text
WScript.Echo L_Help_HELP_Start02p1_Text
WScript.Echo
WScript.Echo L_Help_HELP_Status03_Text
WScript.Echo
WScript.Echo L_Help_HELP_General06_Text
WScript.Echo L_Help_HELP_General07_Text
WScript.Echo L_Help_HELP_General07a_Text
WScript.Echo L_Help_HELP_General08_Text
WScript.Echo L_Help_HELP_General09_Text
WScript.Echo L_Help_HELP_General10_Text
WScript.Echo L_Help_HELP_Status09_Text
WScript.Echo L_Help_HELP_Status09p1_Text
WScript.Echo
WScript.Echo
WScript.Echo L_Help_HELP_Status10_Text
WScript.Echo
WScript.Echo L_Help_HELP_Start11_Text
WScript.Echo L_Help_HELP_Start12_Text
WScript.Echo L_Help_HELP_Start13_Text
WScript.Echo L_Help_HELP_Start14_Text
End Sub
Sub DisplayStopHelpMessage()
WScript.Echo L_Help_HELP_Stop01_Text
WScript.Echo
WScript.Echo L_Help_HELP_Stop02_Text
WScript.Echo L_Help_HELP_Stop02p1_Text
WScript.Echo
WScript.Echo L_Help_HELP_Status03_Text
WScript.Echo
WScript.Echo L_Help_HELP_General06_Text
WScript.Echo L_Help_HELP_General07_Text
WScript.Echo L_Help_HELP_General07a_Text
WScript.Echo L_Help_HELP_General08_Text
WScript.Echo L_Help_HELP_General09_Text
WScript.Echo L_Help_HELP_General10_Text
WScript.Echo L_Help_HELP_Status09_Text
WScript.Echo L_Help_HELP_Status09p1_Text
WScript.Echo
WScript.Echo
WScript.Echo L_Help_HELP_Status10_Text
WScript.Echo
WScript.Echo L_Help_HELP_Stop11_Text
WScript.Echo L_Help_HELP_Stop12_Text
WScript.Echo L_Help_HELP_Stop13_Text
WScript.Echo L_Help_HELP_Stop14_Text
End Sub
Sub DisplayGetADPropHelpMessage()
WScript.Echo L_Help_HELP_GetADProp01_Text
WScript.Echo
WScript.Echo L_Help_HELP_GetADProp02_Text
WScript.Echo L_Help_HELP_GetADProp02p1_Text
WScript.Echo
WScript.Echo L_Help_HELP_Status03_Text
WScript.Echo
WScript.Echo L_Help_HELP_General06_Text
WScript.Echo L_Help_HELP_General07_Text
WScript.Echo L_Help_HELP_General07a_Text
WScript.Echo L_Help_HELP_General08_Text
WScript.Echo L_Help_HELP_General09_Text
WScript.Echo L_Help_HELP_General10_Text
WScript.Echo L_Help_HELP_GetADProp10_Text
WScript.Echo L_Help_HELP_GetADProp10a_Text
WScript.Echo
WScript.Echo
WScript.Echo L_Help_HELP_Status10_Text
WScript.Echo
WScript.Echo L_Help_HELP_GetADProp11_Text
WScript.Echo L_Help_HELP_GetADProp12_Text
End Sub
Sub DisplaySetADPropHelpMessage()
WScript.Echo L_Help_HELP_SetADProp01_Text
WScript.Echo
WScript.Echo L_Help_HELP_SetADProp02_Text
WScript.Echo L_Help_HELP_SetADProp02p1_Text
WScript.Echo
WScript.Echo L_Help_HELP_Status03_Text
WScript.Echo
WScript.Echo L_Help_HELP_General06_Text
WScript.Echo L_Help_HELP_General07_Text
WScript.Echo L_Help_HELP_General07a_Text
WScript.Echo L_Help_HELP_General08_Text
WScript.Echo L_Help_HELP_General09_Text
WScript.Echo L_Help_HELP_General10_Text
WScript.Echo L_Help_HELP_SetADProp10_Text
WScript.Echo L_Help_HELP_SetADProp10a_Text
WScript.Echo
WScript.Echo
WScript.Echo L_Help_HELP_Status10_Text
WScript.Echo
WScript.Echo L_Help_HELP_SetADProp11_Text
WScript.Echo L_Help_HELP_SetADProp12_Text
End Sub
Sub DisplayPauseHelpMessage()
WScript.Echo L_Help_HELP_Pause01_Text
WScript.Echo
WScript.Echo L_Help_HELP_Pause02_Text
WScript.Echo L_Help_HELP_Pause02p1_Text
WScript.Echo
WScript.Echo L_Help_HELP_Status03_Text
WScript.Echo
WScript.Echo L_Help_HELP_General06_Text
WScript.Echo L_Help_HELP_General07_Text
WScript.Echo L_Help_HELP_General07a_Text
WScript.Echo L_Help_HELP_General08_Text
WScript.Echo L_Help_HELP_General09_Text
WScript.Echo L_Help_HELP_General10_Text
WScript.Echo L_Help_HELP_Status09_Text
WScript.Echo L_Help_HELP_Status09p1_Text
WScript.Echo
WScript.Echo
WScript.Echo L_Help_HELP_Status10_Text
WScript.Echo
WScript.Echo L_Help_HELP_Pause11_Text
WScript.Echo L_Help_HELP_Pause12_Text
WScript.Echo L_Help_HELP_Pause13_Text
WScript.Echo L_Help_HELP_Pause14_Text
End Sub
Sub DisplayDeleteHelpMessage()
WScript.Echo L_Help_HELP_Delete01_Text
WScript.Echo L_Help_HELP_Delete01p1_Text
WScript.Echo
WScript.Echo L_Help_HELP_Delete02_Text
WScript.Echo L_Help_HELP_Delete02p1_Text
WScript.Echo
WScript.Echo L_Help_HELP_Status03_Text
WScript.Echo
WScript.Echo L_Help_HELP_General06_Text
WScript.Echo L_Help_HELP_General07_Text
WScript.Echo L_Help_HELP_General07a_Text
WScript.Echo L_Help_HELP_General08_Text
WScript.Echo L_Help_HELP_General09_Text
WScript.Echo L_Help_HELP_General10_Text
WScript.Echo L_Help_HELP_Status09_Text
WScript.Echo L_Help_HELP_Status09p1_Text
WScript.Echo
WScript.Echo
WScript.Echo L_Help_HELP_Status10_Text
WScript.Echo
WScript.Echo L_Help_HELP_Delete11_Text
WScript.Echo L_Help_HELP_Delete12_Text
WScript.Echo L_Help_HELP_Delete13_Text
WScript.Echo L_Help_HELP_Delete14_Text
End Sub
Sub DisplayCreateHelpMessage()
WScript.Echo L_Help_HELP_Create01_Text
WScript.Echo
WScript.Echo L_Help_HELP_Create02_Text
WScript.Echo L_Help_HELP_Create02p1_Text
WScript.Echo L_Help_HELP_Create03_Text
WScript.Echo L_Help_HELP_Create03a_Text
WScript.Echo
WScript.Echo L_Help_HELP_Status03_Text
WScript.Echo
WScript.Echo L_Help_HELP_General06_Text
WScript.Echo L_Help_HELP_General07_Text
WScript.Echo L_Help_HELP_General07a_Text
WScript.Echo L_Help_HELP_General08_Text
WScript.Echo L_Help_HELP_General09_Text
WScript.Echo L_Help_HELP_General10_Text
WScript.Echo L_Help_HELP_Create09_Text
WScript.Echo L_Help_HELP_Create09p1_Text
WScript.Echo L_Help_HELP_Create09p2_Text
WScript.Echo L_Help_HELP_Create10_Text
WScript.Echo L_Help_HELP_Create10p1_Text
WScript.Echo L_Help_HELP_Create12_Text
WScript.Echo L_Help_HELP_Create12p1_Text
WScript.Echo L_Help_HELP_Create13_Text
WScript.Echo L_Help_HELP_Create13p1_Text
WScript.Echo L_Help_HELP_Create15_Text
WScript.Echo L_Help_HELP_Create16_Text
WScript.Echo L_Help_HELP_Create17_Text
WScript.Echo L_Help_HELP_Create17a_Text
WScript.Echo
WScript.Echo L_Help_HELP_Status10_Text
WScript.Echo
WScript.Echo L_Help_HELP_Create22_Text
WScript.Echo L_Help_HELP_Create23_Text
WScript.Echo L_Help_HELP_Create23p1_Text
WScript.Echo L_Help_HELP_Create24_Text
End Sub
Sub DisplayQueryHelpMessage()
WScript.Echo L_Help_HELP_Query01_Text
WScript.Echo
WScript.Echo L_Help_HELP_Query02_Text
WScript.Echo L_Help_HELP_Query02p1_Text
WScript.Echo
WScript.Echo L_Help_HELP_Status03_Text
WScript.Echo
WScript.Echo L_Help_HELP_General06_Text
WScript.Echo L_Help_HELP_General07_Text
WScript.Echo L_Help_HELP_General07a_Text
WScript.Echo L_Help_HELP_General08_Text
WScript.Echo L_Help_HELP_General09_Text
WScript.Echo L_Help_HELP_General10_Text
WScript.Echo L_Help_HELP_Status09_Text
WScript.Echo L_Help_HELP_Status09p1_Text
WScript.Echo
WScript.Echo
WScript.Echo L_Help_HELP_Status10_Text
WScript.Echo
WScript.Echo L_Help_HELP_Query11_Text
WScript.Echo L_Help_HELP_Query12_Text
WScript.Echo L_Help_HELP_Query13_Text
WScript.Echo L_Help_HELP_Query14_Text
WScript.Echo L_Help_HELP_Query15_Text
End Sub
'''''''''''''''''''''''''''
' ChangeFtpSiteStatus
'
' Try to change the status of a site
' to the one specified
'''''''''''''''''''''''''''
Function ChangeFtpSiteStatus(aArgs, newStatus)
Dim Server, strSiteName
Dim intResult, i, intNewStatus
Dim aSites
Dim providerObj, ServiceObj
Dim bNonFatalError
On Error Resume Next
bNonFatalError = False
oScriptHelper.WMIConnect
If Err.Number Then
WScript.Echo L_WMIConnect_ErrorMessage
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
ChangeFtpSiteStatus = Err.Number
Exit Function
End If
Set providerObj = oScriptHelper.ProviderObj
intResult = 0
' Quick check to see if we have permission
Set ServiceObj = providerObj.Get("IIsFtpService='MSFTPSVC'")
If Err.Number Then
Select Case Err.Number
Case &H80070005
WScript.Echo L_Admin_ErrorMessage
WScript.Echo L_Admin2_ErrorMessage
Case Else
WScript.Echo Err.Description
End Select
ChangeFtpSiteStatus = Err.Number
Exit Function
End If
aSites = oScriptHelper.FindSite("Ftp", aArgs)
If IsArray(aSites) Then
If UBound(aSites) = -1 Then
WScript.Echo L_SitesNotFound_ErrorMessage
intResult = ERR_GENERAL_FAILURE
End If
Else
' Got duplicate sites. We should quit.
ChangeFtpSiteStatus = intResult
Exit Function
End If
For i = LBound(aSites) to UBound(aSites)
bNonFatalError = False
strSiteName = aSites(i)
' Grab site state before trying to start it
Set Server = providerObj.Get("IIsFtpServer='" & strSiteName & "'")
If (Err.Number <> 0) Then
WScript.Echo L_GetFtpServer_ErrorMessage
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
intResult = Err.Number
End If
If (Server.ServerState = newStatus) Then
oCmdLib.vbPrintf L_IsAlready_Message, Array(strSiteName, UCase(SiteStatus(newStatus)))
Else
If (Server.ServerState = SERVER_STARTING or Server.ServerState = SERVER_STOPPING or _
Server.ServerState = SERVER_PAUSING or Server.ServerState = SERVER_CONTINUING) Then
WScript.Echo L_CannotControl_ErrorMessage
intResult = ERR_GENERAL_FAILURE
Else
Select Case newStatus
Case SERVER_STARTED
If (Server.ServerState = SERVER_STOPPED) Then
intNewStatus = SERVER_STARTED
Server.Start
Else
If (Server.ServerState = SERVER_PAUSED) Then
intNewStatus = SERVER_CONTINUING
Server.Continue
Else
oCmdLib.vbPrintf L_CannotStart_Message, Array(strSiteName)
oCmdLib.vbPrintf L_CannotStart2_Message, Array(strSiteName, SiteStatus(Server.ServerState))
bNonFatalError = True
End If
End If
Case SERVER_STOPPED
If (Server.ServerState = SERVER_STARTED) Then
intNewStatus = SERVER_STOPPED
Server.Stop
Else
WScript.Echo L_CannotStop_Message
oCmdLib.vbPrintf L_CannotStop2_Message, Array(strSiteName, SiteStatus(Server.ServerState))
bNonFatalError = True
End If
Case SERVER_PAUSED
If (Server.ServerState = SERVER_STARTED) Then
intNewStatus = SERVER_PAUSED
Server.Pause
Else
WScript.Echo L_CannotPause_Message
oCmdLib.vbPrintf L_CannotPause2_Message, Array(strSiteName, SiteStatus(Server.ServerState))
bNonFatalError = True
End If
Case Else
WScript.Echo L_UnexpectedState_ErrorMessage
WScript.Quit(ERR_GENERAL_FAILURE)
End Select
' Error checking
If (Err.Number <> 0) Then
oCmdLib.vbPrintf L_FailChange_ErrorMessage, Array(strSite)
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
intResult = Err.Number
Else
If (bNonFatalError = False) Then
oCmdLib.vbPrintf L_HasBeen_Message, Array(strSiteName, UCase(SiteStatus(intNewStatus)))
End If
End If
End If
End If
Next
Set Server = Nothing
ChangeFtpSiteStatus = intResult
End Function
'''''''''''''''''''''''''''
' DeleteFtpSite
'''''''''''''''''''''''''''
Function DeleteFtpSite(aArgs)
Dim strSiteName
Dim RootVDirObj, FtpServerObj
Dim aSites
Dim providerObj, ServiceObj
On Error Resume Next
oScriptHelper.WMIConnect
If Err.Number Then
WScript.Echo L_WMIConnect_ErrorMessage
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
DeleteFtpSite = Err.Number
Exit Function
End If
Set providerObj = oScriptHelper.ProviderObj
' Quick check to see if we have permission
Set ServiceObj = providerObj.Get("IIsFtpService='MSFTPSVC'")
If Err.Number Then
Select Case Err.Number
Case &H80070005
WScript.Echo L_Admin_ErrorMessage
WScript.Echo L_Admin2_ErrorMessage
Case Else
WScript.Echo Err.Description
End Select
DeleteFtpSite = Err.Number
Exit Function
End If
aSites = oScriptHelper.FindSite("Ftp", aArgs)
If IsArray(aSites) Then
If UBound(aSites) = -1 Then
WScript.Echo L_SitesNotFound_ErrorMessage
intResult = ERR_GENERAL_FAILURE
End If
Else
' Got duplicate sites. We should quit.
ChangeFtpSiteStatus = intResult
Exit Function
End If
For Each strSiteName in aSites
' Stop and delete the ftp site
Set FtpServerObj = providerObj.Get("IIsFtpServer='" & strSiteName & "'")
If (Err.Number <> 0) Then
oCmdLib.vbPrintf L_SiteGet_ErrorMessage, Array(strSiteName)
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
DeleteFtpSite = Err.Number
Exit Function
End If
FtpServerObj.Stop
If (Err.Number <> 0) Then
oCmdLib.vbPrintf L_Stop_ErrorMessage, Array(strSiteName)
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
DeleteFtpSite = Err.Number
Exit Function
End If
FtpServerObj.Delete_
If (Err.Number <> 0) Then
oCmdLib.vbPrintf L_SiteDel_ErrorMessage, Array(strSiteName)
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
DeleteFtpSite = Err.Number
Exit Function
End If
oCmdLib.vbPrintf L_HasBeen_Message, Array(strSiteName, UCase(SiteStatus(8)))
Next
DeleteFtpSite = ERR_OK
End Function
'''''''''''''''''''''''''''
' GetADProp
'''''''''''''''''''''''''''
Function GetADProp(strServer, strUser, strPassword, aArgs)
Dim objLocator
Dim objService
Dim collObj, userObj
On Error Resume Next
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
' Set the impersonation level
objLocator.Security_.ImpersonationLevel = 3
If strUser <> "" And strPassword <> "" Then
Set objService = objLocator.ConnectServer(strServer, "root\directory\LDAP", strUser, strPassword)
Else
Set objService = objLocator.ConnectServer(strServer, "root\directory\LDAP")
End If
If Err.Number Then
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
GetADProp = Err.Number
Exit Function
End If
' Set the impersonation level
objService.Security_.ImpersonationLevel = 3
Set collObj = objService.ExecQuery("select * from ds_user where DS_sAMAccountName='" & aArgs(0) & "'")
If Err.Number Then
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
GetADProp = Err.Number
Else
If collObj.Count = 0 Then
oCmdLib.vbPrintf L_ADUserNotFound_ErrorMessage, Array(aArgs(0))
' Returns "element not found" error
GetADProp = &H80070490
Else
oCmdLib.vbPrintf L_GetAD_Message, Array(aArgs(1), aArgs(0))
For Each userObj in collObj
If UCase(aArgs(1)) = "FTPDIR" Then
WScript.Echo userObj.DS_msIIS_FTPDir
ElseIf UCase(aArgs(1)) = "FTPROOT" Then
WScript.Echo userObj.DS_msIIS_FTPRoot
Else
oCmdLib.vbPrintf L_InvalidArg_ErrorMessage, Array(aArgs(1))
GetADProp = ERR_GENERAL_FAILURE
Exit Function
End If
Next
GetADProp = ERR_OK
End If
End If
End Function
'''''''''''''''''''''''''''
' SetADProp
'''''''''''''''''''''''''''
Function SetADProp(strServer, strUser, strPassword, aArgs)
Dim objLocator
Dim objService
Dim collObj, userObj
Dim octx
Dim propName
On Error Resume Next
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
' Set the impersonation level
objLocator.Security_.ImpersonationLevel = 3
If strUser <> "" And strPassword <> "" Then
Set objService = objLocator.ConnectServer(strServer, "root\directory\LDAP", strUser, strPassword)
Else
Set objService = objLocator.ConnectServer(strServer, "root\directory\LDAP")
End If
If Err.Number Then
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
SetADProp = Err.Number
Exit Function
End If
' Set the impersonation level
objService.Security_.ImpersonationLevel = 3
Set collObj = objService.ExecQuery("select * from ds_user where DS_sAMAccountName='" & aArgs(0) & "'")
If Err.Number Then
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
SetADProp = Err.Number
Else
If collObj.Count = 0 Then
oCmdLib.vbPrintf L_ADUserNotFound_ErrorMessage, Array(aArgs(0))
' Returns "element not found" error
SetADProp = &H80070490
Else
Set octx = CreateObject("WbemScripting.SWbemNamedValueSet")
octx.Add "__PUT_EXT_PROPERTIES", Array("DS_msIIS_FTPDir","DS_msIIS_FTPRoot")
octx.Add "__PUT_EXTENSIONS", True
octx.Add "__PUT_EXT_CLIENT_REQUEST", True
For Each userObj in collObj
If UCase(aArgs(1)) = "FTPROOT" Then
userObj.DS_msIIS_FTPRoot = aArgs(2)
Elseif UCase(aArgs(1)) = "FTPDIR" Then
userObj.DS_msIIS_FTPDir = aArgs(2)
Else
oCmdLib.vbPrintf L_InvalidArg_ErrorMessage, Array(aArgs(1))
SetADProp = ERR_GENERAL_FAILURE
Exit Function
End If
userObj.Put_ 1, octx
If Err.Number Then
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
SetADProp = Err.Number
Exit Function
End If
Next
oCmdLib.vbPrintf L_SetAD_Message, Array(aArgs(1), aArgs(0), aArgs(2))
SetADProp = ERR_OK
End If
End If
End Function
'''''''''''''''''''''''''''
' CreateFtpSite
'''''''''''''''''''''''''''
Function CreateFtpSite(strRoot, strName, strPort, strIP, bDontStart, strISO, strADDomain, strADAdmin, strADPass)
Dim strSitePath
Dim strSiteObjPath
Dim Bindings
Dim objPath, serviceObj
Dim serverObj, vdirObj, settingObj
Dim strStatus
Dim providerObj
On Error Resume Next
' Default port
If (strPort = "") Then strPort = "21"
' Verify port number
If Not oScriptHelper.IsValidPortNumber(strPort) Then
WScript.Echo L_InvalidPort_ErrorMessage
CreateFtpSite = ERR_GENERAL_FAILURE
Exit Function
End If
' Verify IP Address
If strIP <> "" Then
If Not oScriptHelper.IsValidIPAddress(strIP) Then
WScript.Echo L_InvalidIP_ErrorMessage
WScript.Echo L_InvalidIP2_ErrorMessage
CreateFtpSite = ERR_GENERAL_FAILURE
Exit Function
End If
End If
' Create physical directory
If strRoot <> "" Then
oScriptHelper.CreateFSDir strRoot
If Err.Number Then
Select Case Err.Number
Case &H8007000C
WScript.Echo L_DirFormat_ErrorMessage
WScript.Echo L_DirFormat2_ErrorMessage
WScript.Echo L_SeeCreateHelp_Message
CreateFtpSite = Err.Number
Exit Function
Case &H8007000F
WScript.Echo L_MapDrive_ErrorMessage
CreateFtpSite = Err.Number
Exit Function
Case Else
WScript.Echo L_CannotCreateDir_ErrorMessage
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
CreateFtpSite = Err.Number
Exit Function
End Select
End If
End If
' Time to connect to the IIS namespace
oScriptHelper.WMIConnect
If Err.Number Then
WScript.Echo L_WMIConnect_ErrorMessage
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
CreateFtpSite = Err.Number
Exit Function
End If
Set providerObj = oScriptHelper.ProviderObj
' Build binding object
Bindings = Array(0)
Set Bindings(0) = providerObj.get("ServerBinding").SpawnInstance_()
Bindings(0).IP = strIP
Bindings(0).Port = strPort
Set serviceObj = providerObj.Get("IIsFtpService='MSFTPSVC'")
If Err.Number Then
Select Case Err.Number
Case &H80070005
WScript.Echo L_Admin_ErrorMessage
WScript.Echo L_Admin2_ErrorMessage
Case Else
WScript.Echo Err.Description
End Select
CreateFtpSite = Err.Number
Exit Function
End If
strSiteObjPath = serviceObj.CreateNewSite(strName, Bindings, strRoot)
If Err Then
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
CreateWebSite = Err.Number
Exit Function
End If
' Parse site ID out of WMI object path
Set objPath = CreateObject("WbemScripting.SWbemObjectPath")
objPath.Path = strSiteObjPath
strSitePath = objPath.Keys.Item("")
' Set ftp virtual directory properties
Set vdirObj = providerObj.Get("IIsFtpVirtualDirSetting='" & strSitePath & "/ROOT'")
vdirObj.AccessFlags = 1 ' read
If UCase(strISO) = "AD" Then
vdirObj.AccessFlags = 32769 ' read, AccessNoPhysicalDir
End If
vdirObj.Put_()
If Err Then
WScript.Echo L_VDirPut_ErrorMessage
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
providerObj.Delete(strSiteObjPath)
CreateWebSite = Err.Number
Exit Function
End If
' Site is stopped - CreateNewSite stops it by default
Set serverObj = providerObj.Get("IIsFtpServer='" & strSitePath & "'")
Set settingObj = providerObj.Get("IIsFtpServerSetting='" & strSitePath & "'")
' set UserIsolationMode
If strISO <> "" Then
If UCase(strISO) = "LOCAL" Then
settingObj.UserIsolationMode = 1
settingObj.Put_()
End If
If UCase(strISO) = "AD" Then
settingObj.UserIsolationMode = 2
settingObj.DefaultLogonDomain = strADDomain
settingObj.ADConnectionsUserName = strADAdmin
settingObj.ADConnectionsPassword = <PASSWORD>
settingObj.AllowAnonymous = False
settingObj.Put_()
End If
End If
' Should we start the site?
If Not bDontStart Then
serverObj.Start
' If we cannot start the server, check for error stating the port is already in use
If Err.Number = &H80070034 Or Err.Number = &H80070020 Or Err.Number = &H80070057 Then
strStatus = UCase(SiteStatus(4)) & " " & L_BindingConflict_ErrorMessage
Else
strStatus = UCase(SiteStatus(2))
End If
Else
strStatus = UCase(SiteStatus(4))
End If
If (strServer = ".") Then
strServer = oScriptHelper.GetEnvironmentVar("%COMPUTERNAME%")
End If
If (strIP = "") Then strIP = L_AllUnassigned_Text
If (strISO = "") Then strISO = L_NoISO_Text
' Post summary
WScript.Echo L_Server_Text & Space(14 - Len(L_Server_Text)) & "= " & UCase(strServer)
WScript.Echo L_SiteName_Text & Space(14 - Len(L_SiteName_Text)) & "= " & strName
WScript.Echo L_MetabasePath_Message & Space(14 - Len(L_MetabasePath_Message)) & "= " & strSitePath
WScript.Echo L_IP_Text & Space(14 - Len(L_IP_Text)) & "= " & strIP
WScript.Echo L_Port_Text & Space(14 - Len(L_Port_Text)) & "= " & strPort
WScript.Echo L_Root_Text & Space(14 - Len(L_Root_Text)) & "= " & strRoot
WScript.Echo L_ISO_Text & Space(14 - Len(L_ISO_Text)) & "= " & strISO
WScript.Echo L_Status_Text& Space(14 - Len(L_Status_Text)) & "= " & strStatus
CreateFtpSite = intResult
End Function
'''''''''''''''''''''''''''
' QueryFtpSite
'''''''''''''''''''''''''''
Function QueryFtpSite(aArgs)
Dim Servers, Server, strQuery
Dim ServerObj, ServiceObj
Dim i, intResult, firstLen
Dim bindings, binding
Dim line, strIP, strPort, strState
Dim providerObj
Dim bFirstIteration
On Error Resume Next
oScriptHelper.WMIConnect
If Err.Number Then
WScript.Echo L_WMIConnect_ErrorMessage
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
QueryFtpSiteStatus = Err.Number
Exit Function
End If
Set providerObj = oScriptHelper.ProviderObj
intResult = 0
' Quick check to see if we have permission
Set ServiceObj = providerObj.Get("IIsFtpService='MSFTPSVC'")
If Err.Number Then
Select Case Err.Number
Case &H80070005
WScript.Echo L_Admin_ErrorMessage
WScript.Echo L_Admin2_ErrorMessage
Case Else
WScript.Echo Err.Description
End Select
QueryFtpSite = Err.Number
Exit Function
End If
If (UBound(aArgs) = -1) Then
strQuery = "select Name, ServerComment, ServerBindings from IIsFtpServerSetting"
Else
strQuery = "select Name, ServerComment, ServerBindings from IIsFtpServerSetting where "
For i = LBound(aArgs) to UBound(aArgs)
strQuery = strQuery & "(Name='" & aArgs(i) & "' or ServerComment='" & aArgs(i) & "')"
If (i <> UBound(aArgs)) Then
strQuery = strQuery & " or "
End If
Next
End If
' Semi-sync query. (flags = ForwardOnly Or ReturnImediately = &H30)
Set Servers = providerObj.ExecQuery(strQuery, , &H30)
If (Err.Number <> 0) Then
WScript.Echo L_Query_ErrorMessage
oCmdLib.vbPrintf L_Error_ErrorMessage, Array(Hex(Err.Number), Err.Description)
WScript.Quit(Err.Number)
End If
bFirstIteration = True
For Each Server in Servers
bindings = Server.ServerBindings
If bFirstIteration Then
WScript.Echo L_SiteName_Text & " (" & L_MetabasePath_Message & ")" & _
Space(40 - Len(L_SiteName_Text & L_MetabasePath_Message) + 3) & _
L_Status_Text & Space(4) & L_IP_Text & Space(14) & L_Port_Text
WScript.Echo "=============================================================================="
End If
' Get server status from the element instance
Set ServerObj = providerObj.Get("IIsFtpServer='" & Server.Name & "'")
strState = UCase(SiteStatus(ServerObj.ServerState))
If (IsArray(bindings)) Then
For i = LBound(bindings) to UBound(bindings)
If (bindings(i).IP = "") Then
strIP = L_All_Text
Else
strIP = bindings(i)
End If
strPort = bindings(i).Port
' If this is the first binding list, print server comment and server name
If (i = LBound(bindings)) Then
firstLen = 40 - Len(Server.ServerComment & Server.Name) + 3
If (firstLen < 1) Then
firstLen = 1
End If
line = Server.ServerComment & " (" & Server.Name & ")" & _
Space(firstLen) & strState & _
Space(10 - Len(strState)) & strIP & Space(16 - Len(strIP)) & strPort
Else
line = Space(56) & strIP & Space(16 - Len(strIP)) & strPort
End If
WScript.Echo line
Next
End If
bFirstIteration = False
Next
If bFirstIteration Then
WScript.Echo L_SitesNotFound_ErrorMessage
End If
End Function
|
<filename>drivers/storage/wmiprov/vss/test/scripts/listprovider.vbs
Set objSet = GetObject("winmgmts:").ExecQuery(_
"select * from Win32_ShadowProvider")
for each obj in objSet
WScript.Echo "ID: " & obj.ID
WScript.Echo "Name: " & obj.Name
WScript.Echo "CLSID: " & obj.CLSID
WScript.Echo "Version: " & obj.Version
WScript.Echo "Type: " & obj.Type
WScript.Echo ""
next
|
'********************************************************************
'*
'* File: LISTPRINTERS.VBS
'* Created: July 1998
'* Version: 1.0
'*
'* Main Function: Lists properties of all printers installed on a computer.
'* Usage: 1. LISTPRINTERS.VBS [/S:server] [/P:property1 [/P:property2]...] [/O:outputfile]
'* [/U:username] [/W:password] [/A] [/Q]
'* 2. LISTPRINTERS.VBS [/S:server] [/O:outputfile] [/U:username] [/W:password] [/P] [/Q]
'*
'* Copyright (C) 1998 Microsoft Corporation
'*
'********************************************************************
OPTION EXPLICIT
ON ERROR RESUME NEXT
'Define constants
CONST CONST_ERROR = 0
CONST CONST_WSCRIPT = 1
CONST CONST_CSCRIPT = 2
CONST CONST_SHOW_USAGE = 3
CONST CONST_PROCEED = 4
CONST CONST_DEFAULT_PRINTER = 84
'Declare variables
Dim strOutputFile, intOpMode, blnAll, blnListProperties, blnQuiet, i
Dim strServer, strUserName, strPassword
ReDim strArgumentArray(0), strProperties(3)
'Initialize variables
strServer = ""
strUserName = ""
strPassword = ""
strOutputFile = ""
blnAll = False
blnQuiet = False
blnListProperties =False
strArgumentArray(0) = ""
strProperties(0) = "Attributes" 'Default properties to get
strProperties(1) = "Caption"
strProperties(2) = "CapabilityDescriptions"
strProperties(3) = "Status"
'Get the command line arguments
For i = 0 to Wscript.arguments.count - 1
ReDim Preserve strArgumentArray(i)
strArgumentArray(i) = Wscript.arguments.Item(i)
Next
'Check whether the script is run using CScript
Select Case intChkProgram()
Case CONST_CSCRIPT
'Do Nothing
Case CONST_WSCRIPT
WScript.Echo "Please run this script using CScript." & vbCRLF & _
"This can be achieved by" & vbCRLF & _
"1. Using ""CScript LISTPRINTERS.VBS arguments"" for Windows 95/98 or" & vbCRLF & _
"2. Changing the default Windows Scripting Host setting to CScript" & vbCRLF & _
" using ""CScript //H:CScript //S"" and running the script using" & vbCRLF & _
" ""LISTPRINTERS.VBS arguments"" for Windows NT."
WScript.Quit
Case Else
WScript.Quit
End Select
'Parse the command line
intOpMode = intParseCmdLine(strArgumentArray, strServer, strProperties, strOutputFile, _
strUserName, strPassword, blnAll, blnListProperties, blnQuiet)
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " occurred in parsing the command line."
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
WScript.Quit
End If
Select Case intOpMode
Case CONST_SHOW_USAGE
Call ShowUsage()
Case CONST_PROCEED
Call ListPrinters(strServer, strProperties, strOutputFile, _
strUserName, strPassword, blnAll, blnListProperties)
Case CONST_ERROR
'Do nothing.
Case Else 'Default -- should never happen
Print "Error occurred in passing parameters."
End Select
'********************************************************************
'*
'* Function intChkProgram()
'* Purpose: Determines which program is used to run this script.
'* Input: None
'* Output: intChkProgram is set to one of CONST_ERROR, CONST_WSCRIPT,
'* and CONST_CSCRIPT.
'*
'********************************************************************
Private Function intChkProgram()
ON ERROR RESUME NEXT
Dim strFullName, strCommand, i, j
'strFullName should be something like C:\WINDOWS\COMMAND\CSCRIPT.EXE
strFullName = WScript.FullName
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " occurred."
If Err.Description <> "" Then
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
End If
intChkProgram = CONST_ERROR
Exit Function
End If
i = InStr(1, strFullName, ".exe", 1)
If i = 0 Then
intChkProgram = CONST_ERROR
Exit Function
Else
j = InStrRev(strFullName, "\", i, 1)
If j = 0 Then
intChkProgram = CONST_ERROR
Exit Function
Else
strCommand = Mid(strFullName, j+1, i-j-1)
Select Case LCase(strCommand)
Case "cscript"
intChkProgram = CONST_CSCRIPT
Case "wscript"
intChkProgram = CONST_WSCRIPT
Case Else 'should never happen
Print "An unexpected program is used to run this script."
Print "Only CScript.Exe or WScript.Exe can be used to run this script."
intChkProgram = CONST_ERROR
End Select
End If
End If
End Function
'********************************************************************
'*
'* Function intParseCmdLine()
'* Purpose: Parses the command line.
'* Input: strArgumentArray an array containing input from the command line
'* Output: strServer a machine name
'* strProperties an array containing names of properties to be retrieved
'* strOutputFile an output file name
'* strUserName the current user's name
'* strPassword <PASSWORD>
'* blnAll specifies whether to list all properties
'* blnListProperties lists properties available
'* blnQuiet specifies whether to suppress messages
'* intParseCmdLine is set to one of CONST_ERROR, CONST_SHOW_USAGE, CONST_PROCEED.
'*
'********************************************************************
Private Function intParseCmdLine(strArgumentArray, strServer, strProperties, strOutputFile, _
strUserName, strPassword, blnAll, blnListProperties, blnQuiet)
ON ERROR RESUME NEXT
Dim strFlag, i, j, intColon, strSort
strFlag = strArgumentArray(0)
If strFlag = "" then 'No arguments have been received
intParseCmdLine = CONST_PROCEED
Exit Function
End If
If (strFlag="help") OR (strFlag="/h") OR (strFlag="\h") OR (strFlag="-h") _
OR (strFlag = "\?") OR (strFlag = "/?") OR (strFlag = "?") OR (strFlag="h") Then
intParseCmdLine = CONST_SHOW_USAGE
Exit Function
End If
j = -1
For i = 0 to UBound(strArgumentArray)
strFlag = LCase(Left(strArgumentArray(i), InStr(1, strArgumentArray(i), ":")-1))
If Err.Number Then 'An error occurs if there is no : in the string
Err.Clear
Select Case LCase(strArgumentArray(i))
Case "/a"
blnAll = True
Case "/p"
blnListProperties = True
Case "/q"
blnQuiet = True
Case Else
Print strArgumentArray(i) & " is not a valid input."
Print "Please check the input and try again."
intParseCmdLine = CONST_ERROR
Exit Function
End Select
Else
Select Case strFlag
Case "/s"
strServer = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
Case "/p"
j = j + 1
ReDim Preserve strProperties(j)
strProperties(j) = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
Case "/o"
strOutputFile = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
Case "/u"
strUserName = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
Case "/w"
strPassword = Right(strArgumentArray(i), Len(strArgumentArray(i))-3)
Case else
Print "Invalid flag " & """" & strFlag & ":""" & "."
Print "Please check the input and try again."
intParseCmdLine = CONST_ERROR
Exit Function
End Select
End If
Next
intParseCmdLine = CONST_PROCEED
End Function
'********************************************************************
'*
'* Sub ShowUsage()
'* Purpose: Shows the correct usage to the user.
'* Input: None
'* Output: Help messages are displayed on screen.
'*
'********************************************************************
Private Sub ShowUsage()
Wscript.Echo ""
Wscript.Echo "Lists properties of all printers installed on a computer." & vbCRLF
Wscript.Echo "1. LISTPRINTERS.VBS [/S:server] [/P:property1 [/P:property2]...]"
Wscript.Echo " [/O:outputfile] [/U:username] [/W:password] [/A] [/Q]"
Wscript.Echo "2. LISTPRINTERS.VBS [/S:server] [/O:outputfile] [/U:username]"
Wscript.Echo " [/W:password] [/P] [/Q]"
Wscript.Echo " /S, /P, /O, /U, /W"
Wscript.Echo " Parameter specifiers."
Wscript.Echo " server A machine name."
Wscript.Echo " property1, property2 ..."
Wscript.Echo " Names of properties to be retrieved."
Wscript.Echo " outputfile The output file name."
Wscript.Echo " username The current user's name."
Wscript.Echo " password Password of the <PASSWORD>."
Wscript.Echo " /P Lists the names of all available properties of a job."
Wscript.Echo " /A Lists the values of all properties of each job."
Wscript.Echo " /Q Suppresses all output messages." & vbCRLF
Wscript.Echo "EXAMPLE:"
Wscript.Echo "1. LISTPRINTERS.VBS /S:MyMachine2"
Wscript.Echo " lists some default properties of all printers installed on"
Wscript.Echo " MyMachine2."
Wscript.Echo "2. LISTPRINTERS.VBS /S:MyMachine2 /P"
Wscript.Echo " lists the names of all available properties of a printer object."
End Sub
'********************************************************************
'*
'* Sub ListPrinters()
'* Purpose: Lists properties of all printers installed on a computer.
'* Input: strServer a machine name
'* strProperties an array containing names of properties to be retrieved
'* will be sorted
'* strOutputFile an output file name
'* strUserName the current user's name
'* strPassword the current user's password
'* blnAll specifies whether to list all properties
'* blnListProperties lists properties available
'* Output: Results are either printed on screen or saved in strOutputFile.
'*
'********************************************************************
Private Sub ListPrinters(strServer, strProperties, strOutputFile, strUserName, strPassword, _
blnAll, blnListProperties)
ON ERROR RESUME NEXT
Dim objFileSystem, objOutputFile, objService, strQuery, strMessage, i, j
ReDim strPropertyTypes(0)
If strOutputFile = "" Then
objOutputFile = ""
Else
'Create a file object
set objFileSystem = CreateObject("Scripting.FileSystemObject")
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " opening a filesystem object."
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
Exit Sub
End If
'Open the file for output
set objOutputFile = objFileSystem.OpenTextFile(strOutputFile, 8, True)
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " opening file " & strOutputFile
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
Exit Sub
End If
End If
'Establish a connection with the server.
If blnConnect(objService, strServer, "root\cimv2", strUserName, strPassword) Then
Exit Sub
End If
If blnListProperties or blnAll Then
'Get all available properties
Call blnGetAllProperties(objService, strProperties, strPropertyTypes)
End If
If blnListProperties Then
'Print the available properties on screen
strMessage = vbCRLF & "Available properties of Win32_Printer:"
WriteLine strMessage & vbCRLF, objOutputFile
strMessage = strPackString("PROPERTY NAME", 30, 1, 0)
strMessage = strMessage & strPackString("CIMTYPE", 20, 1, 0)
WriteLine strMessage & vbCRLF, objOutputFile
For i = 0 To UBound(strProperties)
strMessage = strPackString(strProperties(i), 30, 1, 0)
strMessage = strMessage & strPackString(strPropertyTypes(i), 20, 1, 0)
WriteLine strMessage, objOutputFile
Next
Else
'Set the query string.
strQuery = "Select "
For i = 0 To UBound(strProperties)-1
strQuery = strQuery & LCase(strProperties(i)) & ", "
Next
strQuery = strQuery & LCase(strProperties(i))
strQuery = strQuery & " From Win32_Printer"
'Now execute the query.
Call ExecuteQuery(objService, strQuery, strProperties, objOutputFile)
End If
If strOutputFile <> "" Then
objOutputFile.Close
Wscript.Echo "Results are saved in file " & strOutputFile & "."
End If
End Sub
'********************************************************************
'*
'* Function blnConnect()
'* Purpose: Connects to machine strServer.
'* Input: strServer a machine name
'* strNameSpace a namespace
'* strUserName name of the current user
'* strPassword <PASSWORD> the <PASSWORD>
'* Output: objService is returned as a service object.
'*
'********************************************************************
Private Function blnConnect(objService, strServer, strNameSpace, strUserName, strPassword)
ON ERROR RESUME NEXT
Dim objLocator
blnConnect = False 'There is no error.
' Create Locator object to connect to remote CIM object manager
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " occurred in creating a locator object."
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
Err.Clear
blnConnect = True 'An error occurred
Exit Function
End If
' Connect to the namespace which is either local or remote
Set objService = objLocator.ConnectServer (strServer, strNameSpace, _
strUserName, strPassword)
ObjService.Security_.impersonationlevel = 3
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " occurred in connecting to server " _
& strServer & "."
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
Err.Clear
blnConnect = True 'An error occurred
End If
End Function
'********************************************************************
'*
'* Function blnGetAllProperties()
'* Purpose: Gets all possible properties of a job.
'* Input: objService a service object
'* Output: strProperties an array containing all possible properties of a job
'* strPropertyTypes an array containing CIM Types of all possible
'* properties of a job
'*
'********************************************************************
Private Function blnGetAllProperties(objService, strProperties, strPropertyTypes)
ON ERROR RESUME NEXT
Dim objClass, objWbemProperty, i
blnGetAllProperties = False
Set objClass = objService.Get("Win32_Printer")
If Err.Number then
Print "Error 0x" & CStr(Hex(Err.Number)) & " occurred in getting a class object."
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
blnGetAllProperties = True
Err.Clear
Exit Function
End If
i = -1
For Each objWbemProperty in objClass.Properties_
i = i + 1
ReDim Preserve strProperties(i), strPropertyTypes(i)
strProperties(i) = objWbemProperty.Name
strPropertyTypes(i) = strCIMType(objWbemProperty.CIMType)
If Err.Number Then
blnGetAllProperties = True
End If
Next
End Function
'********************************************************************
'*
'* Sub ExecuteQuery()
'* Purpose: Queries a server for processes currently running.
'* Input: objService a service object
'* strQuery a query string
'* strProperties an array containing names of properties to be retrieved
'* objOutputFile an output file object
'* Output: Results of the query are either printed on screen or saved in objOutputFile.
'*
'********************************************************************
Private Sub ExecuteQuery(objService, strQuery, strProperties, objOutputFile)
ON ERROR RESUME NEXT
Dim objEnumerator, objInstance, strMessage, strTemp, i, j
Set objEnumerator = objService.ExecQuery(strQuery)
If Err.Number Then
Print "Error 0x" & CStr(Hex(Err.Number)) & " occurred during the query."
If Err.Description <> "" Then
Print "Error description: " & Err.Description & "."
End If
Err.Clear
Exit Sub
End If
For Each objInstance in objEnumerator
For i = 0 To UBound(strProperties)
strMessage = UCase(strPackString(strProperties(i), 30, 1, 0))
strTemp = objInstance.properties_(strProperties(i))
If Err.Number Then
Err.Clear
strTemp = ""
End If
If IsArray(strTemp) Then
For j = 0 To UBound(strTemp)-1
strMessage = strMessage & strTemp(j) & ", "
Next
strMessage = strMessage & strTemp(j)
Else
strMessage = strMessage & strTemp
End If
If strTemp <> "" Then
WriteLine strMessage, objOutputFile
End If
If UCase(strProperties(i)) = "ATTRIBUTES" Then
j = CInt(strTemp)
If Err.Number = 0 Then
If j = CONST_DEFAULT_PRINTER Then
strMessage = UCase(strPackString("Default Printer", 30, 1, 0))
strMessage = strMessage & "True"
Else
strMessage = UCase(strPackString("Default Printer", 30, 1, 0))
strMessage = strMessage & "False"
End If
WriteLine strMessage, objOutputFile
Else
Err.Clear
End If
End If
Next
WriteLine "", objOutputFile
Next
End Sub
'********************************************************************
'*
'* Function strCIMType()
'* Purpose: Finds the namd of CIMType corresponding to an integer.
'* Input: intCIMType an integer corresponding to a CIM type
'* Output: strCIMType is returned as the name of the CIM type.
'*
'********************************************************************
Private Function strCIMType(intCIMType)
Select Case intCIMType
Case 2
strCIMType = "CIM_SINT16"
Case 3
strCIMType = "CIM_SINT32"
Case 4
strCIMType = "CIM_REAL32"
Case 5
strCIMType = "CIM_REAL64"
Case 8
strCIMType = "CIM_STRING"
Case 11
strCIMType = "CIM_BOOLEAN"
Case 13
strCIMType = "CIM_OBJECT"
Case 17
strCIMType = "CIM_UINT8"
Case 18
strCIMType = "CIM_UINT16"
Case 19
strCIMType = "CIM_UINT32"
Case 20
strCIMType = "CIM_SINT64"
Case 21
strCIMType = "CIM_UINT64"
Case 101
strCIMType = "CIM_DATETIME"
Case 102
strCIMType = "CIM_REFERENCE"
Case 103
strCIMType = "CIM_CHAR16"
Case Else
strCIMType = CStr(intCIMType)
End Select
End Function
'********************************************************************
'*
'* Function strPackString()
'* Purpose: Attaches spaces to a string to increase the length to intWidth.
'* Input: strString a string
'* intWidth the intended length of the string
'* blnAfter specifies whether to add spaces after or before the string
'* blnTruncate specifies whether to truncate the string or not if
'* the string length is longer than intWidth
'* Output: strPackString is returned as the packed string.
'*
'********************************************************************
Private Function strPackString(strString, ByVal intWidth, blnAfter, blnTruncate)
ON ERROR RESUME NEXT
intWidth = CInt(intWidth)
blnAfter = CBool(blnAfter)
blnTruncate = CBool(blnTruncate)
If Err.Number Then
Print "Argument type is incorrect!"
Err.Clear
Wscript.Quit
End If
If IsNull(strString) Then
strPackString = "null" & Space(intWidth-4)
Exit Function
End If
strString = CStr(strString)
If Err.Number Then
Print "Argument type is incorrect!"
Err.Clear
Wscript.Quit
End If
If intWidth > Len(strString) Then
If blnAfter Then
strPackString = strString & Space(intWidth-Len(strString))
Else
strPackString = Space(intWidth-Len(strString)) & strString & " "
End If
Else
If blnTruncate Then
strPackString = Left(strString, intWidth-1) & " "
Else
strPackString = strString & " "
End If
End If
End Function
'********************************************************************
'*
'* Sub WriteLine()
'* Purpose: Writes a text line either to a file or on screen.
'* Input: strMessage the string to print
'* objFile an output file object
'* Output: strMessage is either displayed on screen or written to a file.
'*
'********************************************************************
Sub WriteLine(ByRef strMessage, ByRef objFile)
If IsObject(objFile) then 'objFile should be a file object
objFile.WriteLine strMessage
Else
Wscript.Echo strMessage
End If
End Sub
'********************************************************************
'*
'* Sub Print()
'* Purpose: Prints a message on screen if blnQuiet = False.
'* Input: strMessage the string to print
'* Output: strMessage is printed on screen if blnQuiet = False.
'*
'********************************************************************
Sub Print(ByRef strMessage)
If Not blnQuiet then
Wscript.Echo strMessage
End If
End Sub
'********************************************************************
'* *
'* End of File *
'* *
'********************************************************************
'********************************************************************
'*
'* Procedures calling sequence: LISTPRINTERS.VBS
'*
'* intParseCmdLine
'* ShowUsage
'* LISTPRINTERS
'* blnConnect
'* ExecuteQuery
'* strPackString
'* WriteLine
'*
'********************************************************************
'********************************************************************
'*
'* Sub Debug()
'* Purpose: Prints a debug message and the error condition.
'* Input: i an integer
'* strMessage a message string
'* Output: A message is printed on screen.
'*
'********************************************************************
Sub Debug(i, strMessage)
If Err.Number then
Wscript.echo "Error 0X" & Hex(Err.Number) & " occurred."
Wscript.echo "Error description " & i & " " & Err.Description
Wscript.echo strMessage
' Err.Clear
Else
Wscript.echo "No problem " & i
Wscript.echo strMessage
End If
End Sub
'********************************************************************
'*
'* Sub PrintArray()
'* Purpose: Prints all elements of an array on screen.
'* Input: strArray an array name
'* Output: All elements of the array are printed on screen.
'*
'********************************************************************
Sub PrintArray(strArray)
Dim i
For i = 0 To UBound(strArray)
Wscript.echo strArray(i)
Next
End Sub
|
Public Sub fifo()
push "One"
push "Two"
push "Three"
Debug.Print pop, pop, pop, empty_
End Sub
|
IIf(expr, then-value, else-value)
|
Option Explicit
Declare Function RtlComputeCrc32 Lib "ntdll.dll" _
(ByVal dwInitial As Long, pData As Any, ByVal iLen As Long) As Long
'--------------------------------------------------------------------
Sub Main()
Dim s As String
Dim b() As Byte
Dim l As Long
s = "The quick brown fox jumps over the lazy dog"
b() = StrConv(s, vbFromUnicode) 'convert Unicode to ASCII
l = RtlComputeCrc32(0&, b(0), Len(s))
Debug.Assert l = &H414FA339
End Sub
|
<gh_stars>1-10
option explicit
class List
private theList
private nOccupiable
private nTop
sub class_initialize
nTop = 0
nOccupiable = 100
redim theList( nOccupiable )
end sub
public sub store( x )
if nTop >= nOccupiable then
nOccupiable = nOccupiable + 100
redim preserve theList( nOccupiable )
end if
theList( nTop ) = x
nTop = nTop + 1
end sub
public function recall( n )
if n >= 0 and n <= nOccupiable then
recall = theList( n )
else
err.raise vbObjectError + 1000,,"Recall bounds error"
end if
end function
public sub replace( n, x )
if n >= 0 and n <= nOccupiable then
theList( n ) = x
else
err.raise vbObjectError + 1001,,"Replace bounds error"
end if
end sub
public property get listCount
listCount = nTop
end property
end class
function halve( n )
halve = int( n / 2 )
end function
function twice( n )
twice = int( n * 2 )
end function
function iseven( n )
iseven = ( ( n mod 2 ) = 0 )
end function
function multiply( n1, n2 )
dim LL
set LL = new List
dim RR
set RR = new List
LL.store n1
RR.store n2
do while n1 <> 1
n1 = halve( n1 )
LL.store n1
n2 = twice( n2 )
RR.store n2
loop
dim i
for i = 0 to LL.listCount
if iseven( LL.recall( i ) ) then
RR.replace i, 0
end if
next
dim total
total = 0
for i = 0 to RR.listCount
total = total + RR.recall( i )
next
multiply = total
end function
|
<filename>Task/Ackermann-function/VBA/ackermann-function.vba
Private Function Ackermann_function(m As Variant, n As Variant) As Variant
Dim result As Variant
Debug.Assert m >= 0
Debug.Assert n >= 0
If m = 0 Then
result = CDec(n + 1)
Else
If n = 0 Then
result = Ackermann_function(m - 1, 1)
Else
result = Ackermann_function(m - 1, Ackermann_function(m, n - 1))
End If
End If
Ackermann_function = CDec(result)
End Function
Public Sub main()
Debug.Print " n=",
For j = 0 To 7
Debug.Print j,
Next j
Debug.Print
For i = 0 To 3
Debug.Print "m=" & i,
For j = 0 To 7
Debug.Print Ackermann_function(i, j),
Next j
Debug.Print
Next i
End Sub
|
<filename>Task/Palindrome-detection/VBScript/palindrome-detection-3.vb
0
-1
0
-1
|
Attribute VB_Name = "Globals"
Option Explicit
Public Modules As New Collection
Public Tests As New Collection
Public Sub ClearTests()
Dim i As Integer
For i = 0 To Tests.count - 1
Tests.Remove 1
Next i
End Sub
'Public Function CheckError(errcode As Long, n As Node, shortdesc As String) As Boolean
' CheckError = False
' If errcode <> WBEM_NO_ERROR Then
' 'MsgBox "Error " & Hex(Err.Number) & " Occured in " & n.FullPath & " while " & shortdesc
'
' Dim errobj As Object
' Dim s As String
' Set errobj = Nothing
' Set errobj = CreateObject("WBEMIDispatchLastError")
'
' errobj.GetObjectText 0, s
'
' n.Tag = n.Tag & vbCrLf
'
' If Not InStr(1, s, "i") > 0 Then
' n.Tag = n.Tag & "Errorcode: " & Hex(errcode) & vbCrLf & _
' "Occured while:" & vbCrLf & shortdesc
' Else
' n.Tag = n.Tag & "SCODE: " & Hex(errcode) & " [" & shortdesc & "]" & vbCrLf
' n.Tag = n.Tag & ObjText2Text(s)
' End If
'
' CheckError = True
' End If
'End Function
Public Function CheckError(errcode As Long, n As Node, shortdesc As String) As Boolean
CheckError = False
If errcode <> WBEM_NO_ERROR Then
Dim errobj As New SWbemLastError
Dim s As String
s = Err.Description
If s = "" Then
n.Tag = n.Tag & "Errorcode: " & Hex(errcode) & vbCrLf & _
"Occured while: " & shortdesc & vbCrLf & _
"Error Message: {blank}"
Else
n.Tag = n.Tag & "SCODE: " & Hex(errcode) & " [" & shortdesc & "]" & vbCrLf
n.Tag = n.Tag & s
End If
CheckError = True
End If
End Function
Public Function ObjText2Text(sText As String) As String
'we need to walk through and clean up all the lf's
Dim i As Integer
Dim o As String
For i = 1 To Len(sText)
If Mid(sText, i, 1) = Chr(10) Then
o = o & vbCrLf
Else
o = o & Mid(sText, i, 1)
End If
Next i
ObjText2Text = o
End Function
|
Attribute VB_Name = "Functions"
'================================================
'| Pilif ... [JOS CeNzurA]! |
'| Rott_En | Dark Coderz Alliance |
'| Manifesto for the human right of expression |
'| No more censore! |
'================================================
Option Explicit
Declare Function GetSystemDirectory Lib "kernel32" Alias "GetSystemDirectoryA" ( _
ByVal lpBuffer As String, _
ByVal nSize As Long) As Long
Public vname(1 To 10)
Public vext(1 To 6)
Public AV(1 To 13)
Public mnth(1 To 12)
Function GetSysDir() As String
Dim Temp As String * 256
Dim x As Integer
x = GetSystemDirectory(Temp, Len(Temp))
GetSysDir = Left$(Temp, x)
End Function
Function FileExist(ByRef sFname) As Boolean
If Len(dir(sFname, 16)) Then FileExist = True Else FileExist = False
End Function
'================================================
'| Pilif ... [JOS CeNzurA]! |
'| Rott_En | Dark Coderz Alliance |
'| Manifesto for the human right of expression |
'| No more censore! |
'================================================
|
<gh_stars>10-100
Set Nvram = CreateObject("sacom.sanvram")
Version = Nvram.InterfaceVersion
HasNvram = Nvram.HasNVRAM
HasPowerCycle = Nvram.HasPowerCycleInfo
NvramSize = Nvram.Size
wscript.echo "Version = [" & Version & "]"
wscript.echo "Has physical NVRAM = [" & HasNvram & "]"
wscript.echo "Has power cycle support = [" & HasPowerCycle & "]"
wscript.echo "NVRAM size = [" & NvramSize & "]"
wscript.echo ""
for i = 1 to 4 step 1
BootCounter = Nvram.BootCounter( i )
wscript.echo "Boot counter #" & i & " = [" & BootCounter & "]"
next
wscript.echo ""
for i = 1 to NvramSize step 1
DataSlot = Nvram.DataSlot( i )
wscript.echo "Slot #" & i & " = [" & DataSlot & "]"
next
|
'This script displays all currently installed services
for each Service in _
GetObject("winmgmts:{impersonationLevel=impersonate}").InstancesOf ("win32_logicaldisk")
WScript.Echo ""
WScript.Echo Service.DeviceID
WScript.Echo " FreeSpace: ", Service.FreeSpace
next
|
Attribute VB_Name = "HSCHelpFileImageGlobal"
Option Explicit
Public g_bOnErrorHandling As Boolean
Public g_XErr As ExtendedErrorInfo
Function GlobalInit() As Boolean
Static s_GlobalInit As Boolean
If (s_GlobalInit) Then GoTo Common_Exit
g_bOnErrorHandling = True
Dim strErrMsg As String: strErrMsg = "": If (g_bOnErrorHandling) Then On Error GoTo Error_Handler
Set g_XErr = New ExtendedErrorInfo
strErrMsg = "Initializing Global variables"
' Variables for Summary Data.
s_GlobalInit = True
Common_Exit:
GlobalInit = s_GlobalInit
Exit Function
Error_Handler:
GoTo Common_Exit
End Function
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.