Search is not available for this dataset
content
stringlengths
0
376M
<gh_stars>1-10 ' This script converts Xilinx Vivado executable path to Xilinx SDK executable path. ' (The Vivado path is stored in the registry, but the SDK path is not. This helper script solves this.) ' Usage: ' cscript sdkpath.vbs <Xilinx Vivado executable path> ' Example: ' cscript /NoLogo sdkpath.vbs C:\Xilinx\Vivado\2015.4\bin\unwrapped\win64.o\vvgl.exe ' Example output: ' C:\Xilinx\SDK\2015.4\bin\xsdk.bat Set fso = CreateObject("Scripting.FileSystemObject") Path = WScript.Arguments.Item(0) WhereIsVivado = InStr(Path,"\Vivado") XilinxBaseDir = Left(Path, WhereIsVivado) 'WScript.Echo XilinxBaseDir AfterVivado = Mid(Path, WhereIsVivado + 8) 'WScript.Echo AfterVivado WhereIsNextBackslash = InStr(AfterVivado,"\") DirVersion = Left(AfterVivado, WhereIsNextBackslash-1) SdkBatchPath = XilinxbaseDir+"SDK\"+DirVersion+"\bin\xsdk.bat" 'WScript.Echo SdkBatchPath If Not fso.FileExists(SdkBatchPath) Then MsgBox "sdkpath.vbs could not find Xilinx SDK at:" + VbCrLf + SdkBatchPath + VbCrLf + "- Check if Xilinx SDK is installed." + VbCrLf + "- Try manually importing projects to the SDK.", 48 End If WScript.Echo SdkBatchPath
Sub Main() '... If problem Then For n& = Forms.Count To 0 Step -1 Unload Forms(n&) Next Exit Sub End If '... End Sub
Function ASCII_Sequence(range) arr = Split(range,"..") For i = Asc(arr(0)) To Asc(arr(1)) ASCII_Sequence = ASCII_Sequence & Chr(i) & " " Next End Function WScript.StdOut.Write ASCII_Sequence(WScript.Arguments(0)) WScript.StdOut.WriteLine
<reponame>ChristianWulf/grammars-v4<gh_stars>100-1000 2 print tab(33);"LOVE" 6 PRINT 7 PRINT 8 PRINT 20 rem PRINT "THANKS TO <NAME> AND <NAME>" 21 rem print "contributed by <EMAIL> 1996" 51 PRINT 60 INPUT "YOUR MESSAGE, PLEASE"; A$ 61 L=LEN(A$) 70 DIM T$(120) 71 FOR I = 1 to 10 72 PRINT 73 NEXT I 100 FOR J=0 to INT(60/L) 110 FOR I=1 to L 120 T$(J*L+I)=MID$(A$,I,1) 130 NEXT I 131 NEXT J 140 C=0 200 A1=1 201 P=1 202 C=C+1 203 IF C=37 then 999 205 PRINT 210 READ A 211 A1=A1+A 212 IF P=1 then 300 240 FOR I=1 to A 241 PRINT " "; 242 NEXT I 243 P=1 244 GOTO 400 300 FOR I=A1-A TO A1-1 301 PRINT T$(I); 302 NEXT I 303 P=0 400 IF A1>60 THEN 200 410 GOTO 210 600 DATA 60,1,12,26,9,12,3,8,24,17,8,4, 6, 23, 21, 6, 4, 6, 22, 12, 5, 6, 5 610 DATA 4,6,21,11,8,6,4,4,6,21,10,10,5,4,4,6,21,9,11,5,4 620 DATA 4,6,21,8,11,6,4,4,6,21,7,11,7,4,4,6,21,6,11,8,4 630 DATA 4,6,19,1,1,5,11,9,4,4,6,19,1,1,5,10,10,4,4,6,18,2,1,6,8,11,4 640 DATA 4,6,17,3,1,7,5,13,4,4,6,15,5,2,23,5,1,29,5,17,8 650 DATA 1,29,9,9,12,1,13,5,40,1,1,13,5,40,1,4,6,13,3,10,6,12,5,1 660 DATA 5,6,11,3,11,6,14,3,1,5,6,11,3,11,6,15,2,1 670 DATA 6,6,9,3,12,6,16,1,1,6,6,9,3,12,6,7,1,10 680 DATA 7,6,7,3,13,6,6,2,10,7,6,7,3,13,14,10,8,6,5,3,14,6,6,2,10 690 DATA 8,6,5,3,14,6,7,1,10,9,6,3,3,15,6,16,1,1 700 DATA 9,6,3,3,15,6,15,2,1,10,6,1,3,16,6,14,3,1,10,10,16,6,12,5,1 710 DATA 11,8,13,27,1,11,8,13,27,1,60 999 FOR I=1 to 10 1000 PRINT 1001 NEXT I 1002 END
<filename>Task/Fibonacci-sequence/VBScript/fibonacci-sequence-2.vb dim fib set fib = new generator dim i for i = 1 to 100 wscript.stdout.write " " & fib if fib.overflow then wscript.echo exit for end if next
'Bitmap/Bresenham's line algorithm - VBScript - 13/05/2019 Dim map(48,40), list(10), ox, oy data=Array(1,8, 8,16, 16,8, 8,1, 1,8) For i=0 To UBound(map,1): For j=0 To UBound(map,2) map(i,j)="." Next: Next 'j, i points=(UBound(data)+1)/2 For p=1 To points x=data((p-1)*2) y=data((p-1)*2+1) list(p)=Array(x,y) If p=1 Then minX=x: maxX=x: minY=y: maxY=y If x<minX Then minX=x If x>maxX Then maxX=x If y<minY Then minY=y If y>maxY Then maxY=y Next 'p border=2 minX=minX-border*2 : maxX=maxX+border*2 minY=minY-border : maxY=maxY+border ox =-minX : oy =-minY wx=UBound(map,1)-ox : If maxX>wx Then maxX=wx wy=UBound(map,2)-oy : If maxY>wy Then maxY=wy For x=minX To maxX: map(x+ox,0+oy)="-": Next 'x For y=minY To maxY: map(0+ox,y+oy)="|": Next 'y map(ox,oy)="+" For p=1 To points-1 draw_line list(p), list(p+1) Next 'p For y=maxY To minY Step -1 line="" For x=minX To maxX line=line & map(x+ox,y+oy) Next 'x Wscript.Echo line Next 'y Sub draw_line(p1, p2) Dim x,y,xf,yf,dx,dy,sx,sy,err,err2 x =p1(0) : y =p1(1) xf=p2(0) : yf=p2(1) dx=Abs(xf-x) : dy=Abs(yf-y) If x<xf Then sx=+1: Else sx=-1 If y<yf Then sy=+1: Else sy=-1 err=dx-dy Do map(x+ox,y+oy)="X" If x=xf And y=yf Then Exit Do err2=err+err If err2>-dy Then err=err-dy: x=x+sx If err2< dx Then err=err+dx: y=y+sy Loop End Sub 'draw_line
<filename>Task/Arithmetic-Integer/VBScript/arithmetic-integer-1.vb option explicit dim a, b wscript.stdout.write "A? " a = wscript.stdin.readline wscript.stdout.write "B? " b = wscript.stdin.readline a = int( a ) b = int( b ) wscript.echo "a + b=", a + b wscript.echo "a - b=", a - b wscript.echo "a * b=", a * b wscript.echo "a / b=", a / b wscript.echo "a \ b=", a \ b wscript.echo "a mod b=", a mod b wscript.echo "a ^ b=", a ^ b
WScript.Echo Join(Split("Hello,How,Are,You,Today", ","), ".")
REM ================================================================================= REM REM IIS_SWITCH <Cluster_Name> [<group_name>] REM REM REM Replace IIS resources (Web and FTP) with generic scripts. REM Note: If you chose to replace all groups, then the resource types that are REM not supported by Windows Server 2003 will also be deleted by the script REM REM Copyright (c) 2001 Microsoft Corporation REM REM ================================================================================= Option Explicit REM --------------------------------------------------------------------------------- REM DeleteResourceTypes (objCluster) REM REM Delete the resource types that are not valid in Windows Server 2003 REM --------------------------------------------------------------------------------- sub DeleteResourceTypes(objCluster) Dim colTypes Dim objType Dim colRes on error resume next set colTypes = objCluster.ResourceTypes REM Delete IIS resource type set objType = colTypes.Item("IIS Server Instance") set colRes = objType.Resources if colRes.Count = 0 then objType.Delete end if REM Delete SMTP resource type set objType = colTypes.Item("SMTP Server Instance") set colRes = objType.Resources if colRes.Count = 0 then objType.Delete end if REM Delete NNTP resource type set objType = colTypes.Item("NNTP Server Instance") set colRes = objType.Resources if colRes.Count = 0 then objType.Delete end if end sub REM --------------------------------------------------------------------------------- REM SwitchResource (objOld, objNew) REM REM Switch old object out of the tree and put in the new object REM Rebuild all the dependencies REM --------------------------------------------------------------------------------- sub SwitchResource(objOld, objNew) Dim colOldDeps Dim colNewDeps Dim objDep REM Switch out the dependent resources REM set colOldDeps = objOld.Dependents set colNewDeps = objNew.Dependents for each objDep in colOldDeps colOldDeps.RemoveItem objDep.Name colNewDeps.AddItem objDep next REM Switch out the dependencies REM set colOldDeps = objOld.Dependencies set colNewDeps = objNew.Dependencies for each objDep in colOldDeps colOldDeps.RemoveItem objDep.Name colNewDeps.AddItem objDep next end Sub REM --------------------------------------------------------------------------------- REM CreateGenScript(objGroup, strName, web) REM REM Routine to create a generic script resource in a specific group REM --------------------------------------------------------------------------------- Function CreateGenScript(objGroup, strName, web) Dim colResources Dim objResource Dim colPrivateProps Dim strScript if web then strScript = "%windir%\system32\inetsrv\clusweb.vbs" else strScript = "%windir%\system32\inetsrv\clusftp.vbs" end if set colResources = objGroup.Resources set objResource = colResources.CreateItem(strName, "Generic Script", 0) set colPrivateProps = objResource.PrivateProperties colPrivateProps.CreateItem "ScriptFilepath", strScript colPrivateProps.SaveChanges set CreateGenScript = objResource end Function REM --------------------------------------------------------------------------------- REM UpgradeIIS(objCluster, objGroup) REM REM Routine to upgrade all Web and FTP resources to Windows Server 2003 resource REM --------------------------------------------------------------------------------- Sub UpgradeIIS(objCluster, objGroup) DIM colResources DIM objResource DIM objNewResource DIM colPrivateProps DIM objProp DIM resName DIM boolWeb DIM oldState on error resume next Err.Clear REM Take the cluster group offline if it is online REM it is not online or offline, return an error REM oldState = objGroup.state if objGroup.state = 0 then objGroup.offline 5000 end if if objGroup.state = 3 then objGroup.offline 5000 end if do while objGroup.state = 4 sleep (5) loop if objGroup.state <> 1 then wscript.echo "ERROR: The group '" + objGroup.Name + "' is not in a state to perform this operation" wscript.quit(1) end if REM Find all IIS resources (Web and FTP) in the group REM set colResources = objGroup.Resources for each objResource in colResources REM Look for IIS resources REM if objResource.TypeName = "IIS Server Instance" then resName = objResource.Name REM Figure out whether it is an FTP resource or a Web resource REM set colPrivateProps = objResource.PrivateProperties set objProp = colPrivateProps.Item("ServiceName") boolWeb = (objProp.Value = "W3SVC") REM Rename the old resource REM objResource.Name = resName + " (W2K)" REM Switch out the old resource and plumb in the new one REM set objNewResource = CreateGenScript(objGroup, resName, boolWeb) SwitchResource objResource, objNewResource REM Now delete the old resource and print out a message (assuming nothing broke) REM if Err.Number = 0 then objResource.Delete if boolWeb then wscript.echo "INFO: Upgraded IIS Web resource '" + resName + "'" else wscript.echo "INFO: Upgraded IIS FTP resource '" + resName + "'" end if else REM Catch any errors that may have happened REM wscript.echo "ERROR: Failed to convert resource '" + resName + "': " + Err.Description Err.Clear end if end if next REM Ok, move the group to the Whistler node and put it back in the REM online state if it was there before REM if oldstate = 0 then objGroup.Move 10000 objGroup.Online 0 end if end Sub REM --------------------------------------------------------------------------------- REM UpgradeGroup(objCluster, objGroup) REM REM Routine to upgrade a single group REM --------------------------------------------------------------------------------- Sub UpgradeGroup(objCluster, objGroup) DIM colResources DIM objResource DIM boolFound DIM objProp REM Figure out whether this group needs any work done to it REM boolFound = False set colResources = objGroup.Resources for each objResource in colResources if objResource.TypeName = "IIS Server Instance" then boolFound = True end if next REM If we found an IIS resource, make sure it is not the cluster group REM and then go upgrade it REM if boolFound then set objResource = objCluster.QuorumResource set objProp = objResource.Group if objProp.Name = objGroup.Name then wscript.echo "WARN: Skipping group '" + objProp.Name + "'" wscript.echo " An IIS resource exists in the cluster group, this is not a supported configuration" else UpgradeIIS objCluster, objGroup end if end if end Sub REM --------------------------------------------------------------------------------- REM main REM REM Main entry point for switch utility REM Usage: REM switch <cluster_name> [<group_name>] REM --------------------------------------------------------------------------------- sub main Dim args Dim objCluster Dim objGroup Dim colGroups Dim colTypes Dim objType on error resume next wscript.echo "Server Cluster (MSCS) upgrade script for IIS resources V1.0" REM Check for the arguments REM set args = Wscript.Arguments if args.count < 1 then wscript.echo "Usage: iis_switch <cluster_name> [<group_name>]" wscript.quit(1) end if REM Open a handle to the cluster REM Set objCluster = CreateObject("MSCluster.Cluster") objCluster.Open (args(0)) if Err.Number <> 0 then wscript.echo "ERROR: Unable to connect to cluster '" + args(0) + "': " + Err.Description wscript.quit(1) end if REM Check that this script is being run on a node that has the generic script resource REM i.e. a Windows Server 2003 cluster node REM set colTypes = objCluster.ResourceTypes set objType = colTypes.Item("Generic Script") if Err.Number <> 0 then wscript.echo "ERROR: You must execute this script against a Windows Server 2003 node" wscript.quit(1) end if REM Either upgrade all groups or just the specified group REM if args.count = 1 then set colGroups = objCluster.ResourceGroups for each objGroup in colGroups UpgradeGroup objCluster, objGroup next else set colGroups = objCluster.ResourceGroups set objGroup = colGroups.Item(args(1)) UpgradeGroup objCluster, objGroup end if REM delete the resource types that are no longer supported DeleteResourceTypes objCluster end sub main()
WScript.StdErr.WriteLine "Goodbye, World!"
<filename>Task/Day-of-the-week/VBScript/day-of-the-week.vb For year = 2008 To 2121 If Weekday(DateSerial(year, 12, 25)) = 1 Then WScript.Echo year End If Next
Attribute VB_Name = "Main" Option Explicit Private Const DB_VERSION_C As String = "DBVersion" Private Const OPERATORS_AND_C As String = "OperatorsAnd" Private Const OPERATORS_OR_C As String = "OperatorsOr" Private Const OPERATORS_NOT_C As String = "OperatorsNot" Private Const AUTHORING_GROUP_C As String = "AuthoringGroup" Private Const LOCK_KEYWORDS_C As String = "LockKeywords" Private Const LOCK_STOP_SIGNS_C As String = "LockStopSigns" Private Const LOCK_STOP_WORDS_C As String = "LockStopWords" Private Const LOCK_SYNONYMS_C As String = "LockSynonyms" Private Const LOCK_SYNONYM_SETS_C As String = "LockSynonymSets" Private Const LOCK_TAXONOMY_C As String = "LockTaxonomy" Private Const LOCK_TYPES_C As String = "LockTypes" Private Const MINIMUM_KEYWORD_VALIDATION_C As String = "MinimumKeywordValidation" Private Const AUTHORING_GROUP_VALUE_C As Long = 10001 Private p_cnn As ADODB.Connection Public Sub MainFunction( _ ByVal i_strDatabaseIn As String, _ ByVal i_strDatabaseOut As String _ ) On Error GoTo LError Dim FSO As Scripting.FileSystemObject Dim rs As ADODB.Recordset Dim strQuery As String Dim strVersion As String Dim strAnd As String Dim strOr As String Dim strNot As String Set FSO = New Scripting.FileSystemObject If (Not FSO.FileExists(i_strDatabaseIn)) Then Err.Raise E_FAIL, , "File " & i_strDatabaseIn & " does not exist" End If FSO.CopyFile i_strDatabaseIn, i_strDatabaseOut Set p_cnn = New ADODB.Connection p_cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & i_strDatabaseOut & ";" Set rs = New ADODB.Recordset strQuery = "UPDATE Taxonomy SET Username = ""Microsoft"", Comments = """"" rs.Open strQuery, p_cnn, adOpenStatic, adLockPessimistic strVersion = p_GetParameter(DB_VERSION_C) strAnd = p_GetParameter(OPERATORS_AND_C) strOr = p_GetParameter(OPERATORS_OR_C) strNot = p_GetParameter(OPERATORS_NOT_C) strQuery = "DELETE * FROM DBParameters" rs.Open strQuery, p_cnn, adOpenStatic, adLockPessimistic p_SetParameter AUTHORING_GROUP_C, AUTHORING_GROUP_VALUE_C p_SetParameter DB_VERSION_C, strVersion p_SetParameter OPERATORS_AND_C, strAnd p_SetParameter OPERATORS_OR_C, strOr p_SetParameter OPERATORS_NOT_C, strNot p_SetParameter LOCK_KEYWORDS_C, "False" p_SetParameter LOCK_STOP_SIGNS_C, "False" p_SetParameter LOCK_STOP_WORDS_C, "False" p_SetParameter LOCK_SYNONYMS_C, "False" p_SetParameter LOCK_SYNONYM_SETS_C, "False" p_SetParameter LOCK_TAXONOMY_C, "False" p_SetParameter LOCK_TYPES_C, "False" p_SetParameter MINIMUM_KEYWORD_VALIDATION_C, "False" p_cnn.Close p_CompactDatabase i_strDatabaseOut LEnd: Exit Sub LError: frmMain.Output Err.Description, LOGGING_TYPE_ERROR_E Err.Raise Err.Number End Sub Public Function p_GetParameter( _ ByVal i_strName As String _ ) As Variant Dim rs As ADODB.Recordset Dim strQuery As String Dim str As String str = Trim$(i_strName) p_GetParameter = Null Set rs = New ADODB.Recordset strQuery = "" & _ "SELECT * " & _ "FROM DBParameters " & _ "WHERE (Name = '" & str & "');" rs.Open strQuery, p_cnn, adOpenForwardOnly, adLockReadOnly If (Not rs.EOF) Then p_GetParameter = rs("Value") End If End Function Private Sub p_SetParameter( _ ByVal i_strName As String, _ ByRef i_vntValue As Variant _ ) Dim rs As ADODB.Recordset Dim strQuery As String Dim str As String str = Trim$(i_strName) Set rs = New ADODB.Recordset strQuery = "" & _ "SELECT * " & _ "FROM DBParameters " & _ "WHERE (Name = '" & str & "');" rs.Open strQuery, p_cnn, adOpenForwardOnly, adLockPessimistic If (rs.EOF) Then rs.AddNew rs("Name") = i_strName End If rs("Value") = i_vntValue rs.Update End Sub Public Sub p_CompactDatabase( _ ByVal i_strDatabase As String, _ Optional ByVal lcid As Long = 1033 _ ) Dim je As New JRO.JetEngine Dim FSO As Scripting.FileSystemObject Dim strTempFile As String Set FSO = New Scripting.FileSystemObject strTempFile = Environ$("TEMP") & "\" & FSO.GetTempName je.CompactDatabase _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & i_strDatabase & ";", _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & strTempFile & ";" & _ "Locale Identifier=" & lcid & ";" FSO.DeleteFile i_strDatabase FSO.MoveFile strTempFile, i_strDatabase End Sub
Set list = CreateObject("System.Collections.Arraylist") Set ludic = CreateObject("System.Collections.Arraylist") 'populate the list For i = 1 To 25000 list.Add i Next 'set 1 as the first ludic number ludic.Add list(0) list.RemoveAt(0) 'variable to count ludic numbers <= 1000 up_to_1k = 1 'determine the succeeding ludic numbers For j = 2 To 2005 If list.Count > 0 Then If list(0) <= 1000 Then up_to_1k = up_to_1k + 1 End If ludic.Add list(0) Else Exit For End If increment = list(0) - 1 n = 0 Do While n <= list.Count - 1 list.RemoveAt(n) n = n + increment Loop Next 'the first 25 ludics WScript.StdOut.WriteLine "First 25 Ludic Numbers:" For k = 0 To 24 If k < 24 Then WScript.StdOut.Write ludic(k) & ", " Else WScript.StdOut.Write ludic(k) End If Next WScript.StdOut.WriteBlankLines(2) 'the number of ludics up to 1000 WScript.StdOut.WriteLine "Ludics up to 1000: " WScript.StdOut.WriteLine up_to_1k WScript.StdOut.WriteBlankLines(1) '2000th - 2005th ludics WScript.StdOut.WriteLine "The 2000th - 2005th Ludic Numbers:" For k = 1999 To 2004 If k < 2004 Then WScript.StdOut.Write ludic(k) & ", " Else WScript.StdOut.Write ludic(k) End If Next WScript.StdOut.WriteBlankLines(2) 'triplets up to 250: x, x+2, and x+6 WScript.StdOut.WriteLine "Ludic Triplets up to 250: " triplets = "" k = 0 Do While ludic(k) + 6 <= 250 x2 = ludic(k) + 2 x6 = ludic(k) + 6 If ludic.IndexOf(x2,1) > 0 And ludic.IndexOf(x6,1) > 0 Then triplets = triplets & ludic(k) & ", " & x2 & ", " & x6 & vbCrLf End If k = k + 1 Loop WScript.StdOut.WriteLine triplets
<reponame>npocmaka/Windows-Server-2003 VERSION 5.00 Begin VB.Form CimXMLTestForm Caption = "Form1" ClientHeight = 8832 ClientLeft = 132 ClientTop = 420 ClientWidth = 10512 LinkTopic = "Form1" ScaleHeight = 8832 ScaleWidth = 10512 StartUpPosition = 3 'Windows Default Begin VB.CommandButton TestInterOp Caption = "TestInterOp" Height = 315 Left = 7200 TabIndex = 25 Top = 4200 Width = 1335 End Begin VB.CommandButton Clear Caption = "Clear" Height = 375 Left = 5520 TabIndex = 20 Top = 3720 Width = 1455 End Begin VB.CommandButton ExecMethod Caption = "ExecMethod" Height = 375 Left = 8880 TabIndex = 19 Top = 3720 Width = 1575 End Begin VB.TextBox ExecQueryBox Height = 2175 Left = 1440 TabIndex = 18 Text = "select * from Win32_Processor" Top = 2160 Width = 3735 End Begin VB.CommandButton ExecQuery Caption = "ExecQuery" Height = 375 Left = 120 TabIndex = 17 Top = 2160 Width = 1215 End Begin VB.CommandButton GetInstance Caption = "GetInstance" Height = 375 Left = 7200 TabIndex = 16 Top = 3720 Width = 1575 End Begin VB.CheckBox DeepOption Caption = "Deep" Height = 255 Left = 240 TabIndex = 14 Top = 2880 Value = 1 'Checked Width = 735 End Begin VB.TextBox EnumInstanceBox Height = 375 Left = 1440 TabIndex = 13 Text = "Win32_ComputerSystem" Top = 1680 Width = 2655 End Begin VB.CommandButton EnumInstance Caption = "EnumInstance" Height = 375 Left = 120 TabIndex = 12 Top = 1680 Width = 1215 End Begin VB.TextBox RequestXMLBox Height = 3375 Left = 5280 MultiLine = -1 'True ScrollBars = 3 'Both TabIndex = 7 Top = 120 Width = 5175 End Begin VB.Frame OutputFrame Caption = "Responses" Height = 4695 Left = 120 TabIndex = 6 Top = 4440 Width = 10215 Begin VB.TextBox LengthBox Height = 375 Left = 8280 TabIndex = 15 Top = 360 Width = 1575 End Begin VB.TextBox XMLOutputBox Height = 3495 Left = 240 MultiLine = -1 'True ScrollBars = 3 'Both TabIndex = 11 Top = 960 Width = 9615 End Begin VB.TextBox StatusTextBox Height = 375 Left = 3120 TabIndex = 10 Top = 360 Width = 5055 End Begin VB.TextBox StatusBox Height = 375 Left = 1560 TabIndex = 9 Top = 360 Width = 1335 End Begin VB.Label HTTPStatus Caption = "HTTP Status" Height = 255 Left = 120 TabIndex = 8 Top = 360 Width = 1095 End End Begin VB.TextBox GetClassBox Height = 405 Left = 1440 TabIndex = 5 Text = "Win32_Desktop" Top = 1200 Width = 2895 End Begin VB.CommandButton GetClass Caption = "GetClass" Height = 375 Left = 360 TabIndex = 4 Top = 1200 Width = 975 End Begin VB.TextBox NamespaceBox Height = 405 Left = 1080 TabIndex = 3 Text = "root\cimv2" Top = 600 Width = 2895 End Begin VB.TextBox URLBox Height = 405 Left = 1080 TabIndex = 1 Text = "http://localhost/cimom" Top = 120 Width = 2895 End Begin VB.Frame FlagsFrame Caption = "Flags" Height = 1575 Left = 120 TabIndex = 21 Top = 2640 Width = 1215 Begin VB.CheckBox QualifiersOption Caption = "Qualifiers" Height = 255 Left = 120 TabIndex = 24 Top = 1200 Width = 975 End Begin VB.CheckBox ClassOriginOption Caption = "Class Org." Height = 375 Left = 120 TabIndex = 23 Top = 840 Width = 975 End Begin VB.CheckBox LocalOption Caption = "Local" Height = 195 Left = 120 TabIndex = 22 Top = 600 Value = 1 'Checked Width = 735 End End Begin VB.Label NamespaceLabel Caption = "Namespace" Height = 255 Left = 0 TabIndex = 2 Top = 720 Width = 975 End Begin VB.Label URLLabel Caption = "URL" Height = 255 Left = 240 TabIndex = 0 Top = 240 Width = 495 End End Attribute VB_Name = "CimXMLTestForm" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Private Sub ClearOutput() StatusBox.Text = " " StatusTextBox.Text = " " XMLOutputBox.Text = " " LengthBox.Text = " " End Sub Private Sub Clear_Click() RequestXMLBox.Text = "" End Sub Private Sub EnumInstance_Click() ClearOutput Set theRequest = CreateObject("Microsoft.XMLHTTP") theRequest.open "M-POST", URLBox.Text, False theRequest.setRequestHeader "Content-Type", "application/xml;charset=""utf-8""" theRequest.setRequestHeader "Man", "http://www.dmtf.org/cim/operation;ns=73" theRequest.setRequestHeader "73-CIMOperation", "MethodCall" theRequest.setRequestHeader "73-CIMMethod", "EnumerateInstances" theRequest.setRequestHeader "73-CIMObject", NamespaceBox.Text Dim theLocalOption As String Dim theIncludeQualifierOption As String Dim theIncludeClassOriginOption As String If (LocalOption.Value = 1) Then theLocalOption = "TRUE" Else theLocalOption = "FALSE" End If If (QualifiersOption.Value = 1) Then theIncludeQualifierOption = "TRUE" Else theIncludeQualifierOption = "FALSE" End If If (ClassOriginOption.Value = 1) Then theIncludeClassOriginOption = "TRUE" Else theIncludeClassOriginOption = "FALSE" End If Dim theDeep As String theDeep = "TRUE" If DeepOption.Value = 0 Then theDeep = "FALSE" End If Dim theBody As String theBody = "<?xml version=""1.0"" ?>" & Chr(13) & Chr(10) & _ "<CIM CIMVERSION=""2.0"" DTDVERSION=""2.0"">" & Chr(13) & Chr(10) & _ "<MESSAGE ID=""877"" PROTOCOLVERSION=""1.0"">" & Chr(13) & Chr(10) & _ "<SIMPLEREQ>" & Chr(13) & Chr(10) & _ "<IMETHODCALL NAME=""EnumerateInstances"">" & Chr(13) & Chr(10) & _ "<LOCALNAMESPACEPATH>" & Chr(13) & Chr(10) & _ "<NAMESPACE NAME=""" & NamespaceBox.Text & """ />" & Chr(13) & Chr(10) & _ "</LOCALNAMESPACEPATH>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""ClassName"">" & EnumInstanceBox.Text & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""LocalOnly"">" & theLocalOption & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""DeepInheritance"">" & theDeep & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""IncludeQualifiers"">" & theIncludeQualifierOption & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""IncludeClassOrigin"">" & theIncludeClassOriginOption & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "</IMETHODCALL>" & Chr(13) & Chr(10) & _ "</SIMPLEREQ>" & Chr(13) & Chr(10) & _ "</MESSAGE>" & Chr(13) & Chr(10) & _ "</CIM>" ShowResults theRequest, theBody End Sub Private Sub ExecMethod_Click() If RequestXMLBox.Text = "" Then RequestXMLBox.Text = "<?xml version=""1.0"" ?>" & Chr(13) & Chr(10) & _ "<CIM CIMVERSION=""2.0"" DTDVERSION=""2.0"">" & Chr(13) & Chr(10) & _ "<MESSAGE ID=""877"" PROTOCOLVERSION=""1.0"">" & Chr(13) & Chr(10) & _ "<SIMPLEREQ>" & Chr(13) & Chr(10) & _ "<METHODCALL NAME=""Create"">" & Chr(13) & Chr(10) & _ "<LOCALCLASSPATH>" & Chr(13) & Chr(10) & _ "<LOCALNAMESPACEPATH>" & Chr(13) & Chr(10) & _ "<NAMESPACE NAME=""root\cimv2"" />" & Chr(13) & Chr(10) & _ "</LOCALNAMESPACEPATH>" & Chr(13) & Chr(10) & _ "<CLASSNAME NAME=""Win32_Process""/>" & Chr(13) & Chr(10) & _ "</LOCALCLASSPATH>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""CommandLine"">notepad.exe</PARAMVALUE>" & Chr(13) & Chr(10) & _ "</METHODCALL>" & Chr(13) & Chr(10) & _ "</SIMPLEREQ>" & Chr(13) & Chr(10) & _ "</MESSAGE>" & Chr(13) & Chr(10) & _ "</CIM>" Else ClearOutput Set theRequest = CreateObject("Microsoft.XMLHTTP") theRequest.open "POST", URLBox.Text, False theRequest.setRequestHeader "Content-Type", "application/xml;charset=""utf-8""" theRequest.setRequestHeader "CIMOperation", "MethodCall" theRequest.setRequestHeader "CIMMethod", "Create" theRequest.setRequestHeader "CIMObject", "root/cimv2:win32_process" ShowResults theRequest, RequestXMLBox.Text End If End Sub Private Sub ExecQuery_Click() ClearOutput Set theRequest = CreateObject("Microsoft.XMLHTTP") theRequest.open "M-POST", URLBox.Text, False theRequest.setRequestHeader "Content-Type", "application/xml;charset=""utf-8""" theRequest.setRequestHeader "Man", "http://www.dmtf.org/cim/operation;ns=73" theRequest.setRequestHeader "73-CIMOperation", "MethodCall" theRequest.setRequestHeader "73-CIMMethod", "ExecQuery" theRequest.setRequestHeader "73-CIMObject", NamespaceBox.Text Dim theLocalOption As String Dim theIncludeQualifierOption As String Dim theIncludeClassOriginOption As String If (LocalOption.Value = 1) Then theLocalOption = "TRUE" Else theLocalOption = "FALSE" End If If (QualifiersOption.Value = 1) Then theIncludeQualifierOption = "TRUE" Else theIncludeQualifierOption = "FALSE" End If If (ClassOriginOption.Value = 1) Then theIncludeClassOriginOption = "TRUE" Else theIncludeClassOriginOption = "FALSE" End If Dim theBody As String theBody = "<?xml version=""1.0"" ?>" & Chr(13) & Chr(10) & _ "<CIM CIMVERSION=""2.0"" DTDVERSION=""2.0"">" & Chr(13) & Chr(10) & _ "<MESSAGE ID=""877"" PROTOCOLVERSION=""1.0"">" & Chr(13) & Chr(10) & _ "<SIMPLEREQ>" & Chr(13) & Chr(10) & _ "<IMETHODCALL NAME=""ExecQuery"">" & Chr(13) & Chr(10) & _ "<LOCALNAMESPACEPATH>" & Chr(13) & Chr(10) & _ "<NAMESPACE NAME=""" & NamespaceBox.Text & """ />" & Chr(13) & Chr(10) & _ "</LOCALNAMESPACEPATH>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""QueryLanguage"">" & Chr(13) & Chr(10) & _ "WQL" & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""Query"">" & Chr(13) & Chr(10) & _ ExecQueryBox.Text & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""IncludeQualifiers"">" & theIncludeQualifierOption & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""IncludeClassOrigin"">" & theIncludeClassOriginOption & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "</IMETHODCALL>" & Chr(13) & Chr(10) & _ "</SIMPLEREQ>" & Chr(13) & Chr(10) & _ "</MESSAGE>" & Chr(13) & Chr(10) & _ "</CIM>" ShowResults theRequest, theBody End Sub Private Sub GetClass_Click() ClearOutput Set theRequest = CreateObject("Microsoft.XMLHTTP") theRequest.open "M-POST", URLBox.Text, False theRequest.setRequestHeader "Content-Type", "application/xml;charset=""utf-8""" theRequest.setRequestHeader "Man", "http://www.dmtf.org/cim/operation;ns=73" theRequest.setRequestHeader "73-CIMOperation", "MethodCall" theRequest.setRequestHeader "73-CIMMethod", "GetClass" theRequest.setRequestHeader "73-CIMObject", NamespaceBox.Text Dim theBody As String Dim theLocalOption As String Dim theIncludeQualifierOption As String Dim theIncludeClassOriginOption As String If (LocalOption.Value = 1) Then theLocalOption = "TRUE" Else theLocalOption = "FALSE" End If If (QualifiersOption.Value = 1) Then theIncludeQualifierOption = "TRUE" Else theIncludeQualifierOption = "FALSE" End If If (ClassOriginOption.Value = 1) Then theIncludeClassOriginOption = "TRUE" Else theIncludeClassOriginOption = "FALSE" End If theBody = "<?xml version=""1.0"" ?>" & Chr(13) & Chr(10) & _ "<CIM CIMVERSION=""2.0"" DTDVERSION=""2.0"">" & Chr(13) & Chr(10) & _ "<MESSAGE ID=""877"" PROTOCOLVERSION=""1.0"">" & Chr(13) & Chr(10) & _ "<SIMPLEREQ>" & Chr(13) & Chr(10) & _ "<IMETHODCALL NAME=""GetClass"">" & Chr(13) & Chr(10) & _ "<LOCALNAMESPACEPATH>" & Chr(13) & Chr(10) & _ "<NAMESPACE NAME=""" & NamespaceBox.Text & """ />" & Chr(13) & Chr(10) & _ "</LOCALNAMESPACEPATH>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""ClassName"">" & GetClassBox.Text & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""LocalOnly"">" & theLocalOption & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""IncludeQualifiers"">" & theIncludeQualifierOption & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""IncludeClassOrigin"">" & theIncludeClassOriginOption & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "</IMETHODCALL>" & Chr(13) & Chr(10) & _ "</SIMPLEREQ>" & Chr(13) & Chr(10) & _ "</MESSAGE>" & Chr(13) & Chr(10) & _ "</CIM>" ShowResults theRequest, theBody End Sub Private Sub GetInstance_Click() Dim theLocalOption As String Dim theIncludeQualifierOption As String Dim theIncludeClassOriginOption As String If (LocalOption.Value = 1) Then theLocalOption = "TRUE" Else theLocalOption = "FALSE" End If If (QualifiersOption.Value = 1) Then theIncludeQualifierOption = "TRUE" Else theIncludeQualifierOption = "FALSE" End If If (ClassOriginOption.Value = 1) Then theIncludeClassOriginOption = "TRUE" Else theIncludeClassOriginOption = "FALSE" End If If RequestXMLBox.Text = "" Then RequestXMLBox.Text = "<?xml version=""1.0"" ?>" & Chr(13) & Chr(10) & _ "<CIM CIMVERSION=""2.0"" DTDVERSION=""2.0"">" & Chr(13) & Chr(10) & _ "<MESSAGE ID=""877"" PROTOCOLVERSION=""1.0"">" & Chr(13) & Chr(10) & _ "<SIMPLEREQ>" & Chr(13) & Chr(10) & _ "<IMETHODCALL NAME=""GetInstance"">" & Chr(13) & Chr(10) & _ "<LOCALNAMESPACEPATH>" & Chr(13) & Chr(10) & _ "<NAMESPACE NAME=""root\cimv2"" />" & Chr(13) & Chr(10) & _ "</LOCALNAMESPACEPATH>" & Chr(13) & Chr(10) & _ "<PARAMVALUE.INSTNAME NAME=""InstanceName"">" & Chr(13) & Chr(10) & _ "<INSTANCENAME CLASSNAME=""Win32_ComputerSystem"">" & Chr(13) & Chr(10) & _ "<KEYBINDING NAME=""NAME"">" & Chr(13) & Chr(10) & _ "<KEYVALUE>RAJESHR31</KEYVALUE>" & Chr(13) & Chr(10) & _ "</KEYBINDING>" & Chr(13) & Chr(10) & _ "</INSTANCENAME>" & Chr(13) & Chr(10) & _ "</PARAMVALUE.INSTNAME>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""LocalOnly"">" & theLocalOption & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""IncludeQualifiers"">" & theIncludeQualifierOption & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""IncludeClassOrigin"">" & theIncludeClassOriginOption & "</PARAMVALUE>" & Chr(13) & Chr(10) & _ "</IMETHODCALL>" & Chr(13) & Chr(10) & _ "</SIMPLEREQ>" & Chr(13) & Chr(10) & _ "</MESSAGE>" & Chr(13) & Chr(10) & _ "</CIM>" Else ClearOutput Set theRequest = CreateObject("Microsoft.XMLHTTP") theRequest.open "M-POST", URLBox.Text, False theRequest.setRequestHeader "Content-Type", "application/xml;charset=""utf-8""" theRequest.setRequestHeader "Man", "http://www.dmtf.org/cim/operation;ns=73" theRequest.setRequestHeader "73-CIMOperation", "MethodCall" theRequest.setRequestHeader "73-CIMMethod", "GetInstance" theRequest.setRequestHeader "73-CIMObject", NamespaceBox.Text ShowResults theRequest, RequestXMLBox.Text End If End Sub Private Sub Form_Load() RequestXMLBox.Text = "<?xml version=""1.0"" ?>" & Chr(13) & Chr(10) & _ "<CIM CIMVERSION=""2.0"" DTDVERSION=""2.0"">" & Chr(13) & Chr(10) & _ "<MESSAGE ID=""877"" PROTOCOLVERSION=""1.0"">" & Chr(13) & Chr(10) & _ "<SIMPLEREQ>" & Chr(13) & Chr(10) & _ "<IMETHODCALL NAME=""GetInstance"">" & Chr(13) & Chr(10) & _ "<LOCALNAMESPACEPATH>" & Chr(13) & Chr(10) & _ "<NAMESPACE NAME=""root\cimv2"" />" & Chr(13) & Chr(10) & _ "</LOCALNAMESPACEPATH>" & Chr(13) & Chr(10) & _ "<PARAMVALUE.INSTNAME NAME=""InstanceName"">" & Chr(13) & Chr(10) & _ "<INSTANCENAME CLASSNAME=""Win32_ComputerSystem"">" & Chr(13) & Chr(10) & _ "<KEYBINDING NAME=""NAME"">" & Chr(13) & Chr(10) & _ "<KEYVALUE>RAJESHR31</KEYVALUE>" & Chr(13) & Chr(10) & _ "</KEYBINDING>" & Chr(13) & Chr(10) & _ "</INSTANCENAME>" & Chr(13) & Chr(10) & _ "</PARAMVALUE.INSTNAME>" & Chr(13) & Chr(10) & _ "<PARAMVALUE NAME=""LocalOnly"">FALSE</PARAMVALUE>" & Chr(13) & Chr(10) & _ "</IMETHODCALL>" & Chr(13) & Chr(10) & _ "</SIMPLEREQ>" & Chr(13) & Chr(10) & _ "</MESSAGE>" & Chr(13) & Chr(10) & _ "</CIM>" End Sub Private Sub ShowResults(xmlRequest, xmlBody) RequestXMLBox.Text = xmlBody xmlRequest.send (xmlBody) StatusBox.Text = xmlRequest.Status StatusTextBox.Text = xmlRequest.statusText XMLOutputBox.Text = xmlRequest.responseText LengthBox.Text = Len(xmlRequest.responseText) End Sub Private Sub TestInterOp_Click() ClearOutput Set theRequest = CreateObject("Microsoft.XMLHTTP") theRequest.open "M-POST", URLBox.Text, False theRequest.setRequestHeader "Content-Type", "application/xml;charset=""utf-8""" theRequest.setRequestHeader "Man", "http://www.dmtf.org/cim/operation;ns=73" theRequest.setRequestHeader "73-CIMOperation", "MethodCall" theRequest.setRequestHeader "73-CIMMethod", "EnumerateInstances" theRequest.setRequestHeader "73-CIMObject", NamespaceBox.Text Dim theLocalOption As String Dim theIncludeQualifierOption As String Dim theIncludeClassOriginOption As String If (LocalOption.Value = 1) Then theLocalOption = "TRUE" Else theLocalOption = "FALSE" End If If (QualifiersOption.Value = 1) Then theIncludeQualifierOption = "TRUE" Else theIncludeQualifierOption = "FALSE" End If If (ClassOriginOption.Value = 1) Then theIncludeClassOriginOption = "TRUE" Else theIncludeClassOriginOption = "FALSE" End If Dim theDeep As String theDeep = "TRUE" If DeepOption.Value = 0 Then theDeep = "FALSE" End If Dim theBody As String theBody = RequestXMLBox.Text ShowResults theRequest, theBody End Sub
filepath = "SPECIFY PATH TO TEXT FILE HERE" Set objFSO = CreateObject("Scripting.FileSystemObject") Set objInFile = objFSO.OpenTextFile(filepath,1,False,0) Do Until objInFile.AtEndOfStream line = objInFile.ReadLine WScript.StdOut.WriteLine line Loop objInFile.Close Set objFSO = Nothing
<reponame>npocmaka/Windows-Server-2003<gh_stars>10-100 On Error Resume Next Dim hr Dim fModem Dim lBandwidth Dim fOnline Dim pmpcConnection Stop Set pmpcConnection = WScript.CreateObject("UploadManager.MPCConnection") hr = Err.Number if (hr <> 0) then WScript.Echo "Err Number: " & Err.Number WScript.Echo "Err Desc : " & Err.Description WScript.Echo "Err Source: " & Err.Source WScript.Quit hr end if fOnline = pmpcConnection.Available hr = Err.Number if (hr <> 0) then WScript.Echo "Err Number: " & Err.Number WScript.Echo "Err Desc : " & Err.Description WScript.Echo "Err Source: " & Err.Source WScript.Quit hr end if fModem = pmpcConnection.IsAModem hr = Err.Number if (hr <> 0) then WScript.Echo "Err Number: " & Err.Number WScript.Echo "Err Desc : " & Err.Description WScript.Echo "Err Source: " & Err.Source WScript.Quit hr end if lBandwidth = pmpcConnection.Bandwidth hr = Err.Number if (hr <> 0) then WScript.Echo "Err Number: " & Err.Number WScript.Echo "Err Desc : " & Err.Description WScript.Echo "Err Source: " & Err.Source WScript.Quit hr end if WScript.Echo "Connection Status:" WScript.Echo WScript.Echo " fModem: " & fModem WScript.Echo " dwBandwidth: " & lBandwidth WScript.Echo " fOnline: " & fOnline WScript.Echo Set pmpcConnection = Nothing
Attribute VB_Name = "LCIDFont" Option Explicit Public Sub SetFont(i_frm As Form, i_fnt As StdFont, i_fntColor As Long) On Error Resume Next If (i_fnt Is Nothing) Then Exit Sub End If Dim Ctrl As Control For Each Ctrl In i_frm.Controls If (Ctrl.Tag = 1) Then Set Ctrl.Font = i_fnt Ctrl.ForeColor = i_fntColor End If Next End Sub
<reponame>npocmaka/Windows-Server-2003 '*************************************************************************** 'This script tests the enumeration of subclasses '*************************************************************************** On Error Resume Next for each DiskSubclass in GetObject("winmgmts:").SubclassesOf ("CIM_LogicalDisk") WScript.Echo "Subclass name:", DiskSubclass.Path_.Class next if Err <> 0 Then WScript.Echo Err.Description Err.Clear End if
' L_Welcome_MsgBox_Message_Text = "This script demonstrates how to access MMC using the Windows Scripting Host. It creates and configures a console and saves it to c:\mmctest.msc" L_Welcome_MsgBox_Title_Text = "Windows Scripting Host Sample" Call Welcome() ' ******************************************************************************** Dim mmc Dim doc Dim snapins Dim frame set mmc = wscript.CreateObject("MMC20.Application") Set frame = mmc.Frame Set doc = mmc.Document Set snapins = doc.snapins snapins.Add "{58221c66-ea27-11cf-adcf-00aa00a80033}" ' the services snap-in frame.Restore ' show the UI doc.SaveAs "C:\mmctest.msc" set mmc = Nothing ' ******************************************************************************** ' * ' * 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
<gh_stars>1-10 Option Explicit Sub Test() Dim h As Object, i As Long, u, v, s Set h = CreateObject("Scripting.Dictionary") h.Add "A", 1 h.Add "B", 2 h.Add "C", 3 'Iterate on keys For Each s In h.Keys Debug.Print s Next 'Iterate on values For Each s In h.Items Debug.Print s Next 'Iterate on both keys and values by creating two arrays u = h.Keys v = h.Items For i = 0 To h.Count - 1 Debug.Print u(i), v(i) Next End Sub
<reponame>mullikine/RosettaCodeData Sub Main() 'Long: 4 Bytes (signed), type specifier = & Dim l1 As Long, l2 As Long, l3 As Long 'Integer: 2 Bytes (signed), type specifier = % Dim i1 As Integer, i2 As Integer, i3 As Integer 'Byte: 1 Byte (unsigned), no type specifier Dim b1 As Byte, b2 As Byte, b3 As Byte l1 = 1024& l2 = &H400& l3 = &O2000& Debug.Assert l1 = l2 Debug.Assert l2 = l3 i1 = 1024 i2 = &H400 i3 = &O2000 Debug.Assert i1 = i2 Debug.Assert i2 = i3 b1 = 255 b2 = &O377 b3 = &HFF Debug.Assert b1 = b2 Debug.Assert b2 = b3 End Sub
<reponame>mullikine/RosettaCodeData<gh_stars>1-10 <table> <tr><td> Character</td><td>Speech</td></tr> <tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr> <tr><td>Brians mother</td><td>&lt;angry&gt;Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!&lt;/angry&gt;</td></tr> <tr><td>The multitude</td><td>Who are you?</td></tr> <tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr> <tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr> </table>
Option Explicit Sub Main_ABC() Dim Arr, i As Long Arr = Array("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE") For i = 0 To 6 Debug.Print ">>> can_make_word " & Arr(i) & " => " & ABC(CStr(Arr(i))) Next i End Sub Function ABC(myWord As String) As Boolean Dim myColl As New Collection Dim NbLoop As Long, NbInit As Long Dim b As Byte, i As Byte Const BLOCKS As String = "B,O;X,K;D,Q;C,P;N,A;G,T;R,E;T,G;Q,D;F,S;J,W;H,U;V,I;A,N;O,B;E,R;F,S;L,Y;P,C;Z,M" For b = 0 To 19 myColl.Add Split(BLOCKS, ";")(b), Split(BLOCKS, ";")(b) & b Next b NbInit = myColl.Count NbLoop = NbInit For b = 1 To Len(myWord) For i = 1 To NbLoop If i > NbLoop Then Exit For If InStr(myColl(i), Mid(myWord, b, 1)) <> 0 Then myColl.Remove (i) NbLoop = NbLoop - 1 Exit For End If Next Next b ABC = (NbInit = (myColl.Count + Len(myWord))) End Function
<gh_stars>1-10 Randomize Dim n(9) 'nine is the upperbound. 'since VBS arrays are 0-based, it will have 10 elements. For L = 0 to 9 n(L) = Int(Rnd * 32768) Next WScript.StdOut.Write "ORIGINAL : " For L = 0 to 9 WScript.StdOut.Write n(L) & ";" Next InsertionSort n WScript.StdOut.Write vbCrLf & " SORTED : " For L = 0 to 9 WScript.StdOut.Write n(L) & ";" Next 'the function Sub InsertionSort(theList) For insertionElementIndex = 1 To UBound(theList) insertionElement = theList(insertionElementIndex) j = insertionElementIndex - 1 Do While j >= 0 'necessary for BASICs without short-circuit evaluation If insertionElement < theList(j) Then theList(j + 1) = theList(j) j = j - 1 Else Exit Do End If Loop theList(j + 1) = insertionElement Next End Sub
'---------------------------------------------------------------------- ' ' Copyright (c) Microsoft Corporation 1998-1999 ' All Rights Reserved ' ' Abstract: ' ' subnet_op.vbs - subnet operation script for Windows 2000 DS ' ' Usage: ' ' subnet_op [-adl?] [-n subnet-name] [-s site-name] [-p location] ' [-i ip address] [-m subnet mask] ' '---------------------------------------------------------------------- option explicit ' ' Debugging trace flags. ' const kDebugTrace = 1 const kDebugError = 2 dim gDebugFlag ' ' To enable debug output trace message ' Change the following variable to True. ' gDebugFlag = False ' ' Messages to be displayed if the scripting host is not cscript ' const kMessage1 = "Please run this script using CScript." const kMessage2 = "This can be achieved by" const kMessage3 = "1. Using ""CScript script.vbs arguments"" or" const kMessage4 = "2. Changing the default Windows Scripting Host to CScript" const kMessage5 = " using ""CScript //H:CScript //S"" and running the script " const kMessage6 = " ""script.vbs arguments""." ' ' Operation action values. ' const kActionAdd = 0 const kActionDelete = 1 const kActionList = 2 const kActionCalculate = 3 const kActionUnknown = 4 main ' ' Main execution start here ' sub main on error resume next dim strSubnet dim strSite dim strLocation dim strIpAddress dim strSubnetMask dim iAction dim oSubnet dim iRetval dim oArgs ' ' Abort if the host is not cscript ' if not IsHostCscript() then call wscript.echo(kMessage1 & vbCRLF & kMessage2 & vbCRLF & _ kMessage3 & vbCRLF & kMessage4 & vbCRLF & _ kMessage5 & vbCRLF & kMessage6 & vbCRLF) wscript.quit end if iAction = kActionUnknown iRetval = ParseCommandLine( iAction, strSubnet, strSite, strLocation, strIpAddress, strSubnetMask ) if iRetval = 0 then select case iAction case kActionAdd iRetval = CreateSubnetObject( oSubnet, strSubnet, strSite, strLocation ) case kActionDelete if strSubnet = "all" then iRetval = DeleteAllSubnetObjects( ) else iRetval = DeleteSubnetObject( strSubnet ) end if case kActionList iRetval = ListSubnetObjects( ) case kActionCalculate iRetval = CalculateSubnetObject( strIpAddress, strSubnetMask ) case else Usage( True ) exit sub end select end if end sub ' ' Calculate the subnet object name an IP address and a subnet mask ' function CalculateSubnetObject( ByRef strIpAddress, ByRef strSubnetMask ) on error resume next DebugPrint kDebugTrace, "In the CalculateSubnetObject" Dim aIpAddressOctetArray(4) Dim aSubnetMaskOctetArray(4) Dim strSubnetObjectName if CreateValueFromOctetString( strIpAddress, aIpAddressOctetArray ) = False then wscript.echo "Invalid IP Address, must be of the form ddd.ddd.ddd.ddd, e.g. 172.16.58.3" CalculateSubnetObject = False exit function end if if CreateValueFromOctetString( strSubnetMask, aSubnetMaskOctetArray ) = False then wscript.echo "Invalid Subnet mask, must be of the form ddd.ddd.ddd.ddd, e.g. 255.255.252.0" CalculateSubnetObject = False exit function end if DebugPrint kDebugTrace, "Ip Octet Value " & aIpAddressOctetArray(0) & "." & aIpAddressOctetArray(1) & "." & aIpAddressOctetArray(2) & "." & aIpAddressOctetArray(3) DebugPrint kDebugTrace, "Mask Octet Value " & aSubnetMaskOctetArray(0) & "." & aSubnetMaskOctetArray(1) & "." & aSubnetMaskOctetArray(2) & "." & aSubnetMaskOctetArray(3) if ConvertToSubnetName( aIpAddressOctetArray, aSubnetMaskOctetArray, strSubnetObjectName ) = True then wscript.echo "Subnet Object Name:", strSubnetObjectName CalculateSubnetObject = True else wscript.echo "Unable to convert IP address and subnet mask to subnet object name" CalculateSubnetObject = False end if end function ' ' Convert the given ip address and subnet mask to a DS object name. ' The algorithm is to take the ip address and it with the subnet mask ' this is the subnet then tack on a slash and place the number of bits ' in the subnet mask at the end. For example ip address of 172.16.58.3 ' subnet mask 255.255.252.0 results in a subnet object name of 192.168.3.11/22 ' function ConvertToSubnetName( ByRef aIpOctetArray, ByRef aSubnetOctetArray, ByRef strSubnet ) on error resume next DebugPrint kDebugTrace, "In the ConvertToSubnetObject" Dim iVal0 Dim iVal1 Dim iVal2 Dim iVal3 Dim iBits Dim i Dim j iVal0 = aIpOctetArray(0) and aSubnetOctetArray(0) iVal1 = aIpOctetArray(1) and aSubnetOctetArray(1) iVal2 = aIpOctetArray(2) and aSubnetOctetArray(2) iVal3 = aIpOctetArray(3) and aSubnetOctetArray(3) for i = 0 to 3 for j = 0 to 7 if (aSubnetOctetArray(i) and (2 ^ j)) <> 0 then iBits = iBits + 1 end if next next strSubnet = iVal0 & "." & iVal1 & "." & iVal2 & "." & iVal3 & "/" & iBits ConvertToSubnetName = True end function ' ' Converts an octet string to an array of octet values. For example ' this function when given string 172.16.58.3 will return an array with ' the followin values. A(0) = 157, A(1) = 59, A(2) = 161, A(3) = 2 ' function CreateValueFromOctetString( ByRef strOctet, ByRef aOctetArray ) on error resume next DebugPrint kDebugTrace, "In the CreateValueFromOctetString" Dim i Dim iDotCount Dim cValue Dim iValue for i = 0 to 32 cValue = Mid( strOctet, i, 1 ) if IsNumeric( cValue ) then iValue = iValue * 10 + cValue elseif cValue = "." or cValue = "" then if iValue < 0 or iValue > 255 then DebugPrint kDebugTrace, "Value out of range " & iValue exit for end if aOctetArray(iDotCount) = iValue iDotCount = iDotCount + 1 iValue = 0 if cValue = "" then exit for end if else DebugPrint kDebugTrace, "Invalid character found " & cValue end if next CreateValueFromOctetString = iDotCount = 4 end function ' ' List subnet objects. ' function ListSubnetObjects( ) on error resume next DebugPrint kDebugTrace, "In the ListSubnetObject" dim oConfigurationContainer dim oSite dim oSites dim oSubnet dim strSiteName dim strSubnet call GetConfigurationContainer( oConfigurationContainer ) DebugPrint kDebugError, "GetConfigurationContainer" for each oSites In oConfigurationContainer if oSites.name = "CN=Sites" then for each oSite in oSites if oSite.name = "CN=Subnets" then for each oSubnet in oSite call GetSiteObjectName( strSiteName, oSubnet.siteObject ) strSubnet = StripCNFromName( oSubnet.name ) wscript.echo "Name:", strSubnet, vbTab, "Location:", oSubnet.location, "Site:", strSiteName next end if next end if next ListSubnetObjects = Err <> 0 end function ' ' Get the site name from a site object name, basically return ' the CN of the site for the give Site DN ' sub GetSiteObjectName( ByRef strSiteName, ByRef strSiteObject ) on error resume next dim oSiteObject set oSiteObject = GetObject( "LDAP://" & strSiteObject ) strSiteName = StripCNFromName( oSiteObject.name ) end sub ' ' Function to strip the CN prefix from the given name ' function StripCNFromName( ByRef strNameWithCN ) StripCNFromName = Mid( strNameWithCN, 4 ) end function ' ' Delete subnet object. ' function DeleteSubnetObject( ByRef strSubnetName ) on error resume next DebugPrint kDebugTrace, "In the DeleteSubnetObject" dim oConfigurationContainer dim oSubnets call GetConfigurationContainer( oConfigurationContainer ) DebugPrint kDebugError, "GetConfigurationContainer" set oSubnets = oConfigurationContainer.GetObject("subnetContainer", "CN=Subnets,CN=Sites") DebugPrint kDebugError, "GetSubnetContainer" oSubnets.Delete "subnet", "CN=" & strSubnetName DebugPrint kDebugError, "Delete subnet" if Err <> 0 then wscript.echo "Failure - deleting subnet " & strSubnetName & " error code " & hex(err) else wscript.echo "Success - deleting subnet " & strSubnetName & "" end if DeleteSubnetObject = Err <> 0 end function ' ' Delete subnet object. ' function DeleteAllSubnetObjects( ) on error resume next DebugPrint kDebugTrace, "In the DeleteAllSubnetObjects" dim oConfigurationContainer dim oSite dim oSites dim oSubnet call GetConfigurationContainer( oConfigurationContainer ) DebugPrint kDebugError, "GetConfigurationContainer" for each oSites In oConfigurationContainer if oSites.name = "CN=Sites" then for each oSite in oSites if oSite.name = "CN=Subnets" then for each oSubnet in oSite DeleteSubnetObject( StripCNFromName( oSubnet.name ) ) next end if next end if next DeleteAllSubnetObects = True end function ' ' Creates a subnet object in the current domain. ' function CreateSubnetObject( ByRef oSubnet, ByRef strSubnetName, ByRef strSiteName, ByRef strLocationName ) on error resume next DebugPrint kDebugTrace, "In the CreateSubnetObject" DebugPrint kDebugTrace, "Subnet: " & strSubnetName & " Site: " & strSiteName & " Location: " & strLocationName dim oConfigurationContainer dim oSubnets dim strFullSiteName call GetConfigurationContainer( oConfigurationContainer ) DebugPrint kDebugError, "GetConfigurationContainer" set oSubnets = oConfigurationContainer.GetObject( "subnetContainer", "CN=Subnets,CN=Sites" ) DebugPrint kDebugError, "Get Subnet Containter" set oSubnet = oSubnets.Create("subnet", "cn=" & strSubnetName ) DebugPrint kDebugError, "Create Subnet Object" if strSiteName <> Empty then if CreateFullSiteName( strSiteName, strFullSiteName ) = True then DebugPrint kDebugTrace, "Site Name " & strFullSiteName oSubnet.put "siteObject", strFullSiteName end if end if if strLocationName <> Empty then oSubnet.put "location", strLocationName end if oSubnet.SetInfo DebugPrint kDebugError, "Setinfo on Subnet Object" if Err <> 0 then wscript.echo "Failure - adding subnet " & strSubnetName & " error code " & hex(err) else wscript.echo "Success - adding subnet " & strSubnetName & "" end if CreateSubnetObject = Err <> 0 end function ' ' Create the fully qualified site name of the site name does not have a cn= prefix. ' function CreateFullSiteName( ByRef strSiteName, ByRef strFullSiteName ) on error resume next DebugPrint kDebugTrace, "In the CreateFullSiteName" if UCase( Left( strSiteName, 3 ) ) <> "CN=" then dim RootDSE set RootDSE = GetObject("LDAP://RootDSE") if Err = 0 then strFullSiteName = "CN=" & strSiteName & ",CN=Sites," & RootDSE.get("configurationNamingContext") end if else strFullSiteName = strSiteName end if CreateFullSiteName = strFullSiteName <> Empty end function ' ' Get the configuration container object ' function GetConfigurationContainer( ByRef oConfigurationContainer ) on error resume next DebugPrint kDebugTrace, "In the GetConfigurationContainer" dim RootDSE dim strConfigurationContainer set RootDSE = GetObject("LDAP://RootDSE") DebugPrint kDebugError, "GetObject of RootDSE failed with " set oConfigurationContainer = GetObject("LDAP://" & RootDSE.get("configurationNamingContext")) DebugPrint kDebugError, "GetConfigurationContainer" GetConfigurationContainer = Err <> 0 end function ' ' Debug dispaly helper fuction ' sub DebugPrint( ByVal Flags, ByRef String ) if gDebugFlag = True then if Flags = kDebugTrace then WScript.echo String end if if Flags = kDebugError then if Err <> 0 then WScript.echo String & " Failed with " & Hex( Err ) end if end if end if end sub ' ' Parse the command line into it's components ' function ParseCommandLine( ByRef iAction, ByRef strSubnet, ByRef strSite, ByRef strLocation, ByRef strIpAddress, ByRef strSubnetMask ) DebugPrint kDebugTrace, "In the ParseCommandLine" dim oArgs dim strArg dim i set oArgs = Wscript.Arguments while i < oArgs.Count select case oArgs(i) Case "-a" iAction = kActionAdd Case "-d" iAction = kActionDelete Case "-l" iAction = kActionList Case "-c" iAction = kActionCalculate Case "-n" i = i + 1 strSubnet = oArgs(i) Case "-s" i = i + 1 strSite = oArgs(i) Case "-p" i = i + 1 strLocation = oArgs(i) Case "-i" i = i + 1 strIpAddress = oArgs(i) Case "-m" i = i + 1 strSubnetMask = oArgs(i) Case "-?" Usage( True ) exit function Case Else Usage( True ) exit function End Select i = i + 1 wend DebugPrint kDebugTrace, "ParseCommandLine Result: " & iAction & " " & strSubnet & " " & strSite & " " & strLocation ParseCommandLine = 0 end function ' ' Display command usage. ' sub Usage( ByVal bExit ) wscript.echo "Usage: subnet_op [-acdl?] [-n subnet-name] [-s site-name] [-p location]" wscript.echo " [-i ip address] [-m subnet mask]" wscript.echo "Arguments:" wscript.echo "-a - add the specfied subnet object" wscript.echo "-c - calculate subnet object name from ip address and subnet mask" wscript.echo "-d - delete the specified subnet object, use 'all' to deleted all subnets" wscript.echo "-i - specifies the ip address" wscript.echo "-l - list all the subnet objects" wscript.echo "-m - specifies the subnet mask" wscript.echo "-n - specifies the subnet name" wscript.echo "-p - specifies the location string for subnet object" wscript.echo "-s - specifies the site for the subnet object" wscript.echo "-? - display command usage" wscript.echo "" wscript.echo "Examples:" wscript.echo "subnet_op -l" wscript.echo "subnet_op -a -n 172.16.31.10/8" wscript.echo "subnet_op -a -n 172.16.31.10/8 -p USA/RED/27N" wscript.echo "subnet_op -a -n 1.0.0.0/8 -p USA/RED/27N -s Default-First-Site-Name" wscript.echo "subnet_op -d -n 1.0.0.0/8" wscript.echo "subnet_op -d -n all" wscript.echo "subnet_op -c -i 172.16.31.10 -m 255.255.252.0" if bExit <> 0 then wscript.quit(1) end if end sub ' ' Determines which program is used to run this script. ' Returns true if the script host is cscript.exe ' function IsHostCscript() on error resume next dim strFullName dim strCommand dim i, j dim bReturn bReturn = false strFullName = WScript.FullName i = InStr(1, strFullName, ".exe", 1) if i <> 0 then j = InStrRev(strFullName, "\", i, 1) if j <> 0 then strCommand = Mid(strFullName, j+1, i-j-1) if LCase(strCommand) = "cscript" then bReturn = true end if end if end if if Err <> 0 then call wscript.echo("Error 0x" & hex(Err.Number) & " occurred. " & Err.Description _ & ". " & vbCRLF & "The scripting host could not be determined.") end if IsHostCscript = bReturn end function
<reponame>LaudateCorpus1/RosettaCodeData Option Explicit Option Base 0 Private Const intBase As Integer = 0 Private Type tPoint X As Double Y As Double End Type Private Type tCircle Centre As tPoint Radius As Double End Type Private Sub sApollonius() Dim Circle1 As tCircle Dim Circle2 As tCircle Dim Circle3 As tCircle Dim CTanTanTan(intBase + 0 to intBase + 7) As tCircle With Circle1 With .Centre .X = 0 .Y = 0 End With .Radius = 1 End With With Circle2 With .Centre .X = 4 .Y = 0 End With .Radius = 1 End With With Circle3 With .Centre .X = 2 .Y = 4 End With .Radius = 2 End With Call fApollonius(Circle1,Circle2,Circle3,CTanTanTan())) End Sub Public Function fApollonius(ByRef C1 As tCircle, _ ByRef C2 As tCircle, _ ByRef C3 As tCircle, _ ByRef CTanTanTan() As tCircle) As Boolean ' Solves the Problem of Apollonius (finding a circle tangent to three other circles in the plane) ' (x_s - x_1)^2 + (y_s - y_1)^2 = (r_s - Tan_1 * r_1)^2 ' (x_s - x_2)^2 + (y_s - y_2)^2 = (r_s - Tan_2 * r_2)^2 ' (x_s - x_3)^2 + (y_s - y_3)^2 = (r_s - Tan_3 * r_3)^2 ' x_s = M + N * r_s ' y_s = P + Q * r_s ' Parameters: ' C1, C2, C3 (circles in the problem) ' Tan1 := An indication if the solution should be externally or internally tangent (+1/-1) to Circle1 (C1) ' Tan2 := An indication if the solution should be externally or internally tangent (+1/-1) to Circle2 (C2) ' Tan3 := An indication if the solution should be externally or internally tangent (+1/-1) to Circle3 (C3) Dim Tangent(intBase + 0 To intBase + 7, intBase + 0 To intBase + 2) As Integer Dim lgTangent As Long Dim Tan1 As Integer Dim Tan2 As Integer Dim Tan3 As Integer Dim v11 As Double Dim v12 As Double Dim v13 As Double Dim v14 As Double Dim v21 As Double Dim v22 As Double Dim v23 As Double Dim v24 As Double Dim w12 As Double Dim w13 As Double Dim w14 As Double Dim w22 As Double Dim w23 As Double Dim w24 As Double Dim p As Double Dim Q As Double Dim M As Double Dim N As Double Dim A As Double Dim b As Double Dim c As Double Dim D As Double 'Check if circle centers are colinear If fColinearPoints(C1.Centre, C2.Centre, C3.Centre) Then fApollonius = False Exit Function End If Tangent(intBase + 0, intBase + 0) = -1 Tangent(intBase + 0, intBase + 1) = -1 Tangent(intBase + 0, intBase + 2) = -1 Tangent(intBase + 1, intBase + 0) = -1 Tangent(intBase + 1, intBase + 1) = -1 Tangent(intBase + 1, intBase + 2) = 1 Tangent(intBase + 2, intBase + 0) = -1 Tangent(intBase + 2, intBase + 1) = 1 Tangent(intBase + 2, intBase + 2) = -1 Tangent(intBase + 3, intBase + 0) = -1 Tangent(intBase + 3, intBase + 1) = 1 Tangent(intBase + 3, intBase + 2) = 1 Tangent(intBase + 4, intBase + 0) = 1 Tangent(intBase + 4, intBase + 1) = -1 Tangent(intBase + 4, intBase + 2) = -1 Tangent(intBase + 5, intBase + 0) = 1 Tangent(intBase + 5, intBase + 1) = -1 Tangent(intBase + 5, intBase + 2) = 1 Tangent(intBase + 6, intBase + 0) = 1 Tangent(intBase + 6, intBase + 1) = 1 Tangent(intBase + 6, intBase + 2) = -1 Tangent(intBase + 7, intBase + 0) = 1 Tangent(intBase + 7, intBase + 1) = 1 Tangent(intBase + 7, intBase + 2) = 1 For lgTangent = LBound(Tangent) To UBound(Tangent) Tan1 = Tangent(lgTangent, intBase + 0) Tan2 = Tangent(lgTangent, intBase + 1) Tan3 = Tangent(lgTangent, intBase + 2) v11 = 2 * (C2.Centre.X - C1.Centre.X) v12 = 2 * (C2.Centre.Y - C1.Centre.Y) v13 = (C1.Centre.X * C1.Centre.X) _ - (C2.Centre.X * C2.Centre.X) _ + (C1.Centre.Y * C1.Centre.Y) _ - (C2.Centre.Y * C2.Centre.Y) _ - (C1.Radius * C1.Radius) _ + (C2.Radius * C2.Radius) v14 = 2 * (Tan2 * C2.Radius - Tan1 * C1.Radius) v21 = 2 * (C3.Centre.X - C2.Centre.X) v22 = 2 * (C3.Centre.Y - C2.Centre.Y) v23 = (C2.Centre.X * C2.Centre.X) _ - (C3.Centre.X * C3.Centre.X) _ + (C2.Centre.Y * C2.Centre.Y) _ - (C3.Centre.Y * C3.Centre.Y) _ - (C2.Radius * C2.Radius) _ + (C3.Radius * C3.Radius) v24 = 2 * ((Tan3 * C3.Radius) - (Tan2 * C2.Radius)) w12 = v12 / v11 w13 = v13 / v11 w14 = v14 / v11 w22 = (v22 / v21) - w12 w23 = (v23 / v21) - w13 w24 = (v24 / v21) - w14 p = -w23 / w22 Q = w24 / w22 M = -(w12 * p) - w13 N = w14 - (w12 * Q) A = (N * N) + (Q * Q) - 1 b = 2 * ((M * N) - (N * C1.Centre.X) + (p * Q) - (Q * C1.Centre.Y) + (Tan1 * C1.Radius)) c = (C1.Centre.X * C1.Centre.X) _ + (M * M) _ - (2 * M * C1.Centre.X) _ + (p * p) _ + (C1.Centre.Y * C1.Centre.Y) _ - (2 * p * C1.Centre.Y) _ - (C1.Radius * C1.Radius) 'Find a root of a quadratic equation (requires the circle centers not to be e.g. colinear) D = (b * b) - (4 * A * c) With CTanTanTan(lgTangent) .Radius = (-b - VBA.Sqr(D)) / (2 * A) .Centre.X = M + (N * .Radius) .Centre.Y = p + (Q * .Radius) End With Next lgTangent fApollonius = True End Function
<filename>Task/Dot-product/Visual-Basic/dot-product.vb Option Explicit Function DotProduct(a() As Long, b() As Long) As Long Dim l As Long, u As Long, i As Long Debug.Assert DotProduct = 0 'return value automatically initialized with 0 l = LBound(a()) If l = LBound(b()) Then u = UBound(a()) If u = UBound(b()) Then For i = l To u DotProduct = DotProduct + a(i) * b(i) Next i Exit Function End If End If Err.Raise vbObjectError + 123, , "invalid input" End Function Sub Main() Dim a() As Long, b() As Long, x As Long ReDim a(2) a(0) = 1 a(1) = 3 a(2) = -5 ReDim b(2) b(0) = 4 b(1) = -2 b(2) = -1 x = DotProduct(a(), b()) Debug.Assert x = 3 ReDim Preserve a(3) a(3) = 10 ReDim Preserve b(3) b(3) = 2 x = DotProduct(a(), b()) Debug.Assert x = 23 ReDim Preserve a(4) a(4) = 10 On Error Resume Next x = DotProduct(a(), b()) Debug.Assert Err.Number = vbObjectError + 123 Debug.Assert Err.Description = "invalid input" End Sub
'function arguments: "num" is the number to sequence and "return" is the value to return - "s" for the sequence or '"e" for the number elements. Function hailstone_sequence(num,return) n = num sequence = num elements = 1 Do Until n = 1 If n Mod 2 = 0 Then n = n / 2 Else n = (3 * n) + 1 End If sequence = sequence & " " & n elements = elements + 1 Loop Select Case return Case "s" hailstone_sequence = sequence Case "e" hailstone_sequence = elements End Select End Function 'test driving. 'show sequence for 27 WScript.StdOut.WriteLine "Sequence for 27: " & hailstone_sequence(27,"s") WScript.StdOut.WriteLine "Number of Elements: " & hailstone_sequence(27,"e") WScript.StdOut.WriteBlankLines(1) 'show the number less than 100k with the longest sequence count = 1 n_elements = 0 n_longest = "" Do While count < 100000 current_n_elements = hailstone_sequence(count,"e") If current_n_elements > n_elements Then n_elements = current_n_elements n_longest = "Number: " & count & " Length: " & n_elements End If count = count + 1 Loop WScript.StdOut.WriteLine "Number less than 100k with the longest sequence: " WScript.StdOut.WriteLine n_longest
VERSION 5.00 Object = "{6B7E6392-850A-101B-AFC0-4210102A8DA7}#1.2#0"; "comctl32.ocx" Begin VB.Form MainForm Caption = "Metabase Editor" ClientHeight = 7590 ClientLeft = 165 ClientTop = 735 ClientWidth = 10290 Icon = "MetaEdit.frx":0000 LinkTopic = "Form1" ScaleHeight = 7590 ScaleWidth = 10290 StartUpPosition = 3 'Windows Default Begin ComctlLib.ListView DataListView Height = 4575 Left = 3720 TabIndex = 1 Top = 120 Width = 6495 _ExtentX = 11456 _ExtentY = 8070 View = 3 LabelEdit = 1 Sorted = -1 'True LabelWrap = -1 'True HideSelection = -1 'True _Version = 327680 Icons = "DataImageList" SmallIcons = "DataImageList" ForeColor = -2147483640 BackColor = -2147483643 Appearance = 1 MouseIcon = "MetaEdit.frx":0442 NumItems = 6 BeginProperty ColumnHeader(1) {0713E8C7-850A-101B-AFC0-4210102A8DA7} Key = "Id" Object.Tag = "" Text = "Id" Object.Width = 176 EndProperty BeginProperty ColumnHeader(2) {0713E8C7-850A-101B-AFC0-4210102A8DA7} SubItemIndex = 1 Key = "Name" Object.Tag = "" Text = "Name" Object.Width = 176 EndProperty BeginProperty ColumnHeader(3) {0713E8C7-850A-101B-AFC0-4210102A8DA7} SubItemIndex = 2 Key = "Attributes" Object.Tag = "" Text = "Attributes" Object.Width = 176 EndProperty BeginProperty ColumnHeader(4) {0713E8C7-850A-101B-AFC0-4210102A8DA7} SubItemIndex = 3 Key = "UserType" Object.Tag = "" Text = "UT" Object.Width = 176 EndProperty BeginProperty ColumnHeader(5) {0713E8C7-850A-101B-AFC0-4210102A8DA7} SubItemIndex = 4 Key = "DataType" Object.Tag = "" Text = "DT" Object.Width = 176 EndProperty BeginProperty ColumnHeader(6) {0713E8C7-850A-101B-AFC0-4210102A8DA7} SubItemIndex = 5 Key = "Data" Object.Tag = "" Text = "Data" Object.Width = 176 EndProperty End Begin ComctlLib.StatusBar MainStatusBar Align = 2 'Align Bottom Height = 375 Left = 0 TabIndex = 2 Top = 7215 Width = 10290 _ExtentX = 18150 _ExtentY = 661 Style = 1 SimpleText = "" _Version = 327680 BeginProperty Panels {0713E89E-850A-101B-AFC0-4210102A8DA7} NumPanels = 1 BeginProperty Panel1 {0713E89F-850A-101B-AFC0-4210102A8DA7} TextSave = "" Key = "" Object.Tag = "" EndProperty EndProperty MouseIcon = "MetaEdit.frx":045E End Begin ComctlLib.TreeView KeyTreeView Height = 4575 Left = 120 TabIndex = 0 Top = 120 Width = 3495 _ExtentX = 6165 _ExtentY = 8070 _Version = 327680 Indentation = 529 LineStyle = 1 Style = 7 ImageList = "KeyImageList" Appearance = 1 MouseIcon = "MetaEdit.frx":047A End Begin ComctlLib.ListView ErrorListView Height = 2295 Left = 120 TabIndex = 3 Top = 4800 Visible = 0 'False Width = 10095 _ExtentX = 17806 _ExtentY = 4048 View = 3 LabelEdit = 1 Sorted = -1 'True LabelWrap = -1 'True HideSelection = -1 'True _Version = 327680 Icons = "ErrorImageList" SmallIcons = "ErrorImageList" ForeColor = -2147483640 BackColor = -2147483643 BorderStyle = 1 Appearance = 1 MouseIcon = "MetaEdit.frx":0496 NumItems = 5 BeginProperty ColumnHeader(1) {0713E8C7-850A-101B-AFC0-4210102A8DA7} Key = "Key" Object.Tag = "" Text = "Key" Object.Width = 1764 EndProperty BeginProperty ColumnHeader(2) {0713E8C7-850A-101B-AFC0-4210102A8DA7} SubItemIndex = 1 Key = "Property" Object.Tag = "" Text = "Property" Object.Width = 882 EndProperty BeginProperty ColumnHeader(3) {0713E8C7-850A-101B-AFC0-4210102A8DA7} SubItemIndex = 2 Key = "Id" Object.Tag = "" Text = "Id" Object.Width = 882 EndProperty BeginProperty ColumnHeader(4) {0713E8C7-850A-101B-AFC0-4210102A8DA7} SubItemIndex = 3 Key = "Severity" Object.Tag = "" Text = "Severity" Object.Width = 882 EndProperty BeginProperty ColumnHeader(5) {0713E8C7-850A-101B-AFC0-4210102A8DA7} SubItemIndex = 4 Key = "Description" Object.Tag = "" Text = "Description" Object.Width = 2646 EndProperty End Begin ComctlLib.ImageList ErrorImageList Left = 1560 Top = 7200 _ExtentX = 1005 _ExtentY = 1005 BackColor = -2147483643 ImageWidth = 16 ImageHeight = 16 MaskColor = 12632256 _Version = 327680 BeginProperty Images {0713E8C2-850A-101B-AFC0-4210102A8DA7} NumListImages = 3 BeginProperty ListImage1 {0713E8C3-850A-101B-AFC0-4210102A8DA7} Picture = "MetaEdit.frx":04B2 Key = "" EndProperty BeginProperty ListImage2 {0713E8C3-850A-101B-AFC0-4210102A8DA7} Picture = "MetaEdit.frx":07CC Key = "" EndProperty BeginProperty ListImage3 {0713E8C3-850A-101B-AFC0-4210102A8DA7} Picture = "MetaEdit.frx":0AE6 Key = "" EndProperty EndProperty End Begin ComctlLib.ImageList DataImageList Left = 840 Top = 7200 _ExtentX = 1005 _ExtentY = 1005 BackColor = -2147483643 ImageWidth = 16 ImageHeight = 16 MaskColor = 12632256 _Version = 327680 BeginProperty Images {0713E8C2-850A-101B-AFC0-4210102A8DA7} NumListImages = 2 BeginProperty ListImage1 {0713E8C3-850A-101B-AFC0-4210102A8DA7} Picture = "MetaEdit.frx":0E00 Key = "" EndProperty BeginProperty ListImage2 {0713E8C3-850A-101B-AFC0-4210102A8DA7} Picture = "MetaEdit.frx":111A Key = "" EndProperty EndProperty End Begin ComctlLib.ImageList KeyImageList Left = 120 Top = 7200 _ExtentX = 1005 _ExtentY = 1005 BackColor = -2147483643 ImageWidth = 16 ImageHeight = 16 MaskColor = 12632256 UseMaskColor = 0 'False _Version = 327680 BeginProperty Images {0713E8C2-850A-101B-AFC0-4210102A8DA7} NumListImages = 5 BeginProperty ListImage1 {0713E8C3-850A-101B-AFC0-4210102A8DA7} Picture = "MetaEdit.frx":1434 Key = "" EndProperty BeginProperty ListImage2 {0713E8C3-850A-101B-AFC0-4210102A8DA7} Picture = "MetaEdit.frx":174E Key = "" EndProperty BeginProperty ListImage3 {0713E8C3-850A-101B-AFC0-4210102A8DA7} Picture = "MetaEdit.frx":1A68 Key = "" EndProperty BeginProperty ListImage4 {0713E8C3-850A-101B-AFC0-4210102A8DA7} Picture = "MetaEdit.frx":1D82 Key = "" EndProperty BeginProperty ListImage5 {0713E8C3-850A-101B-AFC0-4210102A8DA7} Picture = "MetaEdit.frx":209C Key = "" EndProperty EndProperty End Begin VB.Menu MetabaseMenu Caption = "&Metabase" Begin VB.Menu BackupMenuItem Caption = "&Backup" Visible = 0 'False End Begin VB.Menu RestoreMenuItem Caption = "&Restore" Visible = 0 'False End Begin VB.Menu Seperator11 Caption = "-" Visible = 0 'False End Begin VB.Menu ExitMenuItem Caption = "E&xit" End End Begin VB.Menu EditMenu Caption = "&Edit" Begin VB.Menu NewMenu Caption = "&New" Begin VB.Menu NewKeyMenuItem Caption = "&Key" End Begin VB.Menu Seperator211 Caption = "-" End Begin VB.Menu NewDwordMenuItem Caption = "&DWORD" End Begin VB.Menu NewStringMenuItem Caption = "&String" End Begin VB.Menu NewBinaryMenuItem Caption = "&Binary" End Begin VB.Menu NewExpandStringMenuItem Caption = "&Expand String" End Begin VB.Menu NewMultiStringMenuItem Caption = "&Multi-String" End End Begin VB.Menu DeleteMenuItem Caption = "&Delete" Shortcut = {DEL} End Begin VB.Menu Seperator21 Caption = "-" End Begin VB.Menu RenameKeyMenuItem Caption = "&Rename Key" End Begin VB.Menu CopyKeyMenuItem Caption = "&Copy Key" End End Begin VB.Menu SearchMenu Caption = "&Search" Begin VB.Menu FindMenuItem Caption = "&Find" Shortcut = ^F End Begin VB.Menu FindNextMenuItem Caption = "Find &Next" Shortcut = {F3} End End Begin VB.Menu CheckMenu Caption = "&Check" Begin VB.Menu CheckSchemaMenuItem Caption = "&Schema" End Begin VB.Menu CheckKeyMenuItem Caption = "&Key" End Begin VB.Menu CheckAllMenuItem Caption = "&All Keys" End Begin VB.Menu Seperator31 Caption = "-" End Begin VB.Menu CheckOptionsMenuItem Caption = "&Options" End End Begin VB.Menu ViewMenu Caption = "&View" Begin VB.Menu ErrorListMenuItem Caption = "&Error List" Checked = -1 'True End Begin VB.Menu StatusBarMenuItem Caption = "&Status Bar" Checked = -1 'True End Begin VB.Menu Seprerator41 Caption = "-" End Begin VB.Menu RefreshMenuItem Caption = "&Refresh" Shortcut = {F5} End End Begin VB.Menu HelpMenu Caption = "&Help" Begin VB.Menu AboutMenuItem Caption = "&About Metabase Editor" End End Begin VB.Menu KeyMenu Caption = "KeyMenu" Visible = 0 'False Begin VB.Menu ExpandKeyMenuItem Caption = "&Expand" End Begin VB.Menu Seperator61 Caption = "-" End Begin VB.Menu KeyNewMenuItem Caption = "&New" Begin VB.Menu KeyNewKeyMenuItem Caption = "&Key" End Begin VB.Menu Seperator611 Caption = "-" End Begin VB.Menu KeyNewDwordMenuItem Caption = "&DWORD" End Begin VB.Menu KeyNewStringMenuItem Caption = "&String" End Begin VB.Menu KeyNewBinaryMenuItem Caption = "&Binary" End Begin VB.Menu KeyNewExpandSzMenuItem Caption = "&Expand String" End Begin VB.Menu KeyNewMultiSzMenuItem Caption = "&Multi-String" End End Begin VB.Menu KeyDeleteMenuItem Caption = "&Delete" End Begin VB.Menu KeyRenameMenuItem Caption = "&Rename" End Begin VB.Menu KeyCopyMenuItem Caption = "&Copy" End Begin VB.Menu Seperator62 Caption = "-" End Begin VB.Menu KeyCheckMenuItem Caption = "&Check" End End Begin VB.Menu DataMenu Caption = "DataMenu" Visible = 0 'False Begin VB.Menu DataModifyMenuItem Caption = "&Modify" End Begin VB.Menu Seperator71 Caption = "-" End Begin VB.Menu DataNewMenu Caption = "&New" Begin VB.Menu DataNewDwordMenuItem Caption = "&DWORD" End Begin VB.Menu DataNewStringMenuItem Caption = "&String" End Begin VB.Menu DataNewBinaryMenuItem Caption = "&Binary" End Begin VB.Menu DataNewExpandSzMenuItem Caption = "&ExpandString" End Begin VB.Menu DataNewMultiSzMenuItem Caption = "&Multi-String" End End Begin VB.Menu DataDeleteMenuItem Caption = "&Delete" End End End Attribute VB_Name = "MainForm" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Option Explicit DefInt A-Z 'Globals 'Metabase globals Public MetaUtilObj As Object Const METADATA_NO_ATTRIBUTES = &H0 Const METADATA_INHERIT = &H1 Const METADATA_PARTIAL_PATH = &H2 Const METADATA_SECURE = &H4 Const METADATA_REFERENCE = &H8 Const METADATA_VOLATILE = &H10 Const METADATA_ISINHERITED = &H20 Const METADATA_INSERT_PATH = &H40 Const IIS_MD_UT_SERVER = 1 Const IIS_MD_UT_FILE = 2 Const IIS_MD_UT_WAM = 100 Const ASP_MD_UT_APP = 101 Const ALL_METADATA = 0 Const DWORD_METADATA = 1 Const STRING_METADATA = 2 Const BINARY_METADATA = 3 Const EXPANDSZ_METADATA = 4 Const MULTISZ_METADATA = 5 'Layout globals Const FormBoarder = 40 Dim VDividerPos As Long 'Start of divider Dim HDividerPos As Long 'Top relative to the status bar Dim VDividerHeld As Boolean Dim HDividerHeld As Boolean 'State globals Dim AppCursor As Long Dim KeyLabelEditOrigText As String Dim KeyLabelEditOrigFullPath As String Private Sub Form_Load() AppCursor = vbDefault VDividerHeld = False HDividerHeld = False 'Load Config Config.LoadConfig 'Setup the form VDividerPos = Config.MainFormVDivider HDividerPos = Config.MainFormHDivider MainForm.Height = Config.MainFormHeight MainForm.Width = Config.MainFormWidth If Config.StatusBar Then MainStatusBar.Visible = True StatusBarMenuItem.Checked = True Else MainStatusBar.Visible = False StatusBarMenuItem.Checked = False End If ErrorListMenuItem.Checked = False ErrorListView.Visible = False LayoutForm DataListView.ColumnHeaders(1).Width = Config.DataListIdColWidth DataListView.ColumnHeaders(2).Width = Config.DataListNameColWidth DataListView.ColumnHeaders(3).Width = Config.DataListAttrColWidth DataListView.ColumnHeaders(4).Width = Config.DataListUTColWidth DataListView.ColumnHeaders(5).Width = Config.DataListDTColWidth DataListView.ColumnHeaders(6).Width = Config.DataListDataColWidth ErrorListView.ColumnHeaders(1).Width = Config.ErrorListKeyColWidth ErrorListView.ColumnHeaders(2).Width = Config.ErrorListPropColWidth ErrorListView.ColumnHeaders(3).Width = Config.ErrorListIdColWidth ErrorListView.ColumnHeaders(4).Width = Config.ErrorListSeverityColWidth ErrorListView.ColumnHeaders(5).Width = Config.ErrorListDescColWidth 'MsgBox "You may now attach your debugger." 'Set the data Set MetaUtilObj = CreateObject("MSWC.MetaUtil") LoadKeys ShowSelectedNode End Sub Private Sub Form_Unload(Cancel As Integer) If MainForm.WindowState = vbNormal Then Config.MainFormHeight = MainForm.Height Config.MainFormWidth = MainForm.Width End If Config.MainFormVDivider = VDividerPos Config.MainFormHDivider = HDividerPos Config.DataListIdColWidth = DataListView.ColumnHeaders(1).Width Config.DataListNameColWidth = DataListView.ColumnHeaders(2).Width Config.DataListAttrColWidth = DataListView.ColumnHeaders(3).Width Config.DataListUTColWidth = DataListView.ColumnHeaders(4).Width Config.DataListDTColWidth = DataListView.ColumnHeaders(5).Width Config.DataListDataColWidth = DataListView.ColumnHeaders(6).Width Config.ErrorListKeyColWidth = ErrorListView.ColumnHeaders(1).Width Config.ErrorListPropColWidth = ErrorListView.ColumnHeaders(2).Width Config.ErrorListIdColWidth = ErrorListView.ColumnHeaders(3).Width Config.ErrorListSeverityColWidth = ErrorListView.ColumnHeaders(4).Width Config.ErrorListDescColWidth = ErrorListView.ColumnHeaders(5).Width Config.SaveConfig End Sub Private Sub Form_Resize() LayoutForm End Sub Private Sub Form_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single) If (x > VDividerPos) And _ (x < VDividerPos + FormBoarder) And _ (y <= KeyTreeView.Top + KeyTreeView.Height) Then VDividerHeld = True ElseIf ErrorListView.Visible And _ (y > KeyTreeView.Top + KeyTreeView.Height) And _ (y < ErrorListView.Top) Then HDividerHeld = True End If End Sub Private Sub Form_MouseMove(Button As Integer, Shift As Integer, x As Single, y As Single) If (x > VDividerPos) And _ (x < VDividerPos + FormBoarder) And _ (y <= KeyTreeView.Top + KeyTreeView.Height) Then 'Show that the divider can be moved MainForm.MousePointer = vbSizeWE ElseIf ErrorListView.Visible And _ (y > KeyTreeView.Top + KeyTreeView.Height) And _ (y < ErrorListView.Top) Then 'Show that the divider can be moved MainForm.MousePointer = vbSizeNS ElseIf Not (VDividerHeld Or HDividerHeld) Then 'Revert to normal MainForm.MousePointer = AppCursor End If If VDividerHeld Then 'Move the divider, centering on the cursor VDividerPos = x - (FormBoarder / 2) LayoutForm ElseIf HDividerHeld Then 'Move the divider, centering on the cursor If MainStatusBar.Visible Then HDividerPos = MainStatusBar.Top - y - FormBoarder - (FormBoarder / 2) Else HDividerPos = MainForm.ScaleHeight - y - FormBoarder - (FormBoarder / 2) End If LayoutForm End If End Sub Private Sub KeyTreeView_MouseMove(Button As Integer, Shift As Integer, x As Single, y As Single) If Not (VDividerHeld Or HDividerHeld) Then 'Revert to normal MainForm.MousePointer = AppCursor End If End Sub Private Sub DataListView_MouseMove(Button As Integer, Shift As Integer, x As Single, y As Single) If Not (VDividerHeld Or HDividerHeld) Then 'Revert to normal MainForm.MousePointer = AppCursor End If End Sub Private Sub ErrorListView_MouseMove(Button As Integer, Shift As Integer, x As Single, y As Single) If Not (VDividerHeld Or HDividerHeld) Then 'Revert to normal MainForm.MousePointer = AppCursor End If End Sub Private Sub Form_MouseUp(Button As Integer, Shift As Integer, x As Single, y As Single) If VDividerHeld Then 'Move the divider, centering on the cursor VDividerPos = x - (FormBoarder / 2) LayoutForm VDividerHeld = False ElseIf HDividerHeld Then 'Move the divider, centering on the cursor If MainStatusBar.Visible Then HDividerPos = MainStatusBar.Top - y - FormBoarder - (FormBoarder / 2) Else HDividerPos = MainForm.ScaleHeight - y - FormBoarder - (FormBoarder / 2) End If LayoutForm HDividerHeld = False End If End Sub Private Sub LayoutForm() If MainForm.WindowState <> vbMinimized Then 'Enforce divider ranges If VDividerPos < 2 * FormBoarder Then VDividerPos = 2 * FormBoarder ElseIf VDividerPos > MainForm.ScaleWidth - (FormBoarder * 2) Then VDividerPos = MainForm.ScaleWidth - (FormBoarder * 2) End If If HDividerPos < FormBoarder Then HDividerPos = FormBoarder ElseIf HDividerPos > MainForm.ScaleHeight - MainStatusBar.Height - (FormBoarder * 3) Then HDividerPos = MainForm.ScaleHeight - MainStatusBar.Height - (FormBoarder * 3) End If 'Enforce a minimum size If MainForm.ScaleWidth < FormBoarder * 3 + VDividerPos Then MainForm.Width = (MainForm.Width - MainForm.ScaleWidth) + FormBoarder * 3 + VDividerPos Exit Sub End If If MainStatusBar.Visible And ErrorListView.Visible Then If MainForm.ScaleHeight < MainStatusBar.Height + HDividerPos + (FormBoarder * 4) Then MainForm.Height = (MainForm.Height - MainForm.ScaleHeight) + MainStatusBar.Height + HDividerPos + (FormBoarder * 4) Exit Sub End If ElseIf MainStatusBar.Visible Then If MainForm.ScaleHeight < MainStatusBar.Height + (FormBoarder * 3) Then MainForm.Height = (MainForm.Height - MainForm.ScaleHeight) + MainStatusBar.Height + (FormBoarder * 3) Exit Sub End If ElseIf ErrorListView.Visible Then If MainForm.ScaleHeight < HDividerPos + (FormBoarder * 3) Then MainForm.Height = (MainForm.Height - MainForm.ScaleHeight) + HDividerPos + (FormBoarder * 3) Exit Sub End If Else If MainForm.ScaleHeight < (FormBoarder * 3) Then MainForm.ScaleHeight = (MainForm.Height - MainForm.ScaleHeight) + (FormBoarder * 3) Exit Sub End If End If 'KeyTreeView KeyTreeView.Left = FormBoarder KeyTreeView.Top = FormBoarder KeyTreeView.Width = VDividerPos - FormBoarder If MainStatusBar.Visible And ErrorListView.Visible Then KeyTreeView.Height = MainForm.ScaleHeight - HDividerPos - MainStatusBar.Height - (3 * FormBoarder) ElseIf MainStatusBar.Visible Then KeyTreeView.Height = MainForm.ScaleHeight - MainStatusBar.Height - (2 * FormBoarder) ElseIf ErrorListView.Visible Then KeyTreeView.Height = MainForm.ScaleHeight - HDividerPos - (3 * FormBoarder) Else KeyTreeView.Height = MainForm.ScaleHeight - (2 * FormBoarder) End If 'DataListView DataListView.Left = VDividerPos + FormBoarder DataListView.Top = FormBoarder DataListView.Width = MainForm.ScaleWidth - VDividerPos - (2 * FormBoarder) If MainStatusBar.Visible And ErrorListView.Visible Then DataListView.Height = MainForm.ScaleHeight - HDividerPos - MainStatusBar.Height - (3 * FormBoarder) ElseIf MainStatusBar.Visible Then DataListView.Height = MainForm.ScaleHeight - MainStatusBar.Height - (2 * FormBoarder) ElseIf ErrorListView.Visible Then DataListView.Height = MainForm.ScaleHeight - HDividerPos - (3 * FormBoarder) Else DataListView.Height = MainForm.ScaleHeight - (2 * FormBoarder) End If 'ErrorListView If ErrorListView.Visible Then ErrorListView.Left = FormBoarder ErrorListView.Width = MainForm.ScaleWidth - (2 * FormBoarder) ErrorListView.Top = KeyTreeView.Top + KeyTreeView.Height + FormBoarder ErrorListView.Height = HDividerPos End If End If End Sub Private Sub KeyTreeView_Expand(ByVal CurNode As ComctlLib.Node) 'Look for grandchildren If (CurNode.Tag) And (CurNode.Children > 0) Then Dim SubNode As Node Dim SubKeyStr As Variant Dim NewNode As Node 'For Each sub-node Set SubNode = CurNode.Child Do For Each SubKeyStr In MetaUtilObj.EnumKeys(SubNode.FullPath) Set NewNode = KeyTreeView.Nodes.Add(SubNode, tvwChild, SubNode.FullPath & "/" & SubKeyStr, SubKeyStr) NewNode.Key = NewNode.FullPath NewNode.Image = 1 NewNode.ExpandedImage = 2 'Set node as unvisited NewNode.Tag = True Next 'Resort SubNode.Sorted = True 'Next sub-node or bail If SubNode Is SubNode.LastSibling Then Exit Do Set SubNode = SubNode.Next Loop 'Set node as visited CurNode.Tag = False End If End Sub Private Sub KeyTreeView_Collapse(ByVal Node As ComctlLib.Node) ShowSelectedNode End Sub Private Sub KeyTreeView_KeyPress(KeyAscii As Integer) ShowSelectedNode End Sub Private Sub KeyTreeView_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single) If Button = vbRightButton Then PopupMenu KeyMenu, , , , ExpandKeyMenuItem End If End Sub Private Sub KeyTreeView_NodeClick(ByVal Node As ComctlLib.Node) ShowSelectedNode End Sub Private Sub KeyTreeView_BeforeLabelEdit(Cancel As Integer) If KeyTreeView.SelectedItem Is Nothing Then 'Cancel Cancel = 1 Else KeyLabelEditOrigText = KeyTreeView.SelectedItem.Text KeyLabelEditOrigFullPath = KeyTreeView.SelectedItem.FullPath End If End Sub Private Sub KeyTreeView_AfterLabelEdit(Cancel As Integer, NewString As String) On Error GoTo LError Dim NewFullPath As String If (KeyTreeView.SelectedItem Is Nothing) Or (NewString = "") Then Cancel = 1 ElseIf KeyLabelEditOrigText <> "" Then 'Figure out the new full path If KeyTreeView.SelectedItem.Root Is KeyTreeView.SelectedItem Then NewFullPath = NewString Else NewFullPath = KeyTreeView.SelectedItem.Parent.FullPath & "\" & NewString End If If NewString <> KeyLabelEditOrigText Then 'Rename key KeyTreeView.SelectedItem.Key = NewFullPath MetaUtilObj.RenameKey KeyLabelEditOrigFullPath, NewFullPath KeyTreeView.SelectedItem.Text = NewString End If End If Exit Sub LError: KeyTreeView.SelectedItem.Text = KeyLabelEditOrigText KeyTreeView.SelectedItem.Key = KeyLabelEditOrigFullPath MsgBox "Failure to rename key: " & Err.Description, vbExclamation + vbOKOnly, "Rename Key" Cancel = 1 End Sub Private Sub LoadKeys() 'Clear selected node DataListView.Tag = "" 'Initialize the tree Dim KeyStr As Variant Dim NewNode As Node Dim SubKeyStr As Variant Dim NewSubNode As Node For Each KeyStr In MetaUtilObj.EnumKeys("") Set NewNode = KeyTreeView.Nodes.Add(, , KeyStr, KeyStr) NewNode.Key = NewNode.FullPath NewNode.Image = 3 'Set node as unvisited NewNode.Tag = True For Each SubKeyStr In MetaUtilObj.EnumKeys(KeyStr) Set NewSubNode = KeyTreeView.Nodes.Add(NewNode, tvwChild, KeyStr & "/" & SubKeyStr, SubKeyStr) NewSubNode.Key = NewSubNode.FullPath NewSubNode.Image = 1 NewSubNode.ExpandedImage = 2 'Set node as unvisited NewSubNode.Tag = True Next 'Resort NewNode.Sorted = True Next 'Resort KeyTreeView.Sorted = True Set KeyTreeView.SelectedItem = KeyTreeView.Nodes.Item(1) End Sub Public Sub SelectKey(Key As String) Dim ParentKey As String Dim ChildKey As String Dim CurKey As String ParentKey = Key ChildKey = "" Do While ParentKey <> "" 'Get the current key CurKey = "" Do While (ParentKey <> "") And _ (Left(ParentKey, 1) <> "\") And _ (Left(ParentKey, 1) <> "/") CurKey = CurKey & Left(ParentKey, 1) ParentKey = Right(ParentKey, Len(ParentKey) - 1) Loop If (ParentKey <> "") Then 'Skip the slash ParentKey = Right(ParentKey, Len(ParentKey) - 1) End If If ChildKey = "" Then ChildKey = CurKey Else ChildKey = ChildKey & "\" & CurKey End If If ParentKey <> "" Then KeyTreeView.Nodes(ChildKey).Expanded = True End If Loop Set KeyTreeView.SelectedItem = KeyTreeView.Nodes(ChildKey) KeyTreeView.Nodes(ChildKey).EnsureVisible ShowSelectedNode KeyTreeView.SetFocus End Sub Private Sub RefreshKeys() Dim SelectedKey As String 'Save the selected key If KeyTreeView.SelectedItem Is Nothing Then SelectedKey = "" Else SelectedKey = KeyTreeView.SelectedItem.FullPath End If 'Reload KeyTreeView.Nodes.Clear LoadKeys 'Restore the selected key If SelectedKey <> "" Then SelectKey SelectedKey End If End Sub Private Sub DataListView_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single) If Button = vbRightButton Then PopupMenu DataMenu, , , , DataModifyMenuItem End If End Sub Private Sub DataListView_DblClick() If Not DataListView.SelectedItem Is Nothing Then 'Edit the selected data item If DataListView.SelectedItem.SubItems(4) = "DWord" Or _ DataListView.SelectedItem.SubItems(4) = "String" Or _ DataListView.SelectedItem.SubItems(4) = "ExpandSz" Or _ DataListView.SelectedItem.SubItems(4) = "Binary" Then 'Set the form parameters SimpleEditForm.Machine = KeyTreeView.SelectedItem.Root.FullPath SimpleEditForm.Key = KeyTreeView.SelectedItem.FullPath SimpleEditForm.Id = CLng(DataListView.SelectedItem.Text) 'Run it SimpleEditForm.Init SimpleEditForm.Show vbModal, Me ElseIf DataListView.SelectedItem.SubItems(4) = "MultiSz" Then 'Set the form parameters MultiEditForm.Machine = KeyTreeView.SelectedItem.Root.FullPath MultiEditForm.Key = KeyTreeView.SelectedItem.FullPath MultiEditForm.Id = CLng(DataListView.SelectedItem.Text) 'Run it MultiEditForm.Init MultiEditForm.Show vbModal, Me End If 'Refresh DataListView RefreshData End If End Sub Private Sub DataListView_ColumnClick(ByVal ColumnHeader As ComctlLib.ColumnHeader) If DataListView.SortKey = ColumnHeader.Index - 1 Then 'Reverse the sort order If DataListView.SortOrder = lvwAscending Then DataListView.SortOrder = lvwDescending Else DataListView.SortOrder = lvwAscending End If Else 'Sort ascending on this column DataListView.SortOrder = lvwAscending DataListView.SortKey = ColumnHeader.Index - 1 End If ' Resort DataListView.Sorted = True End Sub Private Sub ShowSelectedNode() Dim SelNode As Node Set SelNode = KeyTreeView.SelectedItem If SelNode Is Nothing Then DataListView.ListItems.Clear ElseIf SelNode.FullPath <> DataListView.Tag Then 'Update the status bar MainStatusBar.SimpleText = SelNode.FullPath 'Update the DataListView DataListView.Tag = SelNode.FullPath DataListView.ListItems.Clear 'Property values are copied for efficency (less calls into Property) Dim Property As Variant Dim NewItem As ListItem Dim Id As Long Dim Attributes As Long Dim AttrStr As String Dim UserType As Long Dim DataType As Long Dim Data As Variant Dim DataStr As String Dim DataBStr As String Dim i As Integer Dim DataByte As Integer For Each Property In MetaUtilObj.EnumProperties(SelNode.FullPath) Set NewItem = DataListView.ListItems.Add() 'Id (padded with spaces so it sorts) Id = Property.Id NewItem.Text = String(10 - Len(Str(Id)), " ") + Str(Id) 'Name NewItem.SubItems(1) = Property.Name 'Attributes Attributes = Property.Attributes AttrStr = "" If (Attributes And METADATA_INHERIT) = METADATA_INHERIT Then If AttrStr <> "" Then AttrStr = AttrStr & " " AttrStr = AttrStr & "Inh" End If If (Attributes And METADATA_PARTIAL_PATH) = METADATA_PARTIAL_PATH Then If AttrStr <> "" Then AttrStr = AttrStr & " " AttrStr = AttrStr & "Pp" End If If (Attributes And METADATA_SECURE) = METADATA_SECURE Then If AttrStr <> "" Then AttrStr = AttrStr & " " AttrStr = AttrStr & "Sec" End If If (Attributes And METADATA_REFERENCE) = METADATA_REFERENCE Then If AttrStr <> "" Then AttrStr = AttrStr & " " AttrStr = AttrStr & "Ref" End If If (Attributes And METADATA_VOLATILE) = METADATA_VOLATILE Then If AttrStr <> "" Then AttrStr = AttrStr & " " AttrStr = AttrStr & "Vol" End If If (Attributes And METADATA_ISINHERITED) = METADATA_ISINHERITED Then If AttrStr <> "" Then AttrStr = AttrStr & " " AttrStr = AttrStr & "IsInh" End If If (Attributes And METADATA_INSERT_PATH) = METADATA_INSERT_PATH Then If AttrStr <> "" Then AttrStr = AttrStr & " " AttrStr = AttrStr & "Ins" End If NewItem.SubItems(2) = AttrStr 'User Type UserType = Property.UserType If UserType = IIS_MD_UT_SERVER Then NewItem.SubItems(3) = "Server" ElseIf UserType = IIS_MD_UT_FILE Then NewItem.SubItems(3) = "File" ElseIf UserType = IIS_MD_UT_WAM Then NewItem.SubItems(3) = "WAM" ElseIf UserType = ASP_MD_UT_APP Then NewItem.SubItems(3) = "ASP App" Else NewItem.SubItems(3) = Str(UserType) End If 'Data Type DataType = Property.DataType If DataType = ALL_METADATA Then NewItem.SubItems(4) = "*All*" ElseIf DataType = DWORD_METADATA Then NewItem.SubItems(4) = "DWord" ElseIf DataType = STRING_METADATA Then NewItem.SubItems(4) = "String" ElseIf DataType = BINARY_METADATA Then NewItem.SubItems(4) = "Binary" ElseIf DataType = EXPANDSZ_METADATA Then NewItem.SubItems(4) = "ExpandSz" ElseIf DataType = MULTISZ_METADATA Then NewItem.SubItems(4) = "MultiSz" Else NewItem.SubItems(4) = "*Unknown*" End If 'Data Data = Property.Data If (Attributes And METADATA_SECURE) = METADATA_SECURE Then DataStr = "*Not Displayed*" ElseIf DataType = BINARY_METADATA Then 'Display as a list of bytes DataStr = "" DataBStr = Property.Data For i = 1 To LenB(DataBStr) DataByte = AscB(MidB(DataBStr, i, 1)) If DataByte < 16 Then DataStr = DataStr & "0" & Hex(AscB(MidB(DataBStr, i, 1))) & " " Else DataStr = DataStr & Hex(AscB(MidB(DataBStr, i, 1))) & " " End If Next ElseIf DataType = MULTISZ_METADATA Then 'Display as a list of strings If IsArray(Data) Then DataStr = "" For i = LBound(Data) To UBound(Data) If i = LBound(Data) Then DataStr = CStr(Data(i)) Else DataStr = DataStr & " " & CStr(Data(i)) End If Next End If Else DataStr = CStr(Data) End If NewItem.SubItems(5) = DataStr 'Set the icon If (DataType = STRING_METADATA) Or _ (DataType = EXPANDSZ_METADATA) Or _ (DataType = MULTISZ_METADATA) Then NewItem.SmallIcon = 1 Else NewItem.SmallIcon = 2 End If Next End If End Sub Public Sub SelectProperty(PropertyStr As String) 'Had to search since I couldn't get the key property working Dim i As Long i = 1 Do While (i <= DataListView.ListItems.Count) And (PropertyStr <> DataListView.ListItems(i)) i = i + 1 Loop If PropertyStr = DataListView.ListItems(i) Then 'Found it Set DataListView.SelectedItem = DataListView.ListItems(i) DataListView.ListItems(i).EnsureVisible DataListView.SetFocus End If End Sub Private Sub RefreshData() Dim SelectedProperty As String 'Save the selected property If DataListView.SelectedItem Is Nothing Then SelectedProperty = "" Else SelectedProperty = DataListView.SelectedItem.Text End If 'Reload DataListView.Tag = "" ShowSelectedNode 'Restore the selected property If SelectedProperty <> "" Then SelectProperty SelectedProperty End If End Sub Private Sub ErrorListView_ColumnClick(ByVal ColumnHeader As ComctlLib.ColumnHeader) If ErrorListView.SortKey = ColumnHeader.Index - 1 Then 'Reverse the sort order If ErrorListView.SortOrder = lvwAscending Then ErrorListView.SortOrder = lvwDescending Else ErrorListView.SortOrder = lvwAscending End If Else 'Sort ascending on this column ErrorListView.SortOrder = lvwAscending ErrorListView.SortKey = ColumnHeader.Index - 1 End If ' Resort ErrorListView.Sorted = True End Sub Private Sub ErrorListView_DblClick() If Not ErrorListView.SelectedItem Is Nothing Then SelectKey ErrorListView.SelectedItem.Text If ErrorListView.SelectedItem.SubItems(1) <> " 0" Then SelectProperty ErrorListView.SelectedItem.SubItems(1) End If End If End Sub Private Sub AddErrorToErrorListView(CheckError As Variant) Dim NewItem As ListItem Dim Key As String Dim Property As Long Dim Id As Long Dim Severity As Long Dim Description As String Key = CheckError.Key Property = CheckError.Property Id = CheckError.Id Severity = CheckError.Severity Description = CheckError.Description Set NewItem = ErrorListView.ListItems.Add NewItem.Text = Key NewItem.SubItems(1) = String(10 - Len(Str(Property)), " ") + Str(Property) NewItem.SubItems(2) = String(10 - Len(Str(Id)), " ") + Str(Id) NewItem.SubItems(3) = Str(Severity) NewItem.SubItems(4) = Description NewItem.SmallIcon = Severity End Sub Private Sub ExitMenuItem_Click() Unload MainForm End Sub Private Function GenerateKeyName(ParentKey As String) As String 'Keep trying until we fail on a key lookup, then we know we have a unique name On Error GoTo LError Dim Name As String Dim Num As Long Dim Hit As Node Num = 0 Do Num = Num + 1 Name = "NewKey" & Str(Num) Set Hit = KeyTreeView.Nodes(ParentKey & "\" & Name) Loop LError: GenerateKeyName = Name End Function Private Sub NewKeyMenuItem_Click() Dim NewName As String Dim NewNode As Node If Not KeyTreeView.SelectedItem Is Nothing Then 'Expand the parent KeyTreeView.SelectedItem.Expanded = True 'Create it NewName = GenerateKeyName(KeyTreeView.SelectedItem.FullPath) Set NewNode = KeyTreeView.Nodes.Add(KeyTreeView.SelectedItem, tvwChild, KeyTreeView.SelectedItem.FullPath & "\" & NewName, NewName) NewNode.Key = NewNode.FullPath NewNode.Image = 1 NewNode.ExpandedImage = 2 'Set node as visited NewNode.Tag = False MetaUtilObj.CreateKey NewNode.FullPath 'Select It Set KeyTreeView.SelectedItem = NewNode DataListView.ListItems.Clear 'Edit it KeyTreeView.StartLabelEdit Else MsgBox "No key selected", vbOKOnly + vbExclamation, "Rename Key" End If End Sub Private Sub NewDwordMenuItem_Click() If Not KeyTreeView.SelectedItem Is Nothing Then 'Set the form parameters SimpleEditForm.Machine = KeyTreeView.SelectedItem.Root.FullPath SimpleEditForm.Key = KeyTreeView.SelectedItem.FullPath SimpleEditForm.Id = 0 SimpleEditForm.NewDataType = DWORD_METADATA 'Run it SimpleEditForm.Init SimpleEditForm.Show vbModal, Me 'Refresh DataListView RefreshData Else MsgBox "No key selected", vbOKOnly + vbExclamation, "New DWord" End If End Sub Private Sub NewStringMenuItem_Click() If Not KeyTreeView.SelectedItem Is Nothing Then 'Set the form parameters SimpleEditForm.Machine = KeyTreeView.SelectedItem.Root.FullPath SimpleEditForm.Key = KeyTreeView.SelectedItem.FullPath SimpleEditForm.Id = 0 SimpleEditForm.NewDataType = STRING_METADATA 'Run it SimpleEditForm.Init SimpleEditForm.Show vbModal, Me 'Refresh DataListView RefreshData Else MsgBox "No key selected", vbOKOnly + vbExclamation, "New String" End If End Sub Private Sub NewExpandStringMenuItem_Click() If Not KeyTreeView.SelectedItem Is Nothing Then 'Set the form parameters SimpleEditForm.Machine = KeyTreeView.SelectedItem.Root.FullPath SimpleEditForm.Key = KeyTreeView.SelectedItem.FullPath SimpleEditForm.Id = 0 SimpleEditForm.NewDataType = EXPANDSZ_METADATA 'Run it SimpleEditForm.Init SimpleEditForm.Show vbModal, Me 'Refresh DataListView RefreshData Else MsgBox "No key selected", vbOKOnly + vbExclamation, "New Expand String" End If End Sub Private Sub NewBinaryMenuItem_Click() If Not KeyTreeView.SelectedItem Is Nothing Then 'Set the form parameters SimpleEditForm.Machine = KeyTreeView.SelectedItem.Root.FullPath SimpleEditForm.Key = KeyTreeView.SelectedItem.FullPath SimpleEditForm.Id = 0 SimpleEditForm.NewDataType = BINARY_METADATA 'Run it SimpleEditForm.Init SimpleEditForm.Show vbModal, Me 'Refresh DataListView RefreshData Else MsgBox "No key selected", vbOKOnly + vbExclamation, "New Expand String" End If End Sub Private Sub NewMultiStringMenuItem_Click() If Not KeyTreeView.SelectedItem Is Nothing Then 'Set the form parameters MultiEditForm.Machine = KeyTreeView.SelectedItem.Root.FullPath MultiEditForm.Key = KeyTreeView.SelectedItem.FullPath MultiEditForm.Id = 0 MultiEditForm.NewDataType = MULTISZ_METADATA 'Run it MultiEditForm.Init MultiEditForm.Show vbModal, Me 'Refresh DataListView RefreshData Else MsgBox "No key selected", vbOKOnly + vbExclamation, "New Expand String" End If End Sub Private Sub DeleteMenuItem_Click() Dim Response As Long If MainForm.ActiveControl Is KeyTreeView Then Response = MsgBox("Are you sure you want to delete key " & KeyTreeView.SelectedItem.FullPath & "?", _ vbQuestion + vbYesNo, "Delete Key") If Response = vbYes Then MetaUtilObj.DeleteKey KeyTreeView.SelectedItem.FullPath KeyTreeView.Nodes.Remove KeyTreeView.SelectedItem.Index ShowSelectedNode End If ElseIf MainForm.ActiveControl Is DataListView Then Response = MsgBox("Are you sure you want to delete property " & Trim(DataListView.SelectedItem.Text) & "?", _ vbQuestion + vbYesNo, "Delete Property") If Response = vbYes Then MetaUtilObj.DeleteProperty KeyTreeView.SelectedItem.FullPath, CLng(DataListView.SelectedItem.Text) DataListView.Tag = "" ShowSelectedNode End If End If End Sub Private Sub RenameKeyMenuItem_Click() If Not KeyTreeView.SelectedItem Is Nothing Then KeyTreeView.StartLabelEdit Else MsgBox "No key selected", vbOKOnly + vbExclamation, "Rename Key" End If End Sub Private Sub CopyKeyMenuItem_Click() If Not KeyTreeView.SelectedItem Is Nothing Then 'Set the form parameters CopyKeyForm.SourceKey = KeyTreeView.SelectedItem.FullPath 'Run it CopyKeyForm.Init CopyKeyForm.Show vbModal, Me 'Refresh DataListView If CopyKeyForm.Moved Then KeyTreeView.Nodes.Remove KeyTreeView.SelectedItem.Index End If RefreshKeys RefreshData Else MsgBox "No key selected", vbOKOnly + vbExclamation, "Rename Key" End If End Sub Private Sub FindMenuItem_Click() FindForm.Show vbModal, Me End Sub Private Sub FindNextMenuItem_Click() FindWorkingForm.Show vbModal, MainForm End Sub Private Sub CheckSchemaMenuItem_Click() Dim CheckError As Variant Dim NumErrors As Long If Not KeyTreeView.SelectedItem Is Nothing Then NumErrors = 0 'Set the cursor to hourglass AppCursor = vbHourglass MainForm.MousePointer = AppCursor 'Make sure the list is visible If Not ErrorListView.Visible Then ErrorListView.Visible = True ErrorListMenuItem.Checked = True LayoutForm ErrorListView.Refresh End If 'Clear the error list ErrorListView.ListItems.Clear 'Add the errors to the list For Each CheckError In MetaUtilObj.CheckSchema(KeyTreeView.SelectedItem.Root.FullPath) AddErrorToErrorListView CheckError NumErrors = NumErrors + 1 Next 'Resort ErrorListView.Sorted = True 'Restore the cursor AppCursor = vbDefault MainForm.MousePointer = AppCursor If NumErrors = 0 Then MainStatusBar.SimpleText = "No errors found in schema." Else MainStatusBar.SimpleText = Str(NumErrors) & " errors found in schema." End If Else MsgBox "No key selected", vbOKOnly + vbExclamation, "Check Schema" End If End Sub Private Sub CheckKeyMenuItem_Click() Dim CheckError As Variant Dim NumErrors As Long If Not KeyTreeView.SelectedItem Is Nothing Then NumErrors = 0 'Set the cursor to hourglass AppCursor = vbHourglass MainForm.MousePointer = AppCursor 'Make sure the list is visible If Not ErrorListView.Visible Then ErrorListView.Visible = True ErrorListMenuItem.Checked = True LayoutForm End If 'Clear the error list ErrorListView.ListItems.Clear 'Add the errors to the list For Each CheckError In MetaUtilObj.CheckKey(KeyTreeView.SelectedItem.FullPath) AddErrorToErrorListView CheckError NumErrors = NumErrors + 1 Next 'Resort ErrorListView.Sorted = True 'Display the number of errors in the status bar If NumErrors = 0 Then MainStatusBar.SimpleText = "No errors found in " & KeyTreeView.SelectedItem.FullPath & "." Else MainStatusBar.SimpleText = Str(NumErrors) & " errors found in " & KeyTreeView.SelectedItem.FullPath & "." End If 'Restore the cursor AppCursor = vbDefault MainForm.MousePointer = AppCursor Else MsgBox "No key selected", vbOKOnly + vbExclamation, "Check Key" End If End Sub Private Sub CheckAllMenuItem_Click() Dim CheckError As Variant Dim Key As Variant Dim NumErrors As Long NumErrors = 0 'Set the cursor to hourglass AppCursor = vbHourglass MainForm.MousePointer = AppCursor 'Make sure the list is visible If Not ErrorListView.Visible Then ErrorListView.Visible = True ErrorListMenuItem.Checked = True LayoutForm End If 'Clear the error list ErrorListView.ListItems.Clear 'Add the errors to the list For Each Key In MetaUtilObj.EnumAllKeys("") For Each CheckError In MetaUtilObj.CheckKey(Key) AddErrorToErrorListView CheckError NumErrors = NumErrors + 1 Next Next 'Resort ErrorListView.Sorted = True 'Display the number of errors in the status bar If NumErrors = 0 Then MainStatusBar.SimpleText = "No errors found outside of schema." Else MainStatusBar.SimpleText = Str(NumErrors) & " errors found outside of schema." End If 'Restore the cursor AppCursor = vbDefault MainForm.MousePointer = AppCursor End Sub Private Sub CheckOptionsMenuItem_Click() CheckOptionsForm.Init CheckOptionsForm.Show vbModal, Me End Sub Private Sub ErrorListMenuItem_Click() If ErrorListView.Visible Then ErrorListView.Visible = False ErrorListMenuItem.Checked = False Else ErrorListView.Visible = True ErrorListMenuItem.Checked = True End If LayoutForm End Sub Private Sub StatusBarMenuItem_Click() If MainStatusBar.Visible Then Config.StatusBar = False MainStatusBar.Visible = False StatusBarMenuItem.Checked = False Else Config.StatusBar = True MainStatusBar.Visible = True StatusBarMenuItem.Checked = True End If LayoutForm End Sub Private Sub RefreshMenuItem_Click() Dim SelectedControl As Control Dim SelectedProperty As String 'Save the focus Set SelectedControl = MainForm.ActiveControl 'Save the selected property If DataListView.SelectedItem Is Nothing Then SelectedProperty = "" Else SelectedProperty = DataListView.SelectedItem.Text End If 'Reload RefreshKeys RefreshData 'Restore the selected property If SelectedProperty <> "" Then SelectProperty SelectedProperty End If 'Restore original focus If Not SelectedControl Is Nothing Then SelectedControl.SetFocus End If End Sub Private Sub AboutMenuItem_Click() Load AboutForm AboutForm.Show vbModal, Me End Sub Private Sub ExpandKeyMenuItem_Click() If Not KeyTreeView.SelectedItem Is Nothing Then KeyTreeView.SelectedItem.Expanded = True End If End Sub Private Sub KeyNewKeyMenuItem_Click() 'Redirect NewKeyMenuItem_Click End Sub Private Sub KeyNewDwordMenuItem_Click() 'Redirect NewDwordMenuItem_Click End Sub Private Sub KeyNewStringMenuItem_Click() 'Redirect NewStringMenuItem_Click End Sub Private Sub KeyNewBinaryMenuItem_Click() 'Redirect NewBinaryMenuItem_Click End Sub Private Sub KeyNewExpandSzMenuItem_Click() 'Redirect NewExpandStringMenuItem_Click End Sub Private Sub KeyNewMultiSzMenuItem_Click() 'Redirect NewMultiStringMenuItem_Click End Sub Private Sub KeyDeleteMenuItem_Click() 'Redirect DeleteMenuItem_Click End Sub Private Sub KeyRenameMenuItem_Click() 'Redirect RenameKeyMenuItem_Click End Sub Private Sub KeyCopyMenuItem_Click() 'Redirect CopyKeyMenuItem_Click End Sub Private Sub KeyCheckMenuItem_Click() 'Redirect CheckKeyMenuItem_Click End Sub Private Sub DataModifyMenuItem_Click() 'Redirect DataListView_DblClick End Sub Private Sub DataNewDwordMenuItem_Click() 'Redirect NewDwordMenuItem_Click End Sub Private Sub DataNewStringMenuItem_Click() 'Redirect NewStringMenuItem_Click End Sub Private Sub DataNewBinaryMenuItem_Click() 'Redirect NewBinaryMenuItem_Click End Sub Private Sub DataNewExpandSzMenuItem_Click() 'Redirect NewExpandStringMenuItem_Click End Sub Private Sub DataNewMultiSzMenuItem_Click() 'Redirect NewMultiStringMenuItem_Click End Sub Private Sub DataDeleteMenuItem_Click() 'Redirect DeleteMenuItem_Click End Sub
Attribute VB_Name = "Globals" Option Explicit Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long Public Declare Function GetUserDefaultLCID Lib "kernel32" () As Long Public Const LB_SELECTSTRING = &H18C Public g_AuthDatabase As AuthDatabase.Main Public g_ErrorInfo As CErrorInfo Public g_Font As StdFont Public g_intFontColor As Long Public Const FILE_EXT_HHC_C As String = ".HHC" Public Const FILE_EXT_HHK_C As String = ".HHK" Public Const FILE_EXT_XLS_C As String = ".XLS" Public Const FILE_EXT_CHM_C As String = ".CHM" Public Const FILE_EXT_HTM_C As String = ".HTM" Public Const FILE_EXT_HHT_C As String = ".HHT" Public Enum SEARCH_TARGET_E ST_TITLE_E = &H1 ST_URI_E = &H2 ST_DESCRIPTION_E = &H4 ST_COMMENTS_E = &H8 ST_BASE_FILE_E = &H10 ST_TOPICS_WITHOUT_KEYWORDS_E = &H20 ST_NODES_WITHOUT_KEYWORDS_E = &H40 ST_SELF_AUTHORING_GROUP_E = &H80 ST_MARK1_E = &H100 ST_BROKEN_LINK_WINME_E = &H200 ST_BROKEN_LINK_STD_E = &H400 ST_BROKEN_LINK_PRO_E = &H800 ST_BROKEN_LINK_PRO64_E = &H1000 ST_BROKEN_LINK_SRV_E = &H2000 ST_BROKEN_LINK_ADV_E = &H4000 ST_BROKEN_LINK_ADV64_E = &H8000 ST_BROKEN_LINK_DAT_E = &H10000 ST_BROKEN_LINK_DAT64_E = &H20000 End Enum Public LocIncludes() As String Public Sub InitializeLocIncludes() Static blnInitialized As Boolean If (blnInitialized) Then Exit Sub End If blnInitialized = True ReDim LocIncludes(2) LocIncludes(0) = LOC_INCLUDE_ALL_C LocIncludes(1) = LOC_INCLUDE_ENU_C LocIncludes(2) = LOC_INCLUDE_LOC_C End Sub Public Sub PopulateCboWithSKUs( _ ByVal i_cbo As ComboBox, _ Optional ByVal blnListCollectiveSKUs As Boolean = False _ ) Dim intIndex As Long Dim SKUs() As SKU_E If (blnListCollectiveSKUs) Then ReDim SKUs(11) Else ReDim SKUs(8) End If SKUs(0) = SKU_STANDARD_E SKUs(1) = SKU_PROFESSIONAL_E SKUs(2) = SKU_PROFESSIONAL_64_E SKUs(3) = SKU_SERVER_E SKUs(4) = SKU_ADVANCED_SERVER_E SKUs(5) = SKU_DATA_CENTER_SERVER_E SKUs(6) = SKU_ADVANCED_SERVER_64_E SKUs(7) = SKU_DATA_CENTER_SERVER_64_E SKUs(8) = SKU_WINDOWS_MILLENNIUM_E If (blnListCollectiveSKUs) Then SKUs(9) = SKU_DESKTOP_ALL_E SKUs(10) = SKU_SERVER_ALL_E SKUs(11) = SKU_ALL_E End If For intIndex = LBound(SKUs) To UBound(SKUs) i_cbo.AddItem DisplayNameForSKU(SKUs(intIndex)), intIndex i_cbo.ItemData(intIndex) = SKUs(intIndex) Next i_cbo.ListIndex = 0 End Sub Public Sub SetFontInternal(i_frm As Form) SetFont i_frm, g_Font, g_intFontColor End Sub
<filename>Task/Statistics-Basic/VBA/statistics-basic.vba Option Base 1 Private Function mean(s() As Variant) As Double mean = WorksheetFunction.Average(s) End Function Private Function standard_deviation(s() As Variant) As Double standard_deviation = WorksheetFunction.StDev(s) End Function Public Sub basic_statistics() Dim s() As Variant For e = 2 To 4 ReDim s(10 ^ e) For i = 1 To 10 ^ e s(i) = Rnd() Next i Debug.Print "sample size"; UBound(s), "mean"; mean(s), "standard deviation"; standard_deviation(s) t = WorksheetFunction.Frequency(s, [{0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}]) For i = 1 To 10 Debug.Print Format((i - 1) / 10, "0.00"); Debug.Print "-"; Format(i / 10, "0.00"), Debug.Print String$(t(i, 1) / (10 ^ (e - 2)), "X"); Debug.Print Next i Debug.Print Next e End Sub
Rem Rem Tests to test the operation cache Rem Sub DeleteAFile(filespec) Dim fso Set fso = CreateObject("Scripting.FileSystemObject") fso.DeleteFile(filespec) End Sub Rem Rem To really verify correctness, set the AZDBG environment variable to 202ff then Rem set Verbose to 1 and follow the instructions Dim Verbose Verbose = 0 DeleteAFile("abc.xml") Dim pAdminManager Set pAdminManager=CreateObject("AzRoles.AzAdminManager") pAdminManager.Initialize 1, "msxml://abc.xml" pAdminManager.Submit Dim AppHandle1 Set AppHandle1=pAdminManager.CreateApplication("MyApp", 0) AppHandle1.Submit Dim OpHandle1 Set OpHandle1=AppHandle1.CreateOperation("Op1", 0) OpHandle1.Submit OpHandle1.OperationId = 61 OpHandle1.Submit Dim OpHandle2 Set OpHandle2=AppHandle1.CreateOperation("Op2", 0) OpHandle2.Submit OpHandle2.OperationId = 62 OpHandle2.Submit Dim GroupHandleA Set GroupHandleA=AppHandle1.CreateApplicationGroup("GroupWorld", 0) GroupHandleA.Type = 2 GroupHandleA.AddMember "s-1-1-0" GroupHandleA.Submit Dim TaskHandle1 Set TaskHandle1=AppHandle1.CreateTask("TaskOp1", 0) TaskHandle1.AddOperation "Op1" TaskHandle1.BizRuleLanguage = "VBScript" Dim BizRule BizRule = "Dim Amount" & vbCr BizRule = BizRule & "Amount = AccessCheck.GetParameter( " & Chr(34) & "Amount" & Chr(34) & ")" & vbCr BizRule = BizRule & "if Amount < 500 then AccessCheck.BusinessRuleResult = TRUE" TaskHandle1.BizRule = BizRule TaskHandle1.Submit Dim TaskHandle2 Set TaskHandle2=AppHandle1.CreateTask("TaskOp2", 0) TaskHandle2.AddOperation "Op2" TaskHandle2.BizRuleLanguage = "VBScript" BizRule = "Dim Item" & vbCr BizRule = BizRule & "Item = AccessCheck.GetParameter( " & Chr(34) & "ItemNo" & Chr(34) & ")" & vbCr BizRule = BizRule & "if Item < 500 then AccessCheck.BusinessRuleResult = TRUE" TaskHandle2.BizRule = BizRule TaskHandle2.Submit Set ScopeHandle1=AppHandle1.CreateScope("MyScopeQ1", 0) ScopeHandle1.Submit Set RoleHandleA=ScopeHandle1.CreateRole("RoleLdapCanOp1", 0) RoleHandleA.AddAppMember "GroupWorld" RoleHandleA.AddTask "TaskOp1" RoleHandleA.AddTask "TaskOp2" Dim Results Dim Names(50) Dim Values(50) Dim Scopes(5) Dim Operations(10) Names(0) = "ALL_HTTP" Values(0) = "HTTP_CONNECTION:Keep-Alive HTTP_ACCEPT:*/* HTTP_ACCEPT_ENCODING:gzip, deflate HTTP_ACCEPT_LANGUAGE:en-us HTTP_HOST:localhost HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3215; .NET CLR 1.0.3415)" Names(1) = "ALL_RAW" Values(1) = "Connection: Keep-Alive Accept: */* Accept-Encoding: gzip, deflate Accept-Language: en-us Host: localhost User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3215; .NET CLR 1.0.3415)" Names(2) = "Amount" Values(2) = 50 Names(3) = "HTTP_USER_AGENT" Values(3) = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3215; .NET CLR 1.0.3415)" Names(4) = "ItemNo" Values(4) = 53 Names(5) = "V4" Values(5) = 52 Names(6) = "V7" Values(6) = 501 Names(7) = "V8" Values(7) = 500 Scopes(0) = "MyScopeQ1" Operations(0) = 61 Dim CCHandle Set CCHandle=AppHandle1.InitializeClientContextFromToken(0, 0) WScript.Echo "...................." Results=CCHandle.AccessCheck("MyObject", Scopes, Operations, Names, Values ) If Results(0) = 5 Then MsgBox("Broken 1") End if If Verbose Then MsgBox("Check to ensure the operation cache was primed") rem Next one should come from the cache WScript.Echo "...................." Results=CCHandle.AccessCheck("MyObject", Scopes, Operations, Names, Values ) If Results(0) = 5 Then MsgBox("Broken 2") End if If Verbose Then MsgBox("Check to ensure the operation cache was used") rem Avoid the cache if the amount changes WScript.Echo "...................." Values(2) = 51 Results=CCHandle.AccessCheck("MyObject", Scopes, Operations, Names, Values ) If Results(0) = 5 Then MsgBox("Broken 3") End if If Verbose Then MsgBox("Check to ensure the operation cache wasn't used") rem Check to ensure we can add an item to an existing cache WScript.Echo "...................." Operations(0) = 62 Results=CCHandle.AccessCheck("MyObject", Scopes, Operations, Names, Values ) If Results(0) = 5 Then MsgBox("Broken 3a") End if If Verbose Then MsgBox("Check if ItemNo was added to existing cache") rem Ensure that didn't flush the "Amount" Cache for Op1 WScript.Echo "...................." Operations(0) = 61 Results=CCHandle.AccessCheck("MyObject", Scopes, Operations, Names, Values ) If Results(0) = 5 Then MsgBox("Broken 3b") End if If Verbose Then MsgBox("Check if cache used for Op1") rem Test with duplicate operations from the cache WScript.Echo "...................." Operations(0) = 61 Operations(1) = 62 Operations(2) = 61 Results=CCHandle.AccessCheck("MyObject", Scopes, Operations, Names, Values ) If Results(0) = 5 Or Results(1) = 5 Or Results(2) = 5 Then MsgBox("Broken 3c") End if If Verbose Then MsgBox("Check if cache used for Op1/Op2/Op1") rem Test with duplicate operations after flushing the cache TaskHandle2.BizRuleLanguage = "VBScript" WScript.Echo "...................." Operations(0) = 61 Operations(1) = 62 Operations(2) = 61 Results=CCHandle.AccessCheck("MyObject", Scopes, Operations, Names, Values ) If Results(0) = 5 Or Results(1) = 5 Or Results(2) = 5 Then MsgBox("Broken 3c") End if If Verbose Then MsgBox("Check if cache primed for Op1/Op2/Op1") Operations(1) = Empty Operations(2) = Empty rem build a different bizrule to test BizRuleStrings WScript.Echo "...................." BizRule = "AccessCheck.BusinessRuleString =" & Chr(34) & "Bob" & Chr(34) TaskHandle1.BizRule = BizRule TaskHandle1.Submit rem this bizrule string fails and set a bizrule string Results=CCHandle.AccessCheck("MyObject", Scopes, Operations, Names, Values ) If Results(0) = 5 Then If CCHandle.GetBusinessRuleString <> "Bob" Then MsgBox("Error 4: Should be 'Bob':" & CCHandle.GetBusinessRuleString ) End If Else MsgBox("Broken 4") End if If Verbose Then MsgBox("Check that the op cache wasn't used for Op1") rem this one too but it comes from the cache WScript.Echo "...................." Results=CCHandle.AccessCheck("MyObject", Scopes, Operations, Names, Values ) If Results(0) = 5 Then If CCHandle.GetBusinessRuleString <> "Bob" Then MsgBox("Error 4: Should be 'Bob':" & CCHandle.GetBusinessRuleString ) End If Else MsgBox("Broken 5") End if If Verbose Then MsgBox("Check that the op cache was used for Op1")
<gh_stars>10-100 '************************************************************************************* '* '* VDS BVT (Smoke) Test '* '************************************************************************************* 'on Error resume Next 'defining constants dim strNamespace, strHost dim tempVolume 'used to pick a volume for test purposes dim tempPath 'used to create a path on the above volume for mounting dim objReportPostFrag dim objReportPostDeFrag dim fso dim strFragCmd, strValpropCmd tempDirPrefix = "Win32_Directory.Name=""" tempQuote="""" srcFolder = "temp" mountDir = "mnt" strFragCmd = "..\bin\i386\frag.exe -r -f20 " strValPropCmd = "..\bin\i386\valprop.exe 1 " Set fso = CreateObject("Scripting.FileSystemObject") 'Parse Command Line If Wscript.Arguments.Count <> 2 Then Wscript.Echo("Invalid Syntax:") Wscript.Echo("") Wscript.Echo("vds.vbs <host|.> <volumePath>") Wscript.quit End If 'do groundwork to set log file logFileName = "log_vdsBVT.txt" Set fso = CreateObject("Scripting.FileSystemObject") result = fso.FileExists(logFileName) if (result = true) then fso.DeleteFile(logFileName) end if set f = fso.CreateTextFile(logFileName) 'extract command line arguments strHost = wscript.Arguments(0) strNamespace = "winmgmts://" & wscript.Arguments(0) & "/root/cimv2" strVolume = wscript.Arguments(1) strVolume = Replace (strVolume, "\", "\\") 'get the volume strQuery = "select * from Win32_Volume where Name = '" & strVolume & "'" set VolumeSet = GetObject(strNamespace).ExecQuery(strQuery) for each obj in VolumeSet set Volume = obj exit for next Call CheckFileSystem () wscript.echo ("----------------------------------------") Call DriveLetterTest () wscript.echo ("----------------------------------------") if strHost = "." then Call CopyFilesToVolume () wscript.echo ("----------------------------------------") Call FragVolume () wscript.echo ("----------------------------------------") else call WriteLog(" REMOTE - skipping volume fragmentation") end if Call DefragAnalysis () wscript.echo ("----------------------------------------") Call ListFragmentation (objReportPostFrag) wscript.echo ("----------------------------------------") Call DefragVolume () wscript.echo ("----------------------------------------") Call ListFragmentation (objReportPostDeFrag) wscript.echo ("----------------------------------------") Call DoMountingTests () wscript.echo ("----------------------------------------") Call DoDiskServices () wscript.echo ("----------------------------------------") Call RWPropertyChanger () wscript.echo ("----------------------------------------") if strHost = "." then Call ValidateAllProperties() wscript.echo ("----------------------------------------") else call WriteLog(" REMOTE - skipping full property validation") end if call DisplaySummary() '********************************************************** function DriveLetterTest() on error resume next DIM strDriveLetter, strDrivePath DIM objNewSet strDriveLetter = "J:" strDrivePath = strDriveLetter & "\" if (isNull (volume.driveletter) ) then wscript.echo ("Assigning drive letter to volume") volume.DriveLetter = strDriveLetter volume.Put_ rc = ReportIfErr(Err, " FAILED - volume (driveLetter) Put operation failed") Result = volume.AddMountPoint(strDrivePath) rc = ReportIfErr(Err, " FAILED - AddMountPoint") call WriteLog (" addmountpoint error code message = " & MapErrorCode("Win32_Volume", "AddMountPoint", Result)) strQuery = "select * from Win32_Volume where Name = '" & strDrivePath & "\'" set objNewSet = GetObject(strNamespace).ExecQuery(strQuery) rc = ReportIfErr(Err, " FAILED - volume query failed") if objNewSet.Count < 1 then call WriteLog (" FAILED - unable to find volume by newly assigned drive letter : " & strDriveLetter) end if end if Err.Clear set volume = RefreshObject(volume) end function '********************************************************** Function CheckFileSystem () on error resume next 'checking filesystem wscript.echo ("File System Checks") if (IsNull(volume.FileSystem)) then wscript.echo (" volume needs formatting .. now formatting ...") Result = volume.Format() rc = ReportIfErr(Err, "FAILED - volume Format method failed") if (Result = 0 AND rc = 0) then call WriteLog(" success - format") else call WriteLog (" FAILED - format result : " & Result & " : " & MapErrorCode("Win32_Volume", "Format", Result)) call WriteLog(" FAILED - bailing out") wscript.quit end if else call WriteLog (" disk does not require formatting; file system = "&volume.FileSystem) end if end Function '********************************************************** Function CopyFilesToVolume () 'copyfiles to volume wscript.echo("") wscript.echo("Copying Temp Files") fso.CopyFile "c:\windows\system32\wbem\*.*", volume.Name call WriteLog (" success - file copy") end Function '********************************************************** Function FragVolume () wscript.echo ("") wscript.echo ("Fragmentation") wscript.echo(" fragmenting the volume to which the above files were copied to") wscript.echo(" please wait since this can take a while ....") DIM objShell, objExec DIM output Set objShell = CreateObject("WScript.Shell") Set objExec = objShell.Exec(strFragCmd & volume.Name) Do While objExec.Status = 0 'WScript.Echo "Exec.Status: " & objExec.Status WScript.Sleep 100 If Not objExec.StdOut.AtEndOfStream Then objExec.StdOut.ReadAll End If Loop end Function function DefragAnalysis() call WriteLog(" success - fragmentation") wscript.echo(" saving disk analysis report") ResultPostFrag = volume.DefragAnalysis(fRecommended, objReportPostFrag) strMessage = MapErrorCode("Win32_volume", "DefragAnalysis", ResultPostFrag) call WriteLog (" defrag error code message = "& strMessage) end function '********************************************************** Function DefragVolume () on error resume next wscript.echo("") wscript.echo("Degrag Tests and Analysis") wscript.echo(" doing defrag on the volume and saving defrag report") fForce = True ResultOfDefrag = volume.Defrag(fForce, objReportPostDefrag) rc = ReportIfErr(Err, "FAILED - volume Defrag method failed") strMessage = MapErrorCode("Win32_volume", "Defrag", ResultOfDefrag) call WriteLog (" defrag error code message = "& strMessage) end Function '********************************************************** Function DoMountingTests() on error resume next wscript.echo ("") wscript.echo ("Mounting Tests") wscript.echo(" selecting volume with windows on it ... ") Set objSet = GetObject(strNamespace).InstancesOf("Win32_Volume") rc = ReportIfErr(Err, " FAILED - volume enumeration failed") for each obj in objSet result = fso.FolderExists(obj.DriveLetter&"\WINDOWS") if ( result = true ) then set tempVolume = obj wscript.echo (" picking "&obj.DriveLetter) exit for end if next if (result = false) then call WriteLog (" FAILED - Could not attain tempVolume ... bailing out ..") wscript.quit end if result = fso.FolderExists(tempVolume.DriveLetter&"\"&mountDir) if (result = true) then wscript.echo(" folder called "&mountDir&" already exsits") else wscript.echo(" creating directory on tempVolume called "&mountDir) fso.CreateFolder(tempVolume.DriveLetter&"\"&mountDir) result = fso.FolderExists(tempVolume.DriveLetter&"\"&mountDir) if (result = true) then wscript.echo (" folder created") wscript.echo ("") else call WriteLog (" FAILED - folder creation failed .. exiting monting tests ... ") exit Function end if end if tempPath = tempVolume.DriveLetter&"\"&mountDir&"\" tempDir = tempDirPrefix&tempVolume.DriveLetter&"\\"&mountDir&tempQuote wscript.echo (" mounting the volume to the above directory, which is = "&tempPath) result = volume.AddMountPoint(tempPath) rc = ReportIfErr(Err, "FAILED - volume addmountpoint method failed") if (result = 0) then call WriteLog (" success - mounting") wscript.echo("") strMessage = MapErrorCode("Win32_volume", "AddMountPoint", result) call WriteLog (" mounting error code message = "& strMessage) else strMessage = MapErrorCode("Win32_volume", "AddMountPoint", result) call WriteLog (" mounting error code message = "& strMessage) call WriteLog (" FAILED - mounting, exiting mounting tests") exit Function end if wscript.echo(" validating mountpoint exists through WMI query") set objSet = volume.Associators_("Win32_MountPoint") rc = ReportIfErr(Err, " FAILED - volume associators operation failed") if (objSet.Count < 1) then call WriteLog(" FAILED - volume associators for known mountpont failed") end if found = FALSE tempCompareName = LCase(tempVolume.DriveLetter)&"\"&mountDir for each obj in objSet if ( tempCompareName = obj.Name) then call WriteLog (" success - validation through WMI query") found = TRUE exit for end if next if (found = FALSE) then call WriteLog (" FAILED - validation through WMI query") end if wscript.echo(" dismounting V1 with permanent option") bPermanent=TRUE Result = Volume.Dismount(True, bPermanent) rc = ReportIfErr(Err, " FAILED - volume Dismount method failed") wscript.echo (" Volume.Dismount returned: " & Result) strMessage = MapErrorCode("Win32_volume", "Dismount", Result) call WriteLog (" dismounting (with perm options) error code message = "& strMessage) wscript.echo("") 'Call ListAllMountPoints() wscript.echo("") wscript.echo(" deleting mountpoint "&tempDir) Set objSet = GetObject(strNamespace).InstancesOf("Win32_MountPoint") rc = ReportIfErr(Err, " FAILED - mountpoint enumeration failed") for each Mount in objSet if (tempDir = Mount.Directory) then wscript.echo (" calling Mount.Delete_") Mount.Delete_ rc = ReportIfErr(Err, " FAILED - mountpoint delete failed") exit for end if next 'Call ListAllMountPoints() wscript.echo("") Set objSet = GetObject(strNamespace).InstancesOf("Win32_MountPoint") for each Mount in objSet if (tempDir = Mount.Directory) then call WriteLog (" FAILED - mountpoint deletion") exit function end if next call WriteLog(" success - mountpoint deletion") end Function '********************************************************** Function ListAllMountPoints () wscript.echo("") wscript.echo(" listing instances of all mountpoints") Set objSet = GetObject(strNamespace).InstancesOf("Win32_MountPoint") rc = ReportIfErr(Err, " FAILED - mountpoint enumeration failed") for each Mount in objSet WScript.Echo " "&Mount.Volume wscript.echo " "&Mount.Directory next End Function 'end of ListAllMountPoints '********************************************************** Function DoDiskServices () on error resume next wscript.echo("") wscript.echo("Disk Services") wscript.echo (" scheduling autochk") dim astrVol(0) astrvol(0) = volume.DriveLetter Result = volume.ScheduleAutoChk(astrvol) rc = ReportIfErr(Err, " FAILED - volume scheduleautochk method failed") if (Result = 0) then wscript.echo " volume.ScheduleAutoChk returned no error" wscript.echo("") else wscript.echo " volume.ScheduleAutoChk returned error code = " & Result end if strMessage = MapErrorCode("Win32_volume", "ScheduleAutoChk", Result) call WriteLog (" ScheduleAutoChk error code message = "& strMessage) wscript.echo("") wscript.echo (" excluding autochk") Result = volume.ExcludeFromAutoChk(astrvol) rc = ReportIfErr(Err, " FAILED - volume excludefromautochk method failed") if (Result = 0) then wscript.echo " volume.ExcludeAutoChk returned no error" wscript.echo("") else wscript.echo " volume.ExcludeAutoChk returned error code = " & Result end if strMessage = MapErrorCode("Win32_volume", "ExcludeFromAutoChk", Result) call WriteLog (" ExcludeAutoChk error code message = "& strMessage) wscript.echo ("") wscript.echo (" running - fsutil dirty set volume.driveletter") DIM objShell, objExec DIM output if strHost = "." then Set objShell = CreateObject("WScript.Shell") Set objExec = objShell.Exec("fsutil dirty set "&volume.DriveLetter) Do While objExec.Status = 0 'WScript.Echo "Exec.Status: " & objExec.Status WScript.Sleep 100 If Not objExec.StdOut.AtEndOfStream Then wscript.echo (objExec.StdOut.ReadAll) End If Loop set volume = RefreshObject(volume) wscript.echo ("") wscript.echo ("checking if diry bit set (success) or not (failure)") if (volume.DirtyBitSet = FALSE) then call WriteLog(" FAILED - dirty bit not set") else call WriteLog(" success - dirty bit set") end if else call WriteLog(" REMOTE - skipping dirty bit set and test") end if wscript.echo("") wscript.echo (" chkdsk") Result = Volume.Chkdsk(True) rc = ReportIfErr(Err, " FAILED - volume chkdsk method failed") if (Result = 0) then wscript.echo " volume.Chkdsk returned no error" else wscript.echo " volume.Chkdsk returned error code = " & Result end if strMessage = MapErrorCode("Win32_volume", "Chkdsk", Result) call WriteLog (" Chkdsk error code message = "& strMessage) set volume = RefreshObject(volume) wscript.echo ("") wscript.echo (" checking if diry bit set (failure) or not (success)") if (volume.DirtyBitSet = TRUE) then call WriteLog(" FAILED - dirty bit set") else call WriteLog(" success - dirty bit not set") end if End Function 'end of DoDiskServices '********************************************************** Function ListAnalysisReport (objReport) wscript.echo "Analysis Report" wscript.echo "" wscript.echo " Volume size = " & objReport.VolumeSize wscript.echo " Cluster size = " & objReport.ClusterSize wscript.echo " Used space = " & objReport.UsedSpace wscript.echo " Free space = " & objReport.FreeSpace wscript.echo " Percent free space = " & objReport.FreeSpacePercent wscript.echo "" wscript.echo "Volume fragmentation" wscript.echo " Total fragmentation = " & objReport.TotalPercentFragmentation wscript.echo " File fragmentation = " & objReport.FilePercentFragmentation wscript.echo " Free space fragmentation = " & objReport.FreeSpacePercentFragmentation wscript.echo "" wscript.echo "File fragmentation" wscript.echo " Total files = " & objReport.TotalFiles wscript.echo " Average file size = " & objReport.AverageFileSize wscript.echo " Total fragmented files = " & objReport.TotalFragmentedFiles wscript.echo " Total excess fragments = " & objReport.TotalExcessFragments wscript.echo " Average fragments per file = " & objReport.AverageFragmentsPerFile wscript.echo "" wscript.echo "Pagefile fragmentation" wscript.echo " Pagefile size = " & objReport.PagefileSize wscript.echo " Total fragments = " & objReport.TotalPagefileFragments wscript.echo "" wscript.echo "Folder fragmentation" wscript.echo " Total folders = " & objReport.TotalFolders wscript.echo " Fragmented folders = " & objReport.FragmentedFolders wscript.echo " Excess folder fragments = " & objReport.ExcessFolderFragments wscript.echo "" wscript.echo "Master File Table (MFT) fragmentation" wscript.echo " Total MFT size = " & objReport.TotalMFTSize wscript.echo " MFT record count = " & objReport.MFTRecordCount wscript.echo " Percent MFT in use = " & objReport.MFTPercentInUse wscript.echo " Total MFT fragments = " & objReport.TotalMFTFragments wscript.echo "" end Function '********************************************************** Function RWPropertyChanger () on error resume next dim tempDeviceID dim tempDriveLetter newDriveLetter = "M:" newLabel = "myLabel" wscript.echo("") wscript.echo("Read/Write Property Changer") wscript.echo(" current drive letter = "&volume.DriveLetter) tempDeviceID = volume.DeviceID tempDriveLetter = volume.DriveLetter ' assign new drive letter wscript.echo(" putting drive letter as M:") volume.DriveLetter = newDriveLetter volume.Put_ rc = ReportIfErr(Err, " FAILED - volume Put operation failed") '------------------------------------------------------------- wscript.echo (" doing a refresh") set volume = RefreshObject(volume) if (volume.DriveLetter = newDriveLetter) then call WriteLog (" success - drive letter change") wscript.echo (" resetting drive letter to orginal") volume.DriveLetter = tempDriveLetter volume.Put_ rc = ReportIfErr(Err, " FAILED - volume Put operation failed") set volume = RefreshObject(volume) wscript.echo (" drive letter is now set back to = "&volume.DriveLetter) else call WriteLog (" FAILED - drive letter change") end if wscript.echo ("") tempLabel = volume.Label if (isNull (tempLabel) ) then wscript.echo (" changing current label (=<null>) to new label (="&newLabel&")") else wscript.echo (" changing current label (="&volume.Label&") to new label (="&newLabel&")") end if volume.Label = newLabel volume.Put_ rc = ReportIfErr(Err, " FAILED - volume Put operation failed") wscript.echo (" doing a refresh") set volume = RefreshObject(volume) if strComp(volume.Label, newLabel, 1) = 0 then call WriteLog (" success - label reset") wscript.echo (" resetting label to orginal") if (isNull (tempLabel) ) then volume.Label = "" wscript.echo (" setting to null") else volume.Label = tempLabel end if volume.Put_ rc = ReportIfErr(Err, " FAILED - volume Put operation failed") wscript.echo (" label is now set") else call WriteLog (" FAILED - label reset test") end if indexCheck = IsNull(volume.IndexingEnabled) if indexCheck = False then wscript.echo ("") wscript.echo (" toggling indexing enabled property") tempIndexing = volume.IndexingEnabled wscript.echo (" volume.IndexingEnabled = "&volume.IndexingEnabled) wscript.echo (" toggling it") success = false if (tempIndexing = true) then volume.IndexingEnabled = false volume.Put_ rc = ReportIfErr(Err, " FAILED - volume Put operation failed") wscript.echo (" doing a refresh") set volume = RefreshObject(volume) if (volume.IndexingEnabled = false) then success = true end if else volume.IndexingEnabled = true volume.Put_ rc = ReportIfErr(Err, " FAILED - volume Put operation failed") wscript.echo (" doing a refresh") set volume = RefreshObject(volume) if (volume.IndexingEnabled = true) then success = true end if end if if (success = false) then call WriteLog (" FAILED - toggling indexingenabled") else call WriteLog (" success - toggling indexingenabled") wscript.echo (" setting it back to = "&tempIndexing) volume.IndexingEnabled = tempIndexing volume.Put_ rc = ReportIfErr(Err, " FAILED - volume Put operation failed") end if end if end Function '********************************************************** Function ListFragmentation (objReport) wscript.echo "Analysis Report" wscript.echo "" wscript.echo " Volume size = " & objReport.VolumeSize wscript.echo " Cluster size = " & objReport.ClusterSize wscript.echo " Used space = " & objReport.UsedSpace wscript.echo " Free space = " & objReport.FreeSpace wscript.echo " Percent free space = " & objReport.FreeSpacePercent wscript.echo "" wscript.echo "Volume fragmentation" wscript.echo " Total fragmentation = " & objReport.TotalPercentFragmentation wscript.echo " File fragmentation = " & objReport.FilePercentFragmentation wscript.echo " Free space fragmentation = " & objReport.FreeSpacePercentFragmentation wscript.echo "" wscript.echo "File fragmentation" wscript.echo " Total files = " & objReport.TotalFiles wscript.echo " Average file size = " & objReport.AverageFileSize wscript.echo " Total fragmented files = " & objReport.TotalFragmentedFiles wscript.echo " Total excess fragments = " & objReport.TotalExcessFragments wscript.echo " Average fragments per file = " & objReport.AverageFragmentsPerFile wscript.echo "" wscript.echo "Pagefile fragmentation" wscript.echo " Pagefile size = " & objReport.PagefileSize wscript.echo " Total fragments = " & objReport.TotalPagefileFragments wscript.echo "" wscript.echo "Folder fragmentation" wscript.echo " Total folders = " & objReport.TotalFolders wscript.echo " Fragmented folders = " & objReport.FragmentedFolders wscript.echo " Excess folder fragments = " & objReport.ExcessFolderFragments wscript.echo "" wscript.echo "Master File Table (MFT) fragmentation" wscript.echo " Total MFT size = " & objReport.TotalMFTSize wscript.echo " MFT record count = " & objReport.MFTRecordCount wscript.echo " Percent MFT in use = " & objReport.MFTPercentInUse wscript.echo " Total MFT fragments = " & objReport.TotalMFTFragments wscript.echo "" end Function '********************************************************** function DisplaySummary() f.Close Set f = fso.OpenTextFile(logFileName) wscript.echo ("") wscript.echo ("***************************************") wscript.echo (" Test Summary ") wscript.echo ("***************************************") wscript.echo ("") Do While f.AtEndOfStream <> True wscript.echo(f.ReadLine) Loop wscript.echo ("") wscript.echo ("***************************************") wscript.echo (" End of Test Summary ") wscript.echo ("***************************************") wscript.echo ("") f.Close end function '********************************************************** Function MapErrorCode(ByRef strClass, ByRef strMethod, ByRef intCode) set objClass = GetObject(strNamespace).Get(strClass, &h20000) set objMethod = objClass.methods_(strMethod) values = objMethod.qualifiers_("values") if ubound(values) < intCode then call WriteLog( " FAILED - no error message found for " & intCode & " : " & strClass & "." & strMethod) MapErrorCode = "" else MapErrorCode = values(intCode) end if End Function '********************************************************** function ValidateAllProperties() wscript.echo ("") wscript.echo (" running ValProp.exe on all volumes ...") DIM objShell, objExec DIM output Set objShell = CreateObject("WScript.Shell") Set objExec = objShell.Exec(strValpropCmd) Do While objExec.Status = 0 'WScript.Echo "Exec.Status: " & objExec.Status WScript.Sleep 100 If Not objExec.StdOut.AtEndOfStream Then wscript.Echo objExec.StdOut.ReadAll End If Loop end function '********************************************************** Function ReportIfErr(ByRef objErr, ByRef strMessage) ReportIfErr = objErr.Number if objErr.Number <> 0 then strError = strMessage & " : " & Hex(objErr.Number) & " : " & objErr.Description call WriteLog (strError) objErr.Clear end if End Function Sub WriteLog(ByRef strMessage) wscript.echo strMessage f.writeline strMessage End Sub 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
<reponame>LaudateCorpus1/RosettaCodeData Sub copystring() a = "Hello World!" b = a a = "I'm gone" Debug.Print b Debug.Print a End Sub
Public Function Horner(x, ParamArray coeff()) Dim result As Double Dim ncoeff As Integer result = 0 ncoeff = UBound(coeff()) For i = ncoeff To 0 Step -1 result = (result * x) + coeff(i) Next i Horner = result End Function
<reponame>npocmaka/Windows-Server-2003<gh_stars>10-100 Set Args = wscript.Arguments If Args.Count() > 0 Then Drive = Args.item(0) Else Drive = "" End If If Args.Count() > 1 Then Wait = Args.item(1) Else Wait = 0 End If Set obj = GetObject("winmgmts:{impersonationLevel=impersonate}!root/default:SystemRestore") If (obj.Enable(Drive, Wait)) = 0 Then wscript.Echo "Success" Else wscript.Echo "Failed" End If
' L_Welcome_MsgBox_Message_Text = "This script demonstrates how to delete snapin items from scriptable objects." L_Welcome_MsgBox_Title_Text = "Windows Scripting Host Sample" Call Welcome() ' ******************************************************************************** Dim mmc Dim doc Dim snapins Dim frame Dim views Dim view Dim scopenamespace Dim rootnode Dim Nodes Dim scopenode Dim SnapNode Dim ResultItem Dim MySnapin ' Following are snapin exposed objects. Dim ScopeNodeObject Dim ResultItemObject 'get the various objects we'll need Set mmc = wscript.CreateObject("MMC20.Application") Set frame = mmc.Frame Set doc = mmc.Document Set namespace = doc.ScopeNamespace Set rootnode = namespace.GetRoot Set views = doc.views Set view = views(1) Set snapins = doc.snapins mmc.UserControl = true ' Add index snapin & multisel sample snapins.Add "{95AD72F0-44CE-11D0-AE29-00AA004B9986}" ' index snapin snapins.Add "{C3D863FF-5135-4CFC-8C11-E7396DA15D03}" ' Multisel sample ' Get rootnode of the snapin. Set SnapNode1 = namespace.GetChild(rootnode) ' Select the root node of the snapin. view.ActiveScopeNode = SnapNode1 ' Get "System" and delete it (Temp selection and delete). Set SnapNode1 = namespace.GetChild(SnapNode1) view.DeleteScopeNode SnapNode1 ' Select "System" and delete it. view.ActiveScopeNode = SnapNode1 view.DeleteScopeNode ' Now enumerate and select the "Space Station" node in multi-sel sample. Set SnapNode1 = namespace.GetChild(rootnode) ' Get the index snapin root Set SnapNode1 = namespace.GetNext(SnapNode1) ' Get multi-sel root view.ActiveScopeNode = SnapNode1 ' Get the 4th child of multi-sel root node Set SnapNode1 = namespace.GetChild(SnapNode1) Set SnapNode1 = namespace.GetNext(SnapNode1) Set SnapNode1 = namespace.GetNext(SnapNode1) Set SnapNode1 = namespace.GetNext(SnapNode1) view.ActiveScopeNode = SnapNode1 ' Get the child of this "Space Vehicles" node and select it. Set SnapNode1 = namespace.GetChild(SnapNode1) view.ActiveScopeNode = SnapNode1 Set Nodes = view.ListItems view.Select Nodes(1) view.DeleteSelection view.Select Nodes(2) view.Select Nodes(3) ' Multiselection verb computation has bugs will be fixed. ' The CMultiSelection object is not computed as LV doesnt have focus. view.DeleteSelection view.SelectAll ' Multiselection verb computation has bugs will be fixed. ' The CMultiSelection object is not computed as LV doesnt have focus. view.DeleteSelection ' Delete "Console Root", this will fail ' view.DeleteScopeNode rootnode Set mmc = Nothing ' ******************************************************************************** ' * ' * 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
'Read the input file. This assumes that the file is in the same 'directory as the script. Set objfso = CreateObject("Scripting.FileSystemObject") Set objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_ "\input.txt",1) list = "" previous_line = "" l = Len(previous_line) Do Until objfile.AtEndOfStream current_line = objfile.ReadLine If Mid(current_line,l+1,1) <> "" Then list = current_line & vbCrLf previous_line = current_line l = Len(previous_line) ElseIf Mid(current_line,l,1) <> "" And Mid(current_line,(l+1),1) = "" Then list = list & current_line & vbCrLf End If Loop WScript.Echo list objfile.Close Set objfso = Nothing
<filename>net/unimodem/tools/src/frmdcb.frm VERSION 5.00 Object = "{6B7E6392-850A-101B-AFC0-4210102A8DA7}#1.2#0"; "COMCTL32.OCX" Object = "{BDC217C8-ED16-11CD-956C-0000C04E4C0A}#1.1#0"; "TABCTL32.OCX" Begin VB.Form frmDCB BorderStyle = 0 'None Caption = "DCB" ClientHeight = 5730 ClientLeft = 0 ClientTop = 0 ClientWidth = 9480 LinkTopic = "Form1" MDIChild = -1 'True ScaleHeight = 5730 ScaleWidth = 9480 ShowInTaskbar = 0 'False Visible = 0 'False Begin TabDlg.SSTab SSTab1 Height = 5055 Left = 0 TabIndex = 1 TabStop = 0 'False Top = 360 Width = 9405 _ExtentX = 16589 _ExtentY = 8916 _Version = 327681 Tabs = 1 TabsPerRow = 8 TabHeight = 794 TabCaption(0) = "Baudrate" TabPicture(0) = "frmDCB.frx":0000 Tab(0).ControlEnabled= -1 'True Tab(0).Control(0)= "Combo1" Tab(0).Control(0).Enabled= 0 'False Tab(0).ControlCount= 1 Begin VB.ComboBox Combo1 BeginProperty Font Name = "MS Sans Serif" Size = 9.75 Charset = 0 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 360 ItemData = "frmDCB.frx":001C Left = 120 List = "frmDCB.frx":004D TabIndex = 2 Text = "0" Top = 600 Width = 9135 End End Begin VB.TextBox Text1 Height = 285 Left = 0 TabIndex = 0 Text = "HKR,, DCB, 1, 1C,00,00,00, 00,4B,00,00, 15,20,00,00, 00,00, 0a,00, 0a,00, 08, 00, 00, 11, 13, 00, 00, 00" Top = 0 Width = 9495 End Begin ComctlLib.StatusBar StatusBar1 Align = 2 'Align Bottom Height = 300 Left = 0 TabIndex = 3 Top = 5430 Width = 9480 _ExtentX = 16722 _ExtentY = 529 SimpleText = "" _Version = 327682 BeginProperty Panels {0713E89E-850A-101B-AFC0-4210102A8DA7} NumPanels = 3 BeginProperty Panel1 {0713E89F-850A-101B-AFC0-4210102A8DA7} AutoSize = 1 Object.Width = 13070 Object.Tag = "" EndProperty BeginProperty Panel2 {0713E89F-850A-101B-AFC0-4210102A8DA7} Style = 6 AutoSize = 2 Object.Width = 1773 MinWidth = 1764 TextSave = "5/12/98" Object.Tag = "" EndProperty BeginProperty Panel3 {0713E89F-850A-101B-AFC0-4210102A8DA7} Style = 5 AutoSize = 2 Object.Width = 1773 MinWidth = 1764 TextSave = "4:31 PM" Object.Tag = "" EndProperty EndProperty BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} Name = "MS Sans Serif" Size = 8.25 Charset = 0 Weight = 700 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty End End Attribute VB_Name = "frmDCB" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Dim DCBLength, BaudRate, BitMask, Rsvd, XonLim, XoffLim, ByteSize, Parity, _ StopBits, XonChar, XoffChar, ErrorChar, EofChar, EvtChar As String Const Delim As String = "," Const H As String = "&H" Dim Which As Integer Public Sub EditCopy() Text1.SelStart = 0 Text1.SelLength = Len(Text1.Text) Text1.SetFocus Clipboard.Clear Clipboard.SetText Text1.Text End Sub Public Sub EditPaste() GetWord (Clipboard.GetText) PreVert (BaudRate) Combo1.Text = CDec(H & PreNum) Dim strFirst As String strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(BaudRate) Text1.SetFocus End Sub Private Sub Combo1_Click() BaudRate = Combo1.Text If BaudRate = "" Then BaudRate = 0 End If If BaudRate > 100000000 Then BaudRate = 0 Combo1.Text = 0 End If HexCon (BaudRate) BaudRate = HexNum Update Dim strFirst As String strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(BaudRate) Text1.SetFocus End Sub Private Sub Combo1_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then BaudRate = Combo1.Text If BaudRate = "" Then BaudRate = 0 End If If BaudRate > 100000000 Then BaudRate = 0 Combo1.Text = 0 End If HexCon (BaudRate) BaudRate = HexNum Update Dim strFirst As String strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(BaudRate) Text1.SetFocus ElseIf (KeyAscii < 48 Or KeyAscii > 57) And KeyAscii <> 46 Then Beep KeyAscii = 0 End If End Sub Private Sub Combo1_LostFocus() BaudRate = Combo1.Text If BaudRate = "" Then BaudRate = 0 End If If BaudRate > 100000000 Then BaudRate = 0 Combo1.Text = 0 End If HexCon (BaudRate) BaudRate = HexNum Update End Sub Private Sub Update() Text1.Text = "HKR,, DCB, 1, " & DCBLength & ", " & BaudRate & ", " & BitMask & ", " & Rsvd _ & ", " & XonLim & ", " & XoffLim & ", " & ByteSize & ", " & Parity & ", " & StopBits _ & ", " & XonChar & ", " & XoffChar & ", " & ErrorChar & ", " & EofChar & ", " & EvtChar End Sub Private Sub Form_Load() ClearControl StatusBar1.Panels.Item(1).Text = "Specifies the baud rate at which the communications device operates." End Sub Public Sub ClearControl() DCBLength = "1C,00,00,00" BaudRate = "80,25,00,00" Combo1.Text = "9600" BitMask = "15,20,00,00" Rsvd = "00,00" XonLim = "0a,00" XoffLim = "0a,00" ByteSize = "08" Parity = "00" StopBits = "00" XonChar = "11" XoffChar = "13" ErrorChar = "00" EofChar = "00" EvtChar = "00" Update Dim strFirst As String strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(BaudRate) If frmDCB.Visible = False Then frmDCB.Show End If Text1.SetFocus End Sub Private Sub GetWord(strString As String) Dim strSubString As String Dim lStart As Long Dim lStop As Long lStart = 1 lStop = Len(strString) While lStart < lStop And "," <> Mid$(strString, lStart, 1) ' Loop until first 1 found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strString, lStop + 1, 1) And lStop <= Len(strString) ' Loop until next , found lStop = lStop + 1 Wend strSubString = Mid$(strString, lStop + 2) lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first 1 found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until next , found lStop = lStop + 1 Wend strSubString = Mid$(strSubString, lStop + 1) lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend FirstDword1 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (FirstDword1) FirstDword1 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend FirstDword2 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (FirstDword2) FirstDword2 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend FirstDword3 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (FirstDword3) FirstDword3 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend FirstDword4 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (FirstDword4) FirstDword4 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend SecondDword1 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (SecondDword1) SecondDword1 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend SecondDword2 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (SecondDword2) SecondDword2 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend SecondDword3 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (SecondDword3) SecondDword3 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend SecondDword4 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (SecondDword4) SecondDword4 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend ThirdDword1 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (ThirdDword1) ThirdDword1 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend ThirdDword2 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (ThirdDword2) ThirdDword2 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) ' Loop until last , found lStop = lStop + 1 Wend ThirdDword3 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (ThirdDword3) ThirdDword3 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) ' Loop until last , found lStop = lStop + 1 Wend ThirdDword4 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (ThirdDword4) ThirdDword4 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend FirstByte1 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (FirstByte1) FirstByte1 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend FirstByte2 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (FirstByte2) FirstByte2 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend SecondByte1 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (SecondByte1) SecondByte1 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend SecondByte2 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (SecondByte2) SecondByte2 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend ThirdByte1 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (ThirdByte1) ThirdByte1 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend ThirdByte2 = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (ThirdByte2) ThirdByte2 = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend FirstBit = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (FirstBit) FirstBit = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend SecondBit = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (SecondBit) SecondBit = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend ThirdBit = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (ThirdBit) ThirdBit = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend FourthBit = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (FourthBit) FourthBit = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) lStop = lStop + 1 Wend FifthBit = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (FifthBit) FifthBit = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) ' Loop until last , found lStop = lStop + 1 Wend SixthBit = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (SixthBit) SixthBit = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend SeventhBit = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (SeventhBit) SeventhBit = CleanNum lStart = 1 lStop = Len(strSubString) While lStart < lStop And "," <> Mid$(strSubString, lStart, 1) ' Loop until first , found lStart = lStart + 1 Wend lStop = lStart While "," <> Mid$(strSubString, lStop + 1, 1) And lStop <= Len(strSubString) ' Loop until last , found lStop = lStop + 1 Wend EighthBit = Mid$(strSubString, lStart + 1, lStop - 1) ' Grab word found between ,'s strSubString = Mid$(strSubString, lStop + 1) Clean (EighthBit) EighthBit = CleanNum DCBLength = FirstDword1 & Delim & FirstDword2 & Delim & FirstDword3 & Delim & FirstDword4 BaudRate = SecondDword1 & Delim & SecondDword2 & Delim & SecondDword3 & Delim & SecondDword4 BitMask = ThirdDword1 & Delim & ThirdDword2 & Delim & ThirdDword3 & Delim & ThirdDword4 Rsvd = FirstByte1 & Delim & FirstByte2 XonLim = SecondByte1 & Delim & SecondByte2 XoffLim = ThirdByte1 & Delim & ThirdByte2 ByteSize = FirstBit Parity = SecondBit StopBits = ThirdBit XonChar = FourthBit XoffChar = FifthBit ErrorChar = SixthBit EofChar = SeventhBit EvtChar = EighthBit Update End Sub Private Sub Form_Resize() Text1.Width = frmDCB.Width SSTab1.Width = frmDCB.Width - 75 SSTab1.Height = frmDCB.Height - 675 Combo1.Width = SSTab1.Width - 370 End Sub Private Sub SSTab1_Click(PreviousTab As Integer) Dim CurrentTab As Integer Dim strFirst As Integer CurrentTab = SSTab1.Tab + 1 Select Case CurrentTab Case "1" strFirst = Len("HKR,, DCB, 1, ") Text1.SelStart = strFirst Text1.SelLength = Len(DCBLength) StatusBar1.Panels.Item(1).Text = "Specifies the length, in bytes, of the DCB structure." Case "2" strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(BaudRate) StatusBar1.Panels.Item(1).Text = "Specifies the baud rate at which the communications device operates." Case "3" strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", " & BaudRate & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(BitMask) StatusBar1.Panels.Item(1).Text = "" Case "4" strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", " & BaudRate & ", " & BitMask & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(Rsvd) StatusBar1.Panels.Item(1).Text = "??? Not used; must be set to zero. ???" Case "5" strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", " & BaudRate & ", " & BitMask & ", " & Rsvd & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(XonLim) StatusBar1.Panels.Item(1).Text = "Specifies the minimum number of bytes allowed in the input buffer before the XON character is sent." Case "6" strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", " & BaudRate & ", " & BitMask & ", " & Rsvd _ & ", " & XonLim & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(XoffLim) StatusBar1.Panels.Item(1).Text = "Specifies the maximum number of bytes allowed in the input buffer before the XOFF character is sent." Case "7" strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", " & BaudRate & ", " & BitMask & ", " & Rsvd _ & ", " & XonLim & ", " & XoffLim & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(ByteSize) StatusBar1.Panels.Item(1).Text = "Specifies the number of bits in the bytes transmitted and received." Case "8" strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", " & BaudRate & ", " & BitMask & ", " & Rsvd _ & ", " & XonLim & ", " & XoffLim & ", " & ByteSize & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(Parity) StatusBar1.Panels.Item(1).Text = "Specifies the parity scheme to be used." Case "9" strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", " & BaudRate & ", " & BitMask & ", " & Rsvd _ & ", " & XonLim & ", " & XoffLim & ", " & ByteSize & ", " & Parity & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(StopBits) StatusBar1.Panels.Item(1).Text = "Specifies the number of stop bits to be used." Case "10" strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", " & BaudRate & ", " & BitMask & ", " & Rsvd _ & ", " & XonLim & ", " & XoffLim & ", " & ByteSize & ", " & Parity & ", " & StopBits & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(XonChar) StatusBar1.Panels.Item(1).Text = "Specifies the value of the XON character for both transmission and reception." Case "11" strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", " & BaudRate & ", " & BitMask & ", " & Rsvd _ & ", " & XonLim & ", " & XoffLim & ", " & ByteSize & ", " & Parity & ", " & StopBits _ & ", " & XonChar & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(XoffChar) StatusBar1.Panels.Item(1).Text = "Specifies the value of the XOFF character for both transmission and reception." Case "12" strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", " & BaudRate & ", " & BitMask & ", " & Rsvd _ & ", " & XonLim & ", " & XoffLim & ", " & ByteSize & ", " & Parity & ", " & StopBits _ & ", " & XonChar & ", " & XoffChar & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(ErrorChar) StatusBar1.Panels.Item(1).Text = "Specifies the value of the character used to replace bytes received with a parity error." Case "13" strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", " & BaudRate & ", " & BitMask & ", " & Rsvd _ & ", " & XonLim & ", " & XoffLim & ", " & ByteSize & ", " & Parity & ", " & StopBits _ & ", " & XonChar & ", " & XoffChar & ", " & ErrorChar & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(EofChar) StatusBar1.Panels.Item(1).Text = "Specifies the value of the character used to signal the end of data." Case "14" strFirst = Len("HKR,, DCB, 1, " & DCBLength & ", " & BaudRate & ", " & BitMask & ", " & Rsvd _ & ", " & XonLim & ", " & XoffLim & ", " & ByteSize & ", " & Parity & ", " & StopBits _ & ", " & XonChar & ", " & XoffChar & ", " & ErrorChar & ", " & EofChar & ", ") Text1.SelStart = strFirst Text1.SelLength = Len(EvtChar) StatusBar1.Panels.Item(1).Text = "Specifies the value of the character used to signal an event." End Select If frmDCB.Visible = False Then frmDCB.Show End If Text1.SetFocus End Sub Private Sub Text1_Click() Dim Start As Integer Start = Text1.SelStart If 25 < Start And Start < 39 Then If Which = 1 Then Exit Sub Text1.SelStart = 27 Text1.SelLength = 11 Text1.SetFocus Which = 1 Else Which = 0 End If 'MsgBox Start End Sub Private Sub Text1_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then Clipboard.Clear Clipboard.SetText Text1.Text EditPaste End If End Sub
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() ' Create a new object path object Dim objectPath As SWbemObjectPath Dim key As SWbemNamedValue Set objectPath = CreateObject("WbemScripting.SWbemObjectPath") ' The Bar class has a reference key and a 64-bit numeric key objectPath.Path = "root/default:Bar.Ref={//foo/root:A=1},Num=9999999999999" ' Display the first key Set key = objectPath.Keys("Ref") ' Should display as Ref, //foo/root:A=1, 102 ' where 102 = wbemCimtypeReference Debug.Print key.Name, key.Value, key.CIMType ' Display the second key Set key = objectPath.Keys("Num") ' Should display as Num, 9999999999999, 21 ' where 102 = wbemCimtypeUint64 Debug.Print key.Name, key.Value, key.CIMType ' Create a new object path object Dim objectPath2 As SWbemObjectPath Set objectPath2 = CreateObject("WbemScripting.SWbemObjectPath") ' We will create the path ' root/default:Bar.Ref={//foo/root:A=1},Num=9999999999999 objectPath2.Namespace = "root/default" ' Add the first key objectPath2.Keys.AddAs "Ref", "//foo/root:A=1", wbemCimtypeReference ' Add the second key - have to add as string objectPath2.Keys.AddAs "Num", "9999999999999", wbemCimtypeUint64 Debug.Print objectPath2.Path End Sub
Function multifactorial(n,d) If n = 0 Then multifactorial = 1 Else For i = n To 1 Step -d If i = n Then multifactorial = n Else multifactorial = multifactorial * i End If Next End If End Function For j = 1 To 5 WScript.StdOut.Write "Degree " & j & ": " For k = 1 To 10 If k = 10 Then WScript.StdOut.Write multifactorial(k,j) Else WScript.StdOut.Write multifactorial(k,j) & " " End If Next WScript.StdOut.WriteLine Next
<reponame>LaudateCorpus1/RosettaCodeData<gh_stars>1-10 Dim a As Integer Dim b As Boolean Debug.Print b a = b Debug.Print a b = True Debug.Print b a = b Debug.Print a
Option Explicit Sub Main() print2dArray getSpiralArray(5) End Sub Function getSpiralArray(dimension As Integer) As Integer() ReDim spiralArray(dimension - 1, dimension - 1) As Integer Dim numConcentricSquares As Integer numConcentricSquares = dimension \ 2 If (dimension Mod 2) Then numConcentricSquares = numConcentricSquares + 1 Dim j As Integer, sideLen As Integer, currNum As Integer sideLen = dimension Dim i As Integer For i = 0 To numConcentricSquares - 1 ' do top side For j = 0 To sideLen - 1 spiralArray(i, i + j) = currNum currNum = currNum + 1 Next ' do right side For j = 1 To sideLen - 1 spiralArray(i + j, dimension - 1 - i) = currNum currNum = currNum + 1 Next ' do bottom side For j = sideLen - 2 To 0 Step -1 spiralArray(dimension - 1 - i, i + j) = currNum currNum = currNum + 1 Next ' do left side For j = sideLen - 2 To 1 Step -1 spiralArray(i + j, i) = currNum currNum = currNum + 1 Next sideLen = sideLen - 2 Next getSpiralArray = spiralArray() End Function Sub print2dArray(arr() As Integer) Dim row As Integer, col As Integer For row = 0 To UBound(arr, 1) For col = 0 To UBound(arr, 2) - 1 Debug.Print arr(row, col), Next Debug.Print arr(row, UBound(arr, 2)) Next End Sub
<filename>inetsrv/iis/utils/metautil/metaedit/findwrk.frm<gh_stars>10-100 VERSION 5.00 Begin VB.Form FindWorkingForm BorderStyle = 3 'Fixed Dialog Caption = "Find" ClientHeight = 1305 ClientLeft = 45 ClientTop = 330 ClientWidth = 3330 Icon = "FindWrk.frx":0000 LinkTopic = "Form1" MaxButton = 0 'False MinButton = 0 'False ScaleHeight = 1305 ScaleWidth = 3330 ShowInTaskbar = 0 'False StartUpPosition = 3 'Windows Default Begin VB.CommandButton CancelButton Caption = "Cancel" Default = -1 'True Height = 345 Left = 1920 TabIndex = 1 Top = 840 Width = 1260 End Begin VB.PictureBox picIcon AutoSize = -1 'True BorderStyle = 0 'None ClipControls = 0 'False Height = 480 Left = 240 Picture = "FindWrk.frx":0442 ScaleHeight = 337.12 ScaleMode = 0 'User ScaleWidth = 337.12 TabIndex = 0 Top = 240 Width = 480 End Begin VB.Label Label1 Caption = "Searching the Metabase..." Height = 255 Left = 960 TabIndex = 2 Top = 360 Width = 2175 End End Attribute VB_Name = "FindWorkingForm" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Option Explicit Option Compare Text DefInt A-Z 'Metabase globals Const ALL_METADATA = 0 Const DWORD_METADATA = 1 Const STRING_METADATA = 2 Const BINARY_METADATA = 3 Const EXPANDSZ_METADATA = 4 Const MULTISZ_METADATA = 5 'Form Parameters Public Target As String Public SearchKeys As Boolean Public SearchNames As Boolean Public SearchData As Boolean Public WholeMatch As Boolean Public NewSearch As Boolean Dim StopSearch As Boolean Dim LastKey As String Dim LastProperty As Long Private Sub Form_Load() Target = "" SearchKeys = True SearchNames = True SearchData = True WholeMatch = True NewSearch = False StopSearch = False LastKey = "" LastProperty = 0 End Sub Private Sub Form_Activate() Dim Key As Variant Dim Property As Object Dim FoundLastKey As Boolean Dim FoundLastProperty As Boolean Dim i As Long Dim Data As Variant StopSearch = False If NewSearch Then NewSearch = False LastKey = "" LastProperty = 0 For Each Key In MainForm.MetaUtilObj.EnumAllKeys("") LastKey = Key 'Check key name If SearchKeys And (InStr(GetChildFromFull(LastKey), Target) <> 0) Then 'Found Me.Hide MainForm.SelectKey LastKey Exit Sub End If 'Dont block DoEvents If StopSearch Then Exit Sub If SearchNames Or SearchData Then For Each Property In MainForm.MetaUtilObj.EnumProperties(Key) LastProperty = Property.Id 'Check property name If SearchKeys And (InStr(CStr(Property.Name), Target) <> 0) Then 'Found Me.Hide MainForm.SelectKey LastKey MainForm.SelectProperty String(10 - Len(Str(Property.Id)), " ") + Str(Property.Id) Exit Sub End If 'Check property data If SearchData Then If SearchPropertyData(Property) Then 'Found Me.Hide MainForm.SelectKey LastKey MainForm.SelectProperty String(10 - Len(Str(Property.Id)), " ") + Str(Property.Id) Exit Sub End If End If 'Dont block DoEvents If StopSearch Then Exit Sub Next 'Property LastProperty = 0 End If 'SearchNames Or SearchData Next 'Key Else 'Resume old search If LastKey <> "" Then FoundLastKey = False FoundLastProperty = False For Each Key In MainForm.MetaUtilObj.EnumAllKeys("") If (Not FoundLastKey) And (CStr(Key) = LastKey) Then FoundLastKey = True End If If FoundLastKey Then 'Check key name if we didn't just catch up If CStr(Key) <> LastKey Then LastKey = Key 'Check key name If SearchKeys And (InStr(GetChildFromFull(LastKey), Target) <> 0) Then 'Found Me.Hide MainForm.SelectKey LastKey Exit Sub End If End If 'Dont block DoEvents If StopSearch Then Exit Sub If SearchNames Or SearchData Then For Each Property In MainForm.MetaUtilObj.EnumProperties(Key) If ((Not FoundLastProperty) And (Property.Id = LastProperty)) Or _ (LastProperty = 0) Then FoundLastProperty = True End If If FoundLastProperty Then 'Check data if we didn't just catch up If Property.Id <> LastProperty Then LastProperty = Property.Id 'Check property name If SearchKeys And (InStr(CStr(Property.Name), Target) <> 0) Then 'Found Me.Hide MainForm.SelectKey LastKey MainForm.SelectProperty String(10 - Len(Str(Property.Id)), " ") + Str(Property.Id) Exit Sub End If 'Check property data If SearchData Then If SearchPropertyData(Property) Then 'Found Me.Hide MainForm.SelectKey LastKey MainForm.SelectProperty String(10 - Len(Str(Property.Id)), " ") + Str(Property.Id) Exit Sub End If End If End If 'Dont block DoEvents If StopSearch Then Exit Sub End If 'FoundLastProperty Next 'Property LastProperty = 0 End If 'SearchNames Or SearchData End If 'FoundLastKey Next 'Key End If 'LastKey <> "" End If 'NewSearch Me.Hide MsgBox "Done searching.", vbInformation + vbOKOnly, "Find Next" End Sub Private Sub CancelButton_Click() StopSearch = True Me.Hide End Sub Private Function SearchPropertyData(ByRef Property As Object) As Boolean Dim Found As Boolean Dim DataType As Long Dim Data As Variant Dim i As Long Found = False DataType = Property.DataType Data = Property.Data If DataType = DWORD_METADATA Then If Target = Str(Data) Then Found = True End If ElseIf DataType = STRING_METADATA Or _ DataType = EXPANDSZ_METADATA Then If InStr(CStr(Data), Target) <> 0 Then Found = True End If ElseIf DataType = BINARY_METADATA Then 'Not supported ElseIf DataType = MULTISZ_METADATA Then If IsArray(Data) Then For i = LBound(Data) To UBound(Data) If InStr(CStr(Data(i)), Target) <> 0 Then Found = True End If Next End If End If SearchPropertyData = Found End Function Private Sub picIcon_Click() If Target = "Fnord" Then MsgBox "There are no Easter eggs in this program.", vbExclamation + vbOKOnly, "Fnord!" End Sub Private Function GetChildFromFull(FullPath As String) As String Dim Child As String Dim Ch As String Dim i As Long 'Find the first slash i = Len(FullPath) Ch = CStr(Mid(FullPath, i, 1)) Do While (i > 0) And (Ch <> "/") And (Ch <> "\") i = i - 1 If (i > 0) Then Ch = CStr(Mid(FullPath, i, 1)) Loop Child = Right(FullPath, Len(FullPath) - i) GetChildFromFull = Child End Function
<filename>admin/pchealth/authtools/prodtools/common/filesanddirs.bas Attribute VB_Name = "FilesAndDirs" Option Explicit Private Declare Function MultiByteToWideChar _ Lib "kernel32" ( _ ByVal CodePage As Long, _ ByVal dwFlags As Long, _ ByVal lpMultiByteStr As String, _ ByVal cchMultiByte As Long, _ ByVal lpWideCharStr As Long, _ ByVal cchWideChar As Long _ ) As Long Public Function FileNameFromPath( _ ByVal i_strPath As String _ ) As String FileNameFromPath = Mid$(i_strPath, InStrRev(i_strPath, "\") + 1) End Function Public Function DirNameFromPath( _ ByVal i_strPath As String _ ) As String Dim intPos As Long DirNameFromPath = "" intPos = InStrRev(i_strPath, "\") If (intPos > 0) Then DirNameFromPath = Mid$(i_strPath, 1, intPos) End If End Function Public Function FileNameFromURI( _ ByVal i_strURI As String _ ) As String Dim intPos As Long intPos = InStrRev(i_strURI, "/") If (intPos = 0) Then ' Sometimes the authors write the URI like "distrib.chm::\distrib.hhc" ' instead of "distrib.chm::/distrib.hhc" intPos = InStrRev(i_strURI, "\") End If FileNameFromURI = Mid$(i_strURI, intPos + 1) End Function Public Function FileExtension( _ ByVal i_strFileName As String _ ) As String Dim strFileName As String Dim intStart As Long strFileName = FileNameFromPath(i_strFileName) intStart = InStrRev(strFileName, ".") If (intStart <> 0) Then FileExtension = Mid$(strFileName, intStart) End If End Function Public Function FileNameWithoutExtension( _ ByVal i_strFileName As String _ ) As String Dim strFileName As String Dim intStart As Long strFileName = FileNameFromPath(i_strFileName) intStart = InStrRev(strFileName, ".") If (intStart <> 0) Then FileNameWithoutExtension = Mid$(strFileName, 1, intStart - 1) Else FileNameWithoutExtension = strFileName End If End Function Public Function FileRead( _ ByVal i_strPath As String, _ Optional ByVal i_intCodePage As Long = 0 _ ) As String Dim strMultiByte As String Dim strWideChar As String Dim intNumChars As Long On Error GoTo LEnd FileRead = "" Dim FSO As Scripting.FileSystemObject Dim TStream As Scripting.TextStream Set FSO = New Scripting.FileSystemObject Set TStream = FSO.OpenTextFile(i_strPath) If (i_intCodePage = 0) Then FileRead = TStream.ReadAll Else strMultiByte = TStream.ReadAll intNumChars = MultiByteToWideChar(i_intCodePage, 0, strMultiByte, Len(strMultiByte), _ StrPtr(strWideChar), 0) strWideChar = Space$(intNumChars) intNumChars = MultiByteToWideChar(i_intCodePage, 0, strMultiByte, Len(strMultiByte), _ StrPtr(strWideChar), Len(strWideChar)) FileRead = Left$(strWideChar, intNumChars) End If LEnd: End Function Public Function FileExists( _ ByVal i_strPath As String _ ) As Boolean On Error GoTo LErrorHandler If (Dir(i_strPath) <> "") Then FileExists = True Else FileExists = False End If Exit Function LErrorHandler: FileExists = False End Function Public Function FileWrite( _ ByVal i_strPath As String, _ ByVal i_strContents As String, _ Optional ByVal i_blnAppend As Boolean = False, _ Optional ByVal i_blnUnicode As Boolean = False _ ) As Boolean On Error Resume Next Dim intError As Long Dim intIOMode As Long Err.Clear FileWrite = False Dim FSO As Scripting.FileSystemObject Dim TStream As Scripting.TextStream Set FSO = New Scripting.FileSystemObject If (i_blnAppend) Then intIOMode = IOMode.ForAppending Else intIOMode = IOMode.ForWriting End If Set TStream = FSO.OpenTextFile(i_strPath, intIOMode, , TristateUseDefault) intError = Err.Number Err.Clear If (intError = 53) Then ' File not found Set TStream = FSO.CreateTextFile(i_strPath, True, i_blnUnicode) ElseIf (intError <> 0) Then GoTo LEnd End If TStream.Write i_strContents intError = Err.Number Err.Clear If (intError <> 0) Then GoTo LEnd End If FileWrite = True LEnd: End Function Public Function TempFile() As String Dim FSO As Scripting.FileSystemObject Set FSO = New Scripting.FileSystemObject TempFile = Environ$("TEMP") & "\" & FSO.GetTempName End Function
'prints a WScript.StdOut.WriteLine Chr(97) 'prints 97 WScript.StdOut.WriteLine Asc("a")
<reponame>hanun2999/Altium-Schematic-Parser '-------------------------------------------------------------------------------------- ' $Summary PCB Layer Sets - Demonstrate the use of macros in changing PCB Layers ' Copyright (c) 2004 by Altium Limited ' ' Enable Basic script For DXP 2004 SP2 '-------------------------------------------------------------------------------------- '-------------------------------------------------------------------------------------- Sub Main LayerSet = "" R = RunDialog(LayerSet) If R <> 0 Then Select Case LayerSet Case 0 TopLayers Case 1 BottomLayers Case 2 MechanicalLayers End Select End IF End Sub '-------------------------------------------------------------------------------------- '-------------------------------------------------------------------------------------- Function RunDialog(ByRef Scheme As String) As String ' Dialog box definition Dim ColorListBoxSource$ (3) ColorListBoxSource$ (0) = "Top Layers" ColorListBoxSource$ (1) = "Bottom Layers" ColorListBoxSource$ (2) = "Mechanical Layers" Begin Dialog DLGTYPE 100,100, 168, 65, "Please Choose a Layer Set" Text 5,13,41,10, "" OKButton 120,8,37,12 CancelButton 120,24,37,12 ListBox 8,4,105,55, ColorListboxSource$(), .ColorListBox End Dialog Dim DlgBox As DlgType Dim Result As String Result = Dialog(DlgBox) ' call the dialog box Scheme = DlgBox.ColorListBox RunDialog = Result End Function '-------------------------------------------------------------------------------------- '-------------------------------------------------------------------------------------- Sub TopLayers Call ResetParameters Call AddStringParameter ("TopSignal" , "True" ) Call AddStringParameter ("Mid1" , "False" ) Call AddStringParameter ("Mid2" , "False" ) Call AddStringParameter ("Mid3" , "False" ) Call AddStringParameter ("Mid4" , "False" ) Call AddStringParameter ("Mid5" , "False" ) Call AddStringParameter ("Mid6" , "False" ) Call AddStringParameter ("Mid7" , "False" ) Call AddStringParameter ("Mid8" , "False" ) Call AddStringParameter ("Mid9" , "False" ) Call AddStringParameter ("Mid10" , "False" ) Call AddStringParameter ("Mid11" , "False" ) Call AddStringParameter ("Mid12" , "False" ) Call AddStringParameter ("Mid13" , "False" ) Call AddStringParameter ("Mid14" , "False" ) Call AddStringParameter ("Mid15" , "False" ) Call AddStringParameter ("Mid16" , "False" ) Call AddStringParameter ("Mid17" , "False" ) Call AddStringParameter ("Mid18" , "False" ) Call AddStringParameter ("Mid19" , "False" ) Call AddStringParameter ("Mid20" , "False" ) Call AddStringParameter ("Mid21" , "False" ) Call AddStringParameter ("Mid22" , "False" ) Call AddStringParameter ("Mid23" , "False" ) Call AddStringParameter ("Mid24" , "False" ) Call AddStringParameter ("Mid25" , "False" ) Call AddStringParameter ("Mid26" , "False" ) Call AddStringParameter ("Mid27" , "False" ) Call AddStringParameter ("Mid28" , "False" ) Call AddStringParameter ("Mid29" , "False" ) Call AddStringParameter ("Mid30" , "False" ) Call AddStringParameter ("BottomSignal" , "False" ) Call AddStringParameter ("TopOverlay" , "True" ) Call AddStringParameter ("BottomOverlay" , "False" ) Call AddStringParameter ("TopPaste" , "True" ) Call AddStringParameter ("BottomPaste" , "False" ) Call AddStringParameter ("TopSolder" , "True" ) Call AddStringParameter ("BottomSolder" , "False" ) Call AddStringParameter ("Plane1" , "False" ) Call AddStringParameter ("Plane2" , "False" ) Call AddStringParameter ("Plane3" , "False" ) Call AddStringParameter ("Plane4" , "False" ) Call AddStringParameter ("Plane5" , "False" ) Call AddStringParameter ("Plane6" , "False" ) Call AddStringParameter ("Plane7" , "False" ) Call AddStringParameter ("Plane8" , "False" ) Call AddStringParameter ("Plane9" , "False" ) Call AddStringParameter ("Plane10" , "False" ) Call AddStringParameter ("Plane11" , "False" ) Call AddStringParameter ("Plane12" , "False" ) Call AddStringParameter ("Plane13" , "False" ) Call AddStringParameter ("Plane14" , "False" ) Call AddStringParameter ("Plane15" , "False" ) Call AddStringParameter ("Plane16" , "False" ) Call AddStringParameter ("DrillGuide" , "False" ) Call AddStringParameter ("KeepOut" , "False" ) Call AddStringParameter ("Mechanical1" , "False" ) Call AddStringParameter ("Mechanical2" , "False" ) Call AddStringParameter ("Mechanical3" , "False" ) Call AddStringParameter ("Mechanical4" , "False" ) Call AddStringParameter ("Mechanical5" , "False" ) Call AddStringParameter ("Mechanical6" , "False" ) Call AddStringParameter ("Mechanical7" , "False" ) Call AddStringParameter ("Mechanical8" , "False" ) Call AddStringParameter ("Mechanical9" , "False" ) Call AddStringParameter ("Mechanical10" , "False" ) Call AddStringParameter ("Mechanical11" , "False" ) Call AddStringParameter ("Mechanical12" , "False" ) Call AddStringParameter ("Mechanical13" , "False" ) Call AddStringParameter ("Mechanical14" , "False" ) Call AddStringParameter ("Mechanical15" , "False" ) Call AddStringParameter ("Mechanical16" , "False" ) Call AddStringParameter ("DrillDrawing" , "False" ) Call AddStringParameter ("MultiLayer" , "True" ) Call RunProcess ("Pcb:DocumentPreferences") End Sub '-------------------------------------------------------------------------------------- '-------------------------------------------------------------------------------------- Sub BottomLayers Call ResetParameters Call AddStringParameter ("TopSignal" , "False" ) Call AddStringParameter ("Mid1" , "False" ) Call AddStringParameter ("Mid2" , "False" ) Call AddStringParameter ("Mid3" , "False" ) Call AddStringParameter ("Mid4" , "False" ) Call AddStringParameter ("Mid5" , "False" ) Call AddStringParameter ("Mid6" , "False" ) Call AddStringParameter ("Mid7" , "False" ) Call AddStringParameter ("Mid8" , "False" ) Call AddStringParameter ("Mid9" , "False" ) Call AddStringParameter ("Mid10" , "False" ) Call AddStringParameter ("Mid11" , "False" ) Call AddStringParameter ("Mid12" , "False" ) Call AddStringParameter ("Mid13" , "False" ) Call AddStringParameter ("Mid14" , "False" ) Call AddStringParameter ("Mid15" , "False" ) Call AddStringParameter ("Mid16" , "False" ) Call AddStringParameter ("Mid17" , "False" ) Call AddStringParameter ("Mid18" , "False" ) Call AddStringParameter ("Mid19" , "False" ) Call AddStringParameter ("Mid20" , "False" ) Call AddStringParameter ("Mid21" , "False" ) Call AddStringParameter ("Mid22" , "False" ) Call AddStringParameter ("Mid23" , "False" ) Call AddStringParameter ("Mid24" , "False" ) Call AddStringParameter ("Mid25" , "False" ) Call AddStringParameter ("Mid26" , "False" ) Call AddStringParameter ("Mid27" , "False" ) Call AddStringParameter ("Mid28" , "False" ) Call AddStringParameter ("Mid29" , "False" ) Call AddStringParameter ("Mid30" , "False" ) Call AddStringParameter ("BottomSignal" , "True" ) Call AddStringParameter ("TopOverlay" , "False" ) Call AddStringParameter ("BottomOverlay" , "True" ) Call AddStringParameter ("TopPaste" , "False" ) Call AddStringParameter ("BottomPaste" , "True" ) Call AddStringParameter ("TopSolder" , "False" ) Call AddStringParameter ("BottomSolder" , "True" ) Call AddStringParameter ("Plane1" , "False" ) Call AddStringParameter ("Plane2" , "False" ) Call AddStringParameter ("Plane3" , "False" ) Call AddStringParameter ("Plane4" , "False" ) Call AddStringParameter ("Plane5" , "False" ) Call AddStringParameter ("Plane6" , "False" ) Call AddStringParameter ("Plane7" , "False" ) Call AddStringParameter ("Plane8" , "False" ) Call AddStringParameter ("Plane9" , "False" ) Call AddStringParameter ("Plane10" , "False" ) Call AddStringParameter ("Plane11" , "False" ) Call AddStringParameter ("Plane12" , "False" ) Call AddStringParameter ("Plane13" , "False" ) Call AddStringParameter ("Plane14" , "False" ) Call AddStringParameter ("Plane15" , "False" ) Call AddStringParameter ("Plane16" , "False" ) Call AddStringParameter ("DrillGuide" , "False" ) Call AddStringParameter ("KeepOut" , "False" ) Call AddStringParameter ("Mechanical1" , "False" ) Call AddStringParameter ("Mechanical2" , "False" ) Call AddStringParameter ("Mechanical3" , "False" ) Call AddStringParameter ("Mechanical4" , "False" ) Call AddStringParameter ("Mechanical5" , "False" ) Call AddStringParameter ("Mechanical6" , "False" ) Call AddStringParameter ("Mechanical7" , "False" ) Call AddStringParameter ("Mechanical8" , "False" ) Call AddStringParameter ("Mechanical9" , "False" ) Call AddStringParameter ("Mechanical10" , "False" ) Call AddStringParameter ("Mechanical11" , "False" ) Call AddStringParameter ("Mechanical12" , "False" ) Call AddStringParameter ("Mechanical13" , "False" ) Call AddStringParameter ("Mechanical14" , "False" ) Call AddStringParameter ("Mechanical15" , "False" ) Call AddStringParameter ("Mechanical16" , "False" ) Call AddStringParameter ("DrillDrawing" , "False" ) Call AddStringParameter ("MultiLayer" , "True" ) Call RunProcess ("Pcb:DocumentPreferences") End Sub '-------------------------------------------------------------------------------------- '-------------------------------------------------------------------------------------- Sub MechanicalLayers Call ResetParameters Call AddStringParameter ("TopSignal" , "False" ) Call AddStringParameter ("Mid1" , "False" ) Call AddStringParameter ("Mid2" , "False" ) Call AddStringParameter ("Mid3" , "False" ) Call AddStringParameter ("Mid4" , "False" ) Call AddStringParameter ("Mid5" , "False" ) Call AddStringParameter ("Mid6" , "False" ) Call AddStringParameter ("Mid7" , "False" ) Call AddStringParameter ("Mid8" , "False" ) Call AddStringParameter ("Mid9" , "False" ) Call AddStringParameter ("Mid10" , "False" ) Call AddStringParameter ("Mid11" , "False" ) Call AddStringParameter ("Mid12" , "False" ) Call AddStringParameter ("Mid13" , "False" ) Call AddStringParameter ("Mid14" , "False" ) Call AddStringParameter ("Mid15" , "False" ) Call AddStringParameter ("Mid16" , "False" ) Call AddStringParameter ("Mid17" , "False" ) Call AddStringParameter ("Mid18" , "False" ) Call AddStringParameter ("Mid19" , "False" ) Call AddStringParameter ("Mid20" , "False" ) Call AddStringParameter ("Mid21" , "False" ) Call AddStringParameter ("Mid22" , "False" ) Call AddStringParameter ("Mid23" , "False" ) Call AddStringParameter ("Mid24" , "False" ) Call AddStringParameter ("Mid25" , "False" ) Call AddStringParameter ("Mid26" , "False" ) Call AddStringParameter ("Mid27" , "False" ) Call AddStringParameter ("Mid28" , "False" ) Call AddStringParameter ("Mid29" , "False" ) Call AddStringParameter ("Mid30" , "False" ) Call AddStringParameter ("BottomSignal" , "False" ) Call AddStringParameter ("TopOverlay" , "False" ) Call AddStringParameter ("BottomOverlay" , "False" ) Call AddStringParameter ("TopPaste" , "False" ) Call AddStringParameter ("BottomPaste" , "False" ) Call AddStringParameter ("TopSolder" , "False" ) Call AddStringParameter ("BottomSolder" , "False" ) Call AddStringParameter ("Plane1" , "False" ) Call AddStringParameter ("Plane2" , "False" ) Call AddStringParameter ("Plane3" , "False" ) Call AddStringParameter ("Plane4" , "False" ) Call AddStringParameter ("Plane5" , "False" ) Call AddStringParameter ("Plane6" , "False" ) Call AddStringParameter ("Plane7" , "False" ) Call AddStringParameter ("Plane8" , "False" ) Call AddStringParameter ("Plane9" , "False" ) Call AddStringParameter ("Plane10" , "False" ) Call AddStringParameter ("Plane11" , "False" ) Call AddStringParameter ("Plane12" , "False" ) Call AddStringParameter ("Plane13" , "False" ) Call AddStringParameter ("Plane14" , "False" ) Call AddStringParameter ("Plane15" , "False" ) Call AddStringParameter ("Plane16" , "False" ) Call AddStringParameter ("DrillGuide" , "True" ) Call AddStringParameter ("KeepOut" , "True" ) Call AddStringParameter ("Mechanical1" , "True" ) Call AddStringParameter ("Mechanical2" , "True" ) Call AddStringParameter ("Mechanical3" , "True" ) Call AddStringParameter ("Mechanical4" , "True" ) Call AddStringParameter ("Mechanical5" , "True" ) Call AddStringParameter ("Mechanical6" , "True" ) Call AddStringParameter ("Mechanical7" , "True" ) Call AddStringParameter ("Mechanical8" , "True" ) Call AddStringParameter ("Mechanical9" , "True" ) Call AddStringParameter ("Mechanical10" , "True" ) Call AddStringParameter ("Mechanical11" , "True" ) Call AddStringParameter ("Mechanical12" , "True" ) Call AddStringParameter ("Mechanical13" , "True" ) Call AddStringParameter ("Mechanical14" , "True" ) Call AddStringParameter ("Mechanical15" , "True" ) Call AddStringParameter ("Mechanical16" , "True" ) Call AddStringParameter ("DrillDrawing" , "True" ) Call AddStringParameter ("MultiLayer" , "False" ) Call RunProcess ("Pcb:DocumentPreferences") End Sub '--------------------------------------------------------------------------------------
Public Const precision = 10000 Private Function continued_fraction(steps As Integer, rid_a As String, rid_b As String) As Double Dim res As Double res = 0 For n = steps To 1 Step -1 res = Application.Run(rid_b, n) / (Application.Run(rid_a, n) + res) Next n continued_fraction = Application.Run(rid_a, 0) + res End Function Function sqr2_a(n As Integer) As Integer sqr2_a = IIf(n = 0, 1, 2) End Function Function sqr2_b(n As Integer) As Integer sqr2_b = 1 End Function Function nap_a(n As Integer) As Integer nap_a = IIf(n = 0, 2, n) End Function Function nap_b(n As Integer) As Integer nap_b = IIf(n = 1, 1, n - 1) End Function Function pi_a(n As Integer) As Integer pi_a = IIf(n = 0, 3, 6) End Function Function pi_b(n As Integer) As Long pi_b = IIf(n = 1, 1, (2 * n - 1) ^ 2) End Function Public Sub main() Debug.Print "Precision:", precision Debug.Print "Sqr(2):", continued_fraction(precision, "sqr2_a", "sqr2_b") Debug.Print "Napier:", continued_fraction(precision, "nap_a", "nap_b") Debug.Print "Pi:", continued_fraction(precision, "pi_a", "pi_b") End Sub
Sub Main() Dim Result As Long Result = Multiply(564231, 897) End Sub
<gh_stars>10-100 ' ' test1.vbs ' ' test string manipulation ' Dim a(2,4) Dim DevConStrings Dim String Dim b a(1,1) = "1,1" a(1,2) = "1,2" a(1,3) = "1,3" a(1,4) = "1,4" a(2,1) = "2,1" a(2,2) = "2,2" a(2,3) = "2,3" a(2,4) = "2,4" set WshShell = WScript.CreateObject("WScript.Shell") set DevConStrings = WScript.CreateObject("DevCon.Strings") DevConStrings.Add "Alpha" DevConStrings.Add "Beta" DevConStrings.Add "Gamma" DevConStrings.Add "Delta" DevConStrings.Insert 2,a Wscript.Echo "Everything with a(xx) at 2" Count = DevConStrings.Count Wscript.Echo "Count="+CStr(Count) FOR EACH String In DevConStrings WScript.Echo String NEXT Wscript.Echo "As array" b = DevConStrings set DevConStrings = nothing set DevConStrings = WScript.CreateObject("DevCon.Strings") DevConStrings.Add b Wscript.Echo "" Wscript.Echo "As array re-applied" FOR i = 1 TO Count WScript.Echo DevConStrings(i) NEXT Wscript.Echo "" Wscript.Echo "As array raw" FOR i = 1 TO Count WScript.Echo b(i) NEXT
<reponame>npocmaka/Windows-Server-2003 Dim oCluster Dim devicePath Dim logSize Dim sCluster Main Sub Main Set oCluster = CreateObject("MSCluster.Cluster") sCluster = InputBox( "Cluster to open?" ) oCluster.Open( sCluster ) devicePath = oCluster.QuorumPath logSize = oCluster.QuorumLogSize MsgBox "Quorum path is " & devicePath MsgBox "Quorum log size is " & logSize End Sub
On Error Resume Next Set S = GetObject("winmgmts:root/default") Set C = S.Get C.Path_.Class = "PUTCLASSTEST00" Set P = C.Properties_.Add ("p", 19) P.Qualifiers_.Add "key", true C.Put_ Set C = GetObject("winmgmts:[locale=ms_409]!root/default:PUTCLASSTEST00") Set I = C.SpawnInstance_ WScript.Echo "Relpath of new instance is", I.Path_.Relpath I.Properties_("p") = 11 WScript.Echo "Relpath of new instance is", I.Path_.Relpath Set NewPath = I.Put_ WScript.Echo "path of new instance is", NewPath.path WScript.Echo "locale of new instance is", NewPath.locale If Err <> 0 Then WScript.Echo Err.Number, Err.Description Err.Clear End If
<filename>admin/pchealth/authtools/prodtools/common/rutinaslib.bas Attribute VB_Name = "RutinasLib" '=========================================================================================== ' Rutinas de Libreria ' '=========================================================================================== ' SubRoutine : vntGetTok ' Author : <NAME> ' Version : 1.1 ' ' Description : Devuelve un Token tipado extrayendo el mismo del String de origen ' sobre la base de un separador de Tokens pasado como argumento. ' ' Called by : Anyone, utility ' ' Environment data: ' Files that it uses (Specify if they are inherited in open state): NONE ' Parameters (Command Line) and usage mode {I,I/O,O}: ' Parameters (inherited from environment) : ' Public Variables created: ' Environment Variables (Public or Module Level) modified: ' Environment Variables used in coupling with other routines: ' Local variables : ' Problems detected : ' Request for Modifications: ' History: ' 1999-08-01 Added some routines for Skipping Whites, and File Management '=========================================================================================== Option Explicit Public Function vntGetTok(ByRef sTokStrIO As String, Optional ByVal iTipDatoIN = vbString, Optional ByVal sTokSepIN As String = ":") As Variant Dim iPosSep As Integer sTokStrIO = Trim$(sTokStrIO) If Len(sTokStrIO) > 0 Then iPosSep = InStr(1, sTokStrIO, sTokSepIN, 0) Select Case iTipDatoIN Case vbInteger To vbDouble, vbCurrency, vbDecimal vntGetTok = IIf(iPosSep > 0, Val(SubStr(sTokStrIO, 1, iPosSep - 1)), _ Val(sTokStrIO)) Case vbString vntGetTok = IIf(iPosSep > 0, SubStr(sTokStrIO, 1, iPosSep - 1), sTokStrIO) Case vbBoolean vntGetTok = IIf(iPosSep > 0, SubStr(sTokStrIO, 1, iPosSep - 1) = "S", _ sTokStrIO = "S") End Select If iPosSep > 0 Then sTokStrIO = SubStr(sTokStrIO, iPosSep + Len(sTokSepIN)) Else sTokStrIO = "" End If Else Select Case iTipDatoIN Case vbInteger vntGetTok = 0 Case vbString vntGetTok = "" Case vbBoolean vntGetTok = False End Select End If End Function Function SubStr(ByVal sStrIN As String, ByVal iPosIn As Integer, _ Optional ByVal iPosFin As Integer = -1) As String On Local Error GoTo SubstrErrHandler If iPosFin = -1 Then iPosFin = Len(sStrIN) SubStr = Mid$(sStrIN, iPosIn, iPosFin - iPosIn + 1) Exit Function SubstrErrHandler: SubStr = vbNullString Resume Next End Function Public Function SkipWhite(ByRef strIn As String) While " " = Left$(strIn, 1) strIn = Right$(strIn, Len(strIn) - 1) Wend SkipWhite = strIn End Function ' Aun no anda, el Dir no funciona sobre shares pareciera. Public Function bIsDirectory(ByVal sDirIN As String) As Boolean On Local Error GoTo ErrHandler bIsDirectory = True Dir sDirIN Exit Function ErrHandler: bIsDirectory = False Resume Next End Function Function FileExists(strPath) As Boolean Dim Msg As String ' Turn on error trapping so error handler responds ' if any error is detected. On Error GoTo CheckError FileExists = False If "" = strPath Then Exit Function FileExists = (Dir(strPath) <> "") ' Avoid executing error handler if no error ' occurs. Exit Function CheckError: ' Branch here if error occurs. ' Define constants to represent intrinsic Visual ' Basic error codes. Const mnErrDiskNotReady = 71, _ mnErrDeviceUnavailable = 68 ' vbExclamation, vbOK, vbCancel, vbCritical, and ' vbOKCancel are constants defined in the VBA type ' library. If (Err.Number = mnErrDiskNotReady) Then Msg = "Put a floppy disk in the drive " Msg = Msg & "and close the door." ' Display message box with an exclamation mark ' icon and with OK and Cancel buttons. If MsgBox(Msg, vbExclamation & vbOKCancel) = _ vbOK Then Resume Else Resume Next End If ElseIf Err.Number = mnErrDeviceUnavailable Then Msg = "This drive or path does not exist: " Msg = Msg & strPath MsgBox Msg, vbExclamation Resume Next Else Msg = "Unexpected error #" & Str(Err.Number) Msg = Msg & " occurred: " & Err.Description ' Display message box with Stop sign icon and ' OK button. MsgBox Msg, vbCritical Stop End If Resume End Function Function Max(ByVal f1 As Double, ByVal f2 As Double) As Double Max = IIf(f1 > f2, f1, f2) End Function ' dirname: Returns the Parent Directory Pathname of a Pathname Public Function Dirname(ByVal sPath As String) As String Dirname = "" If "" = sPath Then Exit Function Dim bDQ As Boolean bDQ = (Left$(sPath, 1) = Chr(34)) Dim iDirWack As Long iDirWack = InStrRev(sPath, "\") iDirWack = Max(iDirWack, InStrRev(sPath, "/")) If iDirWack = 0 Then Exit Function Dirname = Left$(sPath, iDirWack - 1) & IIf(bDQ, Chr(34), "") End Function ' Basename: Returns only the FileName Entry component of a Pathname Public Function Basename(ByVal sPath As String) As String Basename = sPath If "" = sPath Then Exit Function Dim bDQ As Boolean bDQ = (Left$(sPath, 1) = Chr(34)) Dim iDirWack As Long iDirWack = InStrRev(sPath, "\") If iDirWack = 0 Then iDirWack = InStrRev(sPath, "/") If iDirWack = 0 Then Exit Function Basename = IIf(bDQ, Chr(34), "") & Right$(sPath, Len(sPath) - iDirWack) End Function Public Function FilenameNoExt(ByVal sPath As String) As String FilenameNoExt = sPath If "" = sPath Then Exit Function Dim bDQ As Boolean bDQ = (Left$(sPath, 1) = Chr(34)) Dim iDot As Long iDot = InStrRev(sPath, ".") If iDot > 0 Then FilenameNoExt = Left$(sPath, iDot - 1) & IIf(bDQ, Chr(34), "") End If End Function Public Function FileExtension(ByVal sPath As String) As String FileExtension = "" If "" = sPath Then Exit Function Dim bDQ As Boolean bDQ = (Right$(sPath, Len(sPath) - 1) = Chr(34)) If bDQ Then sPath = Left$(sPath, Len(sPath) - 1) Dim iDot As Long iDot = InStrRev(sPath, ".") If iDot > 0 Then FileExtension = UCase$(Right$(sPath, Len(sPath) - iDot)) End If End Function Public Function Rel2AbsPathName(ByVal sPath As String) As String Rel2AbsPathName = sPath If "" = sPath Then Exit Function sPath = Trim$(sPath) If sPath = Basename(sPath) Then Rel2AbsPathName = CurDir() + "\" + sPath ElseIf Left$(sPath, 2) = ".\" Then Rel2AbsPathName = CurDir() + Mid$(sPath, 2, Len(sPath) - 1) ElseIf Left$(sPath, 3) = """.\" Then Rel2AbsPathName = """" + CurDir() + Mid$(sPath, 3, Len(sPath) - 2) End If End Function Public Function UnQuotedPath(sPath As String, Optional bIsQuoted As Boolean = False) As String UnQuotedPath = Trim$(sPath) If "" = UnQuotedPath Then Exit Function If Left$(UnQuotedPath, 1) = """" Then bIsQuoted = True UnQuotedPath = Mid$(UnQuotedPath, 2, Len(UnQuotedPath) - 1) If Right$(UnQuotedPath, 1) = """" Then UnQuotedPath = Left$(UnQuotedPath, Len(UnQuotedPath) - 1) End If End If End Function Public Function QuotedPath(sPath As String) As String QuotedPath = """" + Trim$(sPath) + """" End Function Public Function ChangeFileExt(sPath As String, sExt As String) As String Dim bIsQuoted As Boolean bIsQuoted = False ChangeFileExt = UnQuotedPath(Trim$(sPath), bIsQuoted) If "" = ChangeFileExt Then Exit Function If (bIsQuoted) Then ChangeFileExt = QuotedPath(FilenameNoExt(ChangeFileExt) + sExt) Else ChangeFileExt = FilenameNoExt(ChangeFileExt) + sExt End If End Function Public Function IsFullPathname(ByVal strPath As String) As Boolean strPath = Trim$(strPath) IsFullPathname = (Left$(strPath, 2) = "\\" Or Mid$(strPath, 2, 2) = ":\") End Function #If NEEDED Then Sub DumpError(ByVal strFunction As String, ByVal strErrMsg As String) MsgBox strFunction & " - Failed " & strErrMsg & vbCrLf & _ "Error Number = " & Err.Number & " - " & Err.Description, _ vbCritical, "Error" ' Err.Clear End Sub #End If Function Capitalize(strIn As String) As String Capitalize = UCase$(Left$(strIn, 1)) + Mid$(strIn, 2) End Function Function KindOfPrintf(ByVal strFormat, ByVal args As Variant) As String If (Not IsArray(args)) Then args = Array(args) End If Dim iX As Integer, iPos As Integer KindOfPrintf = "" For iX = 0 To UBound(args) iPos = InStr(strFormat, "%s") If (iPos = 0) Then Exit For strFormat = Mid$(strFormat, 1, iPos - 1) & args(iX) & Mid$(strFormat, iPos + 2) Next iX KindOfPrintf = strFormat End Function Function ShowAsHex(ByVal strHex As String) As String Dim iX As Integer Dim byteRep() As Byte byteRep = strHex ShowAsHex = "0x" For iX = 1 To UBound(byteRep) ShowAsHex = ShowAsHex + Hex(byteRep(iX)) Next iX End Function Function Null2EmptyString(ByVal vntIn) As String If (IsNull(vntIn)) Then Null2EmptyString = vbNullString Else Null2EmptyString = vntIn End If End Function Function Null2Number(ByVal vntIn) As Long If (IsNull(vntIn)) Then Null2Number = 0 Else Null2Number = vntIn End If End Function
'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 '------------------------------------------------------------------------------ 'FILE DESCRIPTION: Script for registering for SMTP Protocol sinks. ' 'File Name: smtpreg.vbs ' ' ' Copyright (c) Microsoft Corporation 1993-1998. All rights reserved. '------------------------------------------------------------------------------ Option Explicit ' ' ' the OnArrival event GUID Const GUIDComCatOnArrival = "{ff3caa23-00b9-11d2-9dfb-00C04FA322BA}" ' the SMTP source type Const GUIDSourceType = "{4f803d90-fd85-11d0-869a-00c04fd65616}" ' Const GUIDCat = "{871736c0-fd85-11d0-869a-00c04fd65616}" Const GUIDSources = "{DBC71A31-1F4B-11d0-869D-80C04FD65616}" ' the SMTP service display name. This is used to key which service to ' edit Const szService = "smtpsvc" ' the event manager object. This is used to communicate with the ' event binding database. Dim EventManager Dim ComCat Dim DatabaseManager Set EventManager = WScript.CreateObject("Event.Manager") Set ComCat = WScript.CreateObject("Event.ComCat") Set DatabaseManager = WScript.CreateObject("Event.MetabaseDatabaseManager") ComCat.RegisterCategory GUIDCat, "Smtp OnArrival", 0 ' cretae the source type Dim SourceType Dim Source Set SourceType = EventManager.SourceTypes.Add(GUIDSourceType) SourceType.DisplayName = "SMTP Source Type" SourceType.EventTypes.Add(GUIDCat) ' create the source Set Source = SourceType.Sources.Add(GUIDSources) Source.DisplayName = "smtpsvc 1" Source.BindingManagerMoniker = DatabaseManager.CreateDatabase(DatabaseManager.MakeVServerPath(szService,1)) Source.Save SourceType.Save ' ' register a new sink with event manager ' ' iInstance - the instance to work against ' szEvent - OnArrival ' szDisplayName - the display name for this new sink ' szProgID - the progid to call for this event ' szRule - the rule to set for this event ' public sub RegisterSink(iInstance, szEvent, szDisplayName, szProgID, szRule) Dim SourceType Dim szSourceDisplayName Dim Source Dim Binding Dim GUIDComCat ' figure out which event they are trying to register with and set ' the comcat for this event in GUIDComCat select case LCase(szEvent) case "onarrival" GUIDComCat = GUIDComCatOnArrival case else WScript.echo "invalid event: " + szEvent exit sub end select ' enumerate through each of the registered instances for the SMTP source ' type and look for the display name that matches the instance display ' name set SourceType = EventManager.SourceTypes(GUIDSourceType) szSourceDisplayName = szService + " " + iInstance for each Source in SourceType.Sources if Source.DisplayName = szSourceDisplayName then ' we've found the desired instance. now add a new binding ' with the right event GUID. by not specifying a GUID to the ' Add method we get server events to create a new ID for this ' event set Binding = Source.GetBindingManager.Bindings(GUIDComCat).Add("") ' set the binding properties Binding.DisplayName = szDisplayName Binding.SinkClass = szProgID ' register a rule with the binding Binding.SourceProperties.Add "Rule", szRule ' save the binding Binding.Save WScript.Echo "registered " + szDisplayName exit sub end if next end sub ' ' check for a previously registered sink with the passed in name ' ' iInstance - the instance to work against ' szEvent - OnArrival ' szDisplayName - the display name of the event to check ' bCheckError - Any errors returned public sub CheckSink(iInstance, szEvent, szDisplayName, bCheckError) Dim SourceType Dim GUIDComCat Dim szSourceDisplayName Dim Source Dim Bindings Dim Binding bCheckError = FALSE select case LCase(szEvent) case "onarrival" GUIDComCat = GUIDComCatOnArrival case else WScript.echo "invalid event: " + szEvent exit sub end select ' find the source for this instance set SourceType = EventManager.SourceTypes(GUIDSourceType) szSourceDisplayName = szService + " " + iInstance for each Source in SourceType.Sources if Source.DisplayName = szSourceDisplayName then ' find the binding by display name. to do this we enumerate ' all of the bindings and try to match on the display name set Bindings = Source.GetBindingManager.Bindings(GUIDComCat) for each Binding in Bindings if Binding.DisplayName = szDisplayName then ' we've found the binding, now log an error WScript.Echo "Binding with the name " + szDisplayName + " already exists" exit sub end if next end if next bCheckError = TRUE end sub ' ' unregister a previously registered sink ' ' iInstance - the instance to work against ' szEvent - OnArrival ' szDisplayName - the display name of the event to remove ' public sub UnregisterSink(iInstance, szEvent, szDisplayName) Dim SourceType Dim GUIDComCat Dim szSourceDisplayName Dim Source Dim Bindings Dim Binding select case LCase(szEvent) case "onarrival" GUIDComCat = GUIDComCatOnArrival case else WScript.echo "invalid event: " + szEvent exit sub end select ' find the source for this instance set SourceType = EventManager.SourceTypes(GUIDSourceType) szSourceDisplayName = szService + " " + iInstance for each Source in SourceType.Sources if Source.DisplayName = szSourceDisplayName then ' find the binding by display name. to do this we enumerate ' all of the bindings and try to match on the display name set Bindings = Source.GetBindingManager.Bindings(GUIDComCat) for each Binding in Bindings if Binding.DisplayName = szDisplayName then ' we've found the binding, now remove it Bindings.Remove(Binding.ID) WScript.Echo "removed " + szDisplayName + " " + Binding.ID end if next end if next end sub ' ' add or remove a property from the source or sink propertybag for an event ' ' iInstance - the SMTP instance to edit ' szEvent - the event type (OnArrival) ' szDisplayName - the display name of the event ' szPropertyBag - the property bag to edit ("source" or "sink") ' szOperation - "add" or "remove" ' szPropertyName - the name to edit in the property bag ' szPropertyValue - the value to assign to the name (ignored for remove) ' public sub EditProperty(iInstance, szEvent, szDisplayName, szPropertyBag, szOperation, szPropertyName, szPropertyValue) Dim SourceType Dim GUIDComCat Dim szSourceDisplayName Dim Source Dim Bindings Dim Binding Dim PropertyBag select case LCase(szEvent) case "onarrival" GUIDComCat = GUIDComCatOnArrival case else WScript.echo "invalid event: " + szEvent exit sub end select ' find the source for this instance set SourceType = EventManager.SourceTypes(GUIDSourceType) szSourceDisplayName = szService + " " + iInstance for each Source in SourceType.Sources if Source.DisplayName = szSourceDisplayName then set Bindings = Source.GetBindingManager.Bindings(GUIDComCat) ' find the binding by display name. to do this we enumerate ' all of the bindings and try to match on the display name for each Binding in Bindings if Binding.DisplayName = szDisplayName then ' figure out which set of properties we want to modify ' based on the szPropertyBag parameter select case LCase(szPropertyBag) case "source" set PropertyBag = Binding.SourceProperties case "sink" set PropertyBag = Binding.SinkProperties case else WScript.echo "invalid propertybag: " + szPropertyBag exit sub end select ' figure out what operation we want to perform select case LCase(szOperation) case "remove" ' they want to remove szPropertyName from the ' property bag PropertyBag.Remove szPropertyName WScript.echo "removed property " + szPropertyName case "add" ' add szPropertyName to the property bag and ' set its value to szValue. if this value ' already exists then this will change the value ' it to szValue. PropertyBag.Add szPropertyName, szPropertyValue WScript.echo "set property " + szPropertyName + " to " + szPropertyValue case else WScript.echo "invalid operation: " + szOperation exit sub end select ' save the binding Binding.Save end if next end if next end sub ' ' this helper function takes an IEventSource object and a event category ' and dumps all of the bindings for this category under the source ' ' Source - the IEventSource object to display the bindings for ' GUIDComCat - the event category to display the bindings for ' public sub DisplaySinksHelper(Source, GUIDComCat) Dim Binding Dim propval ' walk each of the registered bindings for this component category for each Binding in Source.GetBindingManager.Bindings(GUIDComCat) ' display the binding properties WScript.echo " Binding " + Binding.ID + " {" WScript.echo " DisplayName = " + Binding.DisplayName WScript.echo " SinkClass = " + Binding.SinkClass ' walk each of the source properties and display them WScript.echo " SourceProperties {" for each propval in Binding.SourceProperties WScript.echo " " + propval + " = " + Binding.SourceProperties.Item(propval) next WScript.echo " }" ' walk each of the sink properties and display them WScript.echo " SinkProperties {" for each Propval in Binding.SinkProperties WScript.echo " " + propval + " = " + Binding.SinkProperties.Item(Propval) next WScript.echo " }" WScript.echo " }" next end sub ' ' dumps all of the information in the binding database related to SMTP ' public sub DisplaySinks Dim SourceType Dim Source ' look for each of the sources registered for the SMTP source type set SourceType = EventManager.SourceTypes(GUIDSourceType) for each Source in SourceType.Sources ' display the source properties WScript.echo "Source " + Source.ID + " {" WScript.echo " DisplayName = " + Source.DisplayName ' display all of the sinks registered for the OnArrival event WScript.echo " OnArrival Sinks {" call DisplaySinksHelper(Source, GUIDComCatOnArrival) WScript.echo " }" next end sub ' ' display usage information for this script ' public sub DisplayUsage WScript.echo "usage: cscript smtpreg.vbs <command> <arguments>" WScript.echo " commands:" WScript.echo " /add <Instance> <Event> <DisplayName> <SinkClass> <Rule>" WScript.echo " /remove <Instance> <Event> <DisplayName>" WScript.echo " /setprop <Instance> <Event> <DisplayName> <PropertyBag> <PropertyName> " WScript.echo " <PropertyValue>" WScript.echo " /delprop <Instance> <Event> <DisplayName> <PropertyBag> <PropertyName>" WScript.echo " /enum" WScript.echo " arguments:" WScript.echo " <Instance> is the SMTP instance to work against" WScript.echo " <Event> can be OnArrival" WScript.echo " <DisplayName> is the display name of the event to edit" WScript.echo " <SinkClass> is the sink class for the event" WScript.echo " <Rule> is the rule to use for the event" WScript.echo " <PropertyBag> can be Source or Sink" WScript.echo " <PropertyName> is the name of the property to edit" WScript.echo " <PropertyValue> is the value to assign to the property" end sub Dim iInstance Dim szEvent Dim szDisplayName Dim szSinkClass Dim szRule Dim szPropertyBag Dim szPropertyName Dim szPropertyValue dim bCheck ' ' this is the main body of our script. it reads the command line parameters ' specified and then calls the appropriate function to perform the operation ' if WScript.Arguments.Count = 0 then call DisplayUsage else Select Case LCase(WScript.Arguments(0)) Case "/add" iInstance = WScript.Arguments(1) szEvent = WScript.Arguments(2) szDisplayName = WScript.Arguments(3) szSinkClass = WScript.Arguments(4) szRule = WScript.Arguments(5) call CheckSink(iInstance, szEvent, szDisplayName, bCheck) if bCheck = TRUE then call RegisterSink(iInstance, szEvent, szDisplayName, szSinkClass, szRule) End if Case "/remove" iInstance = WScript.Arguments(1) szEvent = WScript.Arguments(2) szDisplayName = WScript.Arguments(3) call UnregisterSink(iInstance, szEvent, szDisplayName) Case "/setprop" iInstance = WScript.Arguments(1) szEvent = WScript.Arguments(2) szDisplayName = WScript.Arguments(3) szPropertyBag = WScript.Arguments(4) szPropertyName = WScript.Arguments(5) szPropertyValue = WScript.Arguments(6) call EditProperty(iInstance, szEvent, szDisplayName, szPropertyBag, "add", szPropertyName, szPropertyValue) Case "/delprop" iInstance = WScript.Arguments(1) szEvent = WScript.Arguments(2) szDisplayName = WScript.Arguments(3) szPropertyBag = WScript.Arguments(4) szPropertyName = WScript.Arguments(5) call EditProperty(iInstance, szEvent, szDisplayName, szPropertyBag, "remove", szPropertyName, "") Case "/dump" call DisplaySinks Case "/enum" call DisplaySinks Case Else call DisplayUsage End Select end if
Public stateBSD As Variant Public stateMS As Variant Private Function bsd() As Long Dim temp As Variant temp = CDec(1103515245 * stateBSD + 12345) temp2 = temp / 2 ^ 31 temp3 = CDec(WorksheetFunction.Floor_Precise(temp2)) stateBSD = temp - (2 ^ 31) * temp3 bsd = stateBSD End Function Private Function ms() As Integer Dim temp As Variant temp = CDec(214013 * stateMS + 2531011) temp2 = temp / 2 ^ 31 temp3 = CDec(WorksheetFunction.Floor_Precise(temp2)) stateMS = temp - (2 ^ 31) * temp3 ms = stateMS \ 2 ^ 16 End Function Public Sub main() stateBSD = CDec(0) stateMS = CDec(0) Debug.Print " BSD", " MS" For i = 1 To 10 Debug.Print Format(bsd, "@@@@@@@@@@"), Format(ms, "@@@@@") Next i End Sub
' Get the performance counter instance for the Windows Management process set perfproc = GetObject("winmgmts://alanbos5/root/cimv2:win32_perfrawdata_perfproc_process.name='winmgmt'") ' Display the handle count in a loop for I = 1 to 10000 Wscript.Echo perfproc.HandleCount 'Wscript.Sleep 2000 ' Refresh the object perfproc.Refresh_ next
set objDBConnection = Wscript.CreateObject("ADODB.Connection") set RS = Wscript.CreateObject("ADODB.Recordset") SERVER = InputBox("Enter the name of the SQL Server you wish to connect to"&vbcrlf&vbcrlf&"This SQL Server must have the Northwind sample database installed.", "Connect to SQL Server...") IF LEN(TRIM(SERVER)) = 0 THEN MsgBox "You did not enter the name of a machine to query. Exiting script.", vbCritical, "No machine requested." WScript.Quit END IF USERNAME = InputBox("Enter the name of the SQL Server username to query with", "Enter SQL username...") IF LEN(TRIM(USERNAME)) = 0 THEN MsgBox "You did not enter the SQL Server username to query with. Exiting script.", vbCritical, "No username specified." WScript.Quit END IF PWD = InputBox("Enter the password of the SQL Server you wish to connect to"&vbcrlf&vbcrlf&"Leave blank if no password is needed.", "Enter SQL password...") SQLQuery1 ="SELECT Employees.FirstName AS FirstName, Employees.City AS City FROM Employees WHERE Employees.Lastname = 'Suyama'" objDBConnection.open "Provider=SQLOLEDB;Data Source="&SERVER&";Initial Catalog=Northwind;User ID="&USERNAME&";Password="&<PASSWORD>&";" Set GetRS = objDBConnection.Execute(SQLQuery1) IF GetRS.EOF THEN MsgBox "No employees were found with the last name you searched on!" ELSE Do While Not GetRS.EOF MsgBox "There is an employee in "&GetRS("City")&" named "&GetRS("FirstName")&" with the last name you searched on." GetRS.MoveNext Loop END IF
'------------------------------------------------------------------------- 'Global Variables '------------------------------------------------------------------------- Dim G_ADMIN_PORT Dim G_HTTP Dim G_IIS Dim G_HOST Dim G_ADMIN_NAME Dim G_SHARES_WEBSITEID Dim G_SHARES_NAME Dim G_objHTTPService 'WMI server HTTP object Dim G_nNICCount 'NIC count Dim G_objService 'WMI server HTTP object Dim G_ADMIN_WEBSITEID 'HTTP administration web site WMI name Dim strComputerName Const WMI_IIS_NAMESPACE = "root\MicrosoftIISv1" 'constant to connect to WMI G_ADMIN_PORT = "0" G_ADMIN_NAME = "Administration" G_SHARES_NAME = "Shares" G_HTTP = "http://" G_IIS = "IIS://" G_HOST = GetSystemName() G_SHARES_WEBSITEID = "0" Set G_objHTTPService = GetWMIConnection(WMI_IIS_NAMESPACE) Set G_objService = GetWMIConnection("Default") G_SHARES_WEBSITEID = GetWebSiteID( G_SHARES_NAME ) G_ADMIN_WEBSITEID = GetWebSiteID( G_ADMIN_NAME ) G_ADMIN_PORT = GetAdminPortNumber() Dim strSharesFolder Set oFileSystemObject = CreateObject("Scripting.FileSystemObject") strSharesFolder = GetSharesWebSitePath("Shares") strSharesFolder = "c:\inetpub\shares" Set oDefaultHTMFile = oFileSystemObject.CreateTextFile( strSharesFolder + "\default.asp", True) oDefaultHTMFile.WriteLine( chr(60) & chr(37) ) oDefaultHTMFile.WriteLine( "Dim strServerName " ) oDefaultHTMFile.WriteLine( "Dim WinNTSysInfo " ) oDefaultHTMFile.WriteLine( "Set WinNTSysInfo = CreateObject(""WinNTSystemInfo"") " ) oDefaultHTMFile.WriteLine( "strServerName = UCASE( WinNTSysInfo.ComputerName ) " ) oDefaultHTMFile.WriteLine( chr(37) & chr(62) ) '------------------------------------------------------------------------- 'Start of localization content '------------------------------------------------------------------------- Dim L_HEADER Dim L_FOOTER Dim objLocMgr Dim varReplace varReplace = "" Set objLocMgr = CreateObject("ServerAppliance.localizationmanager") L_HEADER = GetLocString("httpsh.dll", "40300001", "") L_FOOTER = GetLocString("httpsh.dll", "40300002", "") set objLocMgr = nothing '------------------------------------------------------------------------- 'End of localization content '------------------------------------------------------------------------- oDefaultHTMFile.WriteLine("<body marginWidth =0 marginHeight=0 topmargin=0 LEFTMARGIN=0>" ) oDefaultHTMFile.WriteLine("<table width='100%' height='100%' cellspacing=0 cellpadding=0 border=0>" ) oDefaultHTMFile.WriteLine("<tr style='BACKGROUND-COLOR: #000000;" ) oDefaultHTMFile.WriteLine("COLOR: #ffffff;FONT-FAMILY: Arial;FONT-SIZE: 12pt;FONT-WEIGHT: bold;TEXT-DECORATION: none;'> <td align=left> <img src=OEM_LOGO.gif></td>" ) oDefaultHTMFile.WriteLine("<td>" + "<" & "% = strServerName" & "%" & ">" + "</td><td align=right><img src=WinPwr_h_R.gif></td></tr>" ) oDefaultHTMFile.WriteLine("<tr width='100%' height='100%' style='PADDING-LEFT: 15px;PADDING-RIGHT: 15px;'> <td valign=top width='30%'><img src=folder.gif><br><BR><BR>" ) urlHTTPSAdmin = G_HTTPS + "<" & "% = strServerName" & "%" & ">" + ":" + G_SHARES_PORT 'oDefaultHTMFile.Writeline( "<div style='PADDING-BOTTOM: 7px;PADDING-LEFT: 7px;PADDING-RIGHT: 0px;PADDING-TOP: 0px;'>" ) 'oDefaultHTMFile.Writeline( "<a style='COLOR: #000000;FONT-FAMILY: tahoma,arial,verdana,sans-serif;FONT-SIZE: 9pt;' HREF=" +urlHTTPSAdmin + ">" + L_HTTPS_FOOTER + " </a> </div" & " " & L_HTTPS_RECOMENDED ) 'oDefaultHTMFile.WriteLine("<BR>") urlAdmin = G_HTTP + "<" & "% = strServerName" & "%" & ">" + ":" + G_ADMIN_PORT oDefaultHTMFile.Writeline( "<div style='PADDING-BOTTOM: 7px;PADDING-LEFT: 7px;PADDING-RIGHT: 0px;PADDING-TOP: 0px;'>" ) oDefaultHTMFile.Writeline( "<a style='COLOR: #000000;FONT-FAMILY: tahoma,arial,verdana,sans-serif;FONT-SIZE: 9pt;' HREF=" + urlAdmin + ">" + L_FOOTER + " </a> </div>" ) oDefaultHTMFile.WriteLine("</td><td colspan=2 valign=top width='70%'><br>" ) oDefaultHTMFile.WriteLine("<div style='font-family:arial,verdana,sans-serif;font-size:11pt;font-weight: bold;'>" ) oDefaultHTMFile.WriteLine( L_HEADER + " " + "<" & "% = strServerName" & "%" & ">" + "</H2>" ) oDefaultHTMFile.WriteLine("</div>") Dim oWebVirtDir Dim oWebRoot Dim index Dim urlAdmin, i, urlHTTPSAdmin Dim arrVroots() ReDim arrVroots(5000, 1 ) Set oWebRoot = GetObject( "IIS://" & G_HOST & "/" & G_SHARES_WEBSITEID & "/root") index = -1 For Each oWebVirtDir in oWebRoot index = index + 1 arrVroots( index, 0 ) = oWebVirtDir.Name Next 'Call QuickSort( arrVroots, 0, index, 1, 0 ) If Index = -1 Then oDefaultHTMFile.Writeline( "<div style='FONT-FAMILY: tahoma,arial,verdana,sans-serif;FONT-SIZE: 9pt;'") oDefaultHTMFile.Writeline( "Empty: There are no shares to list " ) oDefaultHTMFile.Writeline( "</div>" ) End If For i = 0 To index oDefaultHTMFile.Writeline( "<div style='PADDING-BOTTOM: 7px;PADDING-LEFT: 7px;PADDING-RIGHT: 0px;PADDING-TOP: 0px;'>") oDefaultHTMFile.Writeline("<a style='COLOR: #000000;FONT-FAMILY: tahoma,arial,verdana,sans-serif;FONT-SIZE: 9pt;' HREF=" + chr(34) + arrVroots( i, 0 ) + chr(34) + " > " + arrVroots( i, 0 ) + "</a></div>" ) 'oDefaultHTMFile.WriteLine("</div>") Next oDefaultHTMFile.WriteLine("</td></tr></table></body>") 'oDefaultHTMFile.WriteLine("<BR>") 'urlHTTPSAdmin = G_HTTPS + G_HOST + ":" + G_SHARES_PORT 'oDefaultHTMFile.Writeline( "<a HREF=" +urlHTTPSAdmin + ">" + L_HTTPS_FOOTER + " </a> " & " " & L_HTTPS_RECOMENDED ) 'oDefaultHTMFile.WriteLine("<BR>") 'urlAdmin = G_HTTP + G_HOST + ":" + G_ADMIN_PORT 'oDefaultHTMFile.Writeline( "<a HREF=" + urlAdmin + ">" + L_FOOTER + " </a> " ) oDefaultHTMFile.Close '---------------------------------------------------------------------------- ' ' Function : QuickSort ' ' Synopsis : sorts elements in alphabetical order ' ' ' Returns : localized string ' '---------------------------------------------------------------------------- Sub QuickSort(arrData, iLow, iHigh) Dim iTmpLow, iTmpHigh, iTmpMid, vTempVal(2), vTmpHold(2) iTmpLow = iLow iTmpHigh = iHigh If iHigh <= iLow Then Exit Sub iTmpMid = (iLow + iHigh) \ 2 vTempVal(0) = arrData(iTmpMid, 0) 'vTempVal(1) = arrData(iTmpMid, 1) Do While (iTmpLow <= iTmpHigh) Do While (arrData(iTmpLow, 0) < vTempVal(0) And iTmpLow < iHigh) iTmpLow = iTmpLow + 1 Loop Do While (vTempVal(0) < arrData(iTmpHigh, 0) And iTmpHigh > iLow) iTmpHigh = iTmpHigh - 1 Loop If (iTmpLow <= iTmpHigh) Then vTmpHold(0) = arrData(iTmpLow, 0) 'vTmpHold(1) = arrData(iTmpLow, 1) arrData(iTmpLow, 0) = arrData(iTmpHigh, 0) 'arrData(iTmpLow, 1) = arrData(iTmpHigh, 1) arrData(iTmpHigh, 0) = vTmpHold(0) 'arrData(iTmpHigh, 1) = vTmpHold(1) iTmpLow = iTmpLow + 1 iTmpHigh = iTmpHigh - 1 End If Loop If (iLow < iTmpHigh) Then QuickSort arrData, iLow, iTmpHigh End If If (iTmpLow < iHigh) Then QuickSort arrData, iTmpLow, iHigh End If End Sub '---------------------------------------------------------------------------- ' ' Function : GetLocString ' ' Synopsis : Gets localized string from resource dll ' ' Arguments: SourceFile(IN) - resource dll name ' ResourceID(IN) - resource id in hex ' ReplacementStrings(IN) - parameters to replace in string ' ' Returns : localized string ' '---------------------------------------------------------------------------- Function GetLocString(SourceFile, ResourceID, ReplacementStrings) ' returns localized string ' Dim objLocMgr Dim varReplacementStrings ' prep inputs If Left(ResourceID, 2) <> "&H" Then ResourceID = "&H" & ResourceID End If If Trim(SourceFile) = "" Then SourceFile = "svrapp" End If If (Not IsArray(ReplacementStrings)) Then ReplacementStrings = varReplacementStrings End If ' call Localization Manager Set objLocMgr = CreateObject("ServerAppliance.LocalizationManager") If ( IsObject(objLocMgr) ) Then Err.Clear ' ' Disable error trapping ' 'on error resume next ' ' Get the string, do not hault for any errors GetLocString = objLocMgr.GetString(SourceFile, ResourceID, ReplacementStrings) Set objLocMgr = Nothing Dim errorCode Dim errorDesc errorCode = Err.Number errorDesc = Err.description Err.Clear ' ' Check errors ' If errorCode <> 0 Then Dim strErrorDescription strErrorDescription = "ISSUE: String not found. Source:" + CStr(SourceFile) + " ResID:" + CStr(ResourceID) GetLocString = strErrorDescription End If Else GetLocString = "ISSUE: Localization string not found. Source:" + CStr(SourceFile) + " ResID:" + CStr(ResourceID) Err.Clear End If End Function '------------------------------------------------------------------------- 'Function name: GetSharesWebSite 'Description: gets admin website name 'Input Variables: 'Output Variables: None 'Returns: String-Website name '------------------------------------------------------------------------- Function GetWebSiteID( strWebSiteName ) 'On Error Resume Next Err.Clear Dim strMangedSiteName Dim strWMIpath Dim objSiteCollection Dim objSite strWMIpath = "select * from IIs_WebServerSetting where servercomment =" & chr(34) & strWebSiteName & chr(34) set objSiteCollection = G_objHTTPService.ExecQuery(strWMIpath) for each objSite in objSiteCollection GetWebSiteID = objSite.Name Exit For Next End Function '------------------------------------------------------------------------- 'Function name: GetWMIConnection 'Description: Serves in getting connected to the server 'Input Variables: strNamespace 'Output Variables: None 'Returns: Object -connection to the server object 'Global Variables: In -L_WMICONNECTIONFAILED_ERRORMESSAGE -Localized strings 'This will try to create an object and connect to wmi if fails shows failure 'page '------------------------------------------------------------------------- Function GetWMIConnection(strNamespace) Err.Clear Dim objLocator Dim objService Set objLocator = CreateObject("WbemScripting.SWbemLocator") If strNamespace = "" OR strNamespace="default" OR strNamespace="DEFAULT" OR strNamespace="Default" Then Set objService = objLocator.ConnectServer Else Set objService = objLocator.ConnectServer(".",strNamespace ) End if 'If Err.number <> 0 Then ' ServeFailurePage L_WMICONNECTIONFAILED_ERRORMESSAGE & "(" & Err.Number & ")" ' Else Set GetWMIConnection = objService 'End If 'Set to nothing Set objLocator=Nothing Set objService=Nothing End Function '------------------------------------------------------------------------- 'Function name: GetAdminPortNumber() 'Output Variables: None 'page '------------------------------------------------------------------------- Function GetAdminPortNumber() 'On Error Resume Next Dim ObjNACCollection Dim Objinst Dim objIPArray Dim strIPProp,strIPArray Dim arrWinsSrv Dim arrIPAdd,arrPort Dim strIPList GetAdminPortNumber = "8111" 'Getting the IIS_WEB Server Setting instance Set ObjNACCollection = G_objHTTPService.ExecQuery("Select * from IIs_WebServerSetting where Name=" & Chr(34)& G_ADMIN_WEBSITEID & Chr(34)) Dim nIPCount For each Objinst in ObjNACCollection For nIPCount = 0 to ubound(Objinst.ServerBindings) strIPArray = Objinst.ServerBindings(nIPCount) 'split the strIPArray array to get the IP address and port arrWinsSrv = split(strIPArray,":") arrIPAdd = arrWinsSrv(0) arrPort = arrWinsSrv(1) GetAdminPortNumber = arrWinsSrv(1) Next Next End Function '------------------------------------------------------------------------- 'Function name: GetSharesWebSitePath 'Description: gets admin website path 'Input Variables: 'Output Variables: None 'Returns: String-Website path '------------------------------------------------------------------------- Function GetSharesWebSitePath( strWebSiteName ) 'On Error Resume Next 'Err.Clear Dim strSiteName Dim strMangedSiteName Dim strWMIpath Dim objSiteCollection Dim objSite Dim objWMI Dim objHttpname Dim objHttpnames Dim str1 'set ObjWMI = getWMIConnection("root\MicrosoftIISv1") 'Set objHttpnames = objWMI.InstancesOf("IIs_WebVirtualDirSetting") 'strSiteName=GetWebSiteID( G_SHARES_NAME ) 'msgbox strSiteName ' Adding all Http shares to Dictionary object 'For Each objHttpname in objHttpnames ' msgbox objHttpname.name 'str1=split(objHttpname.name,"/") ' To get http shares from only "Shares" web site 'If Mid(objHttpname.name,1,7)=strSiteName Then ' GetSharesWebSitePath = objHttpname.path ' msgbox objHttpname.path ' Exit For ' 'end if 'Next End Function Function GetSystemName() Dim WinNTSysInfo Set WinNTSysInfo = CreateObject("WinNTSystemInfo") GetSystemName = WinNTSysInfo.ComputerName End Function Function GetWebSiteID( strWebSiteName ) 'On Error Resume Next Err.Clear Dim strMangedSiteName Dim strWMIpath Dim objSiteCollection Dim objSite strWMIpath = "select * from IIs_WebServerSetting where servercomment =" & chr(34) & strWebSiteName & chr(34) set objSiteCollection = G_objHTTPService.ExecQuery(strWMIpath) for each objSite in objSiteCollection GetWebSiteID = objSite.Name Exit For Next End Function
' L_Welcome_MsgBox_Message_Text = "This script demonstrates how to enumerate snapins from scriptable objects." L_Welcome_MsgBox_Title_Text = "Windows Scripting Host Sample" Call Welcome() ' ******************************************************************************** Dim mmc Dim doc Dim snapins Dim snapin Dim Sample Dim Cert Dim Services Dim MultiSel Dim Eventlog Dim Index Dim SnapinName Dim OtherData 'get the various objects we'll need Set mmc = wscript.CreateObject("MMC20.Application") Set doc = mmc.Document Set snapins = doc.snapins 'Set Sample = snapins.Add("{18731372-1D79-11D0-A29B-00C04FD909DD}") ' Sample snapin 'Set Cert = snapins.Add("{53D6AB1D-2488-11D1-A28C-00C04FB94F17}") ' Certificates s 'Set Index = snapins.Add("{95AD72F0-44CE-11D0-AE29-00AA004B9986}") ' index snapin 'Set Eventlog = snapins.Add("{975797FC-4E2A-11D0-B702-00C04FD8DBF7}") ' eventlog 'Set Services = snapins.Add("{58221c66-ea27-11cf-adcf-00aa00a80033}") ' the services OtherData = "Num Snapins: " & snapins.Count intRet = MsgBox(OtherData, vbInformation, "Snapins count") ' Enumerate the snapins collection and print the about info for each snapin. For Each snapin in snapins SnapinName = snapin.Name OtherData = "Vendor : " + snapin.Vendor OtherData = OtherData + ", Version : " + snapin.Version OtherData = OtherData + ", CLSID : " + snapin.SnapinCLSID ' intRet = MsgBox(OtherData, vbInformation, "About Information for " & SnapinName) Next For i = 1 To snapins.count Set snapin = snapins.Item(i) SnapinName = snapin.Name OtherData = "Vendor : " + snapin.Vendor OtherData = OtherData + ", Version : " + snapin.Version OtherData = OtherData + ", CLSID : " + snapin.SnapinCLSID intRet = MsgBox(OtherData, vbInformation, "About Information for " & SnapinName) Next Set mmc = Nothing ' ******************************************************************************** ' * ' * 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
'Arithmetic - Integer Sub RosettaArithmeticInt() Dim opr As Variant, a As Integer, b As Integer On Error Resume Next a = CInt(InputBox("Enter first integer", "XLSM | Arithmetic")) b = CInt(InputBox("Enter second integer", "XLSM | Arithmetic")) Debug.Print "a ="; a, "b="; b, vbCr For Each opr In Split("+ - * / \ mod ^", " ") Select Case opr Case "mod": Debug.Print "a mod b", a; "mod"; b, a Mod b Case "\": Debug.Print "a \ b", a; "\"; b, a \ b Case Else: Debug.Print "a "; opr; " b", a; opr; b, Evaluate(a & opr & b) End Select Next opr End Sub
<filename>Task/Terminal-control-Dimensions/Visual-Basic/terminal-control-dimensions.vb Module Module1 Sub Main() Dim bufferHeight = Console.BufferHeight Dim bufferWidth = Console.BufferWidth Dim windowHeight = Console.WindowHeight Dim windowWidth = Console.WindowWidth Console.Write("Buffer Height: ") Console.WriteLine(bufferHeight) Console.Write("Buffer Width: ") Console.WriteLine(bufferWidth) Console.Write("Window Height: ") Console.WriteLine(windowHeight) Console.Write("Window Width: ") Console.WriteLine(windowWidth) End Sub End Module
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 Context As SWbemNamedValueSet Set Context = New WbemScripting.SWbemNamedValueSet Context.Add "fred", -12.356 Context.Add "joe", "blah" V1 = Context!fred V2 = Context("fred") Dim Service As SWbemServices Set Service = GetObject("winmgmts:{impersonationLevel=impersonate}") Dim E As SWbemObjectSet Set E = Service.InstancesOf("Win32_Service") Dim S As SWbemObject For Each S In E Debug.Print S.Name Next Set S = E("Win32_Service=""Winmgmt""") P = S.Path_.DisplayName Dim S1 As SWbemObject Set S1 = GetObject(P) Dim Property As SWbemProperty For Each Property In S1.Properties_ Debug.Print Property.Name & " = " & Property.Value Next End Sub
dim a a = array( "portcullis", "redoubt", "palissade", "turret", "collins", "the parapet", "the quarterdeck") wscript.echo join( a, ", ") dim b b = cocktailSort( a ) wscript.echo join( b, ", ")
Function GCD(ByVal a As Long, ByVal b As Long) As Long Dim h As Long If a Then If b Then Do h = a Mod b a = b b = h Loop While b End If GCD = Abs(a) Else GCD = Abs(b) End If End Function Sub Main() ' testing the above function Debug.Assert GCD(12, 18) = 6 Debug.Assert GCD(1280, 240) = 80 Debug.Assert GCD(240, 1280) = 80 Debug.Assert GCD(-240, 1280) = 80 Debug.Assert GCD(240, -1280) = 80 Debug.Assert GCD(0, 0) = 0 Debug.Assert GCD(0, 1) = 1 Debug.Assert GCD(1, 0) = 1 Debug.Assert GCD(3475689, 23566319) = 7 Debug.Assert GCD(123456789, 234736437) = 3 Debug.Assert GCD(3780, 3528) = 252 End Sub
<reponame>npocmaka/Windows-Server-2003 VERSION 5.00 Begin VB.Form Form1 Caption = "Form1" ClientHeight = 6915 ClientLeft = 60 ClientTop = 345 ClientWidth = 9585 LinkTopic = "Form1" ScaleHeight = 6915 ScaleWidth = 9585 StartUpPosition = 3 'Windows Default Begin VB.CommandButton Clear Caption = "Clear" Height = 615 Left = 720 TabIndex = 4 Top = 5880 Width = 2415 End Begin VB.CommandButton Command3 Caption = "DispSink" Height = 735 Left = 2640 TabIndex = 3 Top = 600 Width = 1695 End Begin VB.CommandButton Command2 Caption = "Reclaim" Height = 735 Left = 5520 TabIndex = 2 Top = 600 Width = 2055 End Begin VB.ListBox List1 Height = 2985 Left = 960 TabIndex = 1 Top = 2520 Width = 5055 End Begin VB.CommandButton Command1 Caption = "VBSink" Height = 735 Left = 360 TabIndex = 0 Top = 480 Width = 1815 End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Dim services As SWbemServices Dim WithEvents sink As SWbemSink Attribute sink.VB_VarHelpID = -1 Dim asyncContext As SWbemNamedValueSet Dim context As SWbemNamedValueSet Private Sub Clear_Click() List1.Clear End Sub Private Sub Command1_Click() Set services = GetObject("winmgmts:") Set sink = New SWbemSink Set asyncContext = New SWbemNamedValueSet Set context = New SWbemNamedValueSet ret = asyncContext.Add("first", 1) ret = context.Add("first", 1) Set ret = services.GetAsync(sink, "Win32_process", , context, asyncContext) End Sub Private Sub Command2_Click() Set services = Nothing Set sink = Nothing Set obj = Nothing Set context = Nothing Set asyncContext = Nothing End Sub Private Sub Command3_Click() Set services = GetObject("winmgmts:") Set asyncContext = New SWbemNamedValueSet Set context = New SWbemNamedValueSet ret = asyncContext.Add("first", 1) ret = context.Add("first", 1) Set sink = services.GetAsync(sink, "Win32_process", , context, asyncContext) End Sub Private Sub sink_OnCompleted(ByVal iHResult As WbemScripting.WbemErrorEnum, ByVal objWbemErrorObject As WbemScripting.ISWbemObject, ByVal objWbemAsyncObject As WbemScripting.ISWbemSinkControl, ByVal objWbemAsyncContext As WbemScripting.ISWbemNamedValueSet) List1.AddItem "iHResult: " & iHResult End Sub Private Sub sink_OnObjectReady(ByVal objWbemObject As WbemScripting.ISWbemObject, ByVal objWbemAsyncObject As WbemScripting.ISWbemSinkControl, ByVal objWbemAsyncContext As WbemScripting.ISWbemNamedValueSet) List1.AddItem (objWbemObject.Path_.Path) End Sub
on error resume next Set ObjectPath = CreateObject("WbemScripting.SWbemObjectPath") ObjectPath.Server = "hah" ObjectPath.Namespace = "root/default/something" ObjectPath.Class = "ho" ObjectPath.Keys.Add "fred1", 10 ObjectPath.Keys.Add "fred2", -34 ObjectPath.Keys.Add "fred3", 65234654 ObjectPath.Keys.Add "fred4", "Wahaay" ObjectPath.Keys.Add "fred5", -786186777 if err <> 0 then WScript.Echo err.number end if WScript.Echo "Pass 1:" WScript.Echo ObjectPath.Path WScript.Echo ObjectPath.DisplayName WScript.Echo "" ObjectPath.Security_.ImpersonationLevel = 3 WScript.Echo "Pass 2:" WScript.Echo ObjectPath.Path WScript.Echo ObjectPath.DisplayName WScript.Echo "" ObjectPath.Security_.AuthenticationLevel = 5 WScript.Echo "Pass 3:" WScript.Echo ObjectPath.Path WScript.Echo ObjectPath.DisplayName WScript.Echo "" Set Privileges = ObjectPath.Security_.Privileges if err <> 0 then WScript.Echo Hex(Err.Number), Err.Description end if Privileges.Add 8 Privileges.Add 20, false WScript.Echo "Pass 4:" WScript.Echo ObjectPath.Path WScript.Echo ObjectPath.DisplayName WScript.Echo "" ObjectPath.DisplayName = "winmgmts:{impersonationLevel=impersonate,authenticationLevel=pktprivacy,(Debug,!IncreaseQuota, CreatePagefile ) }!//fred/root/blah" WScript.Echo "Pass 5:" WScript.Echo ObjectPath.Path WScript.Echo ObjectPath.DisplayName WScript.Echo ""
' VBScript has a String() function that can repeat a character a given number of times ' but this only works with single characters (or the 1st char of a string): WScript.Echo String(10, "123") ' Displays "1111111111" ' To repeat a string of chars, you can use either of the following "hacks"... WScript.Echo Replace(Space(10), " ", "Ha") WScript.Echo Replace(String(10, "X"), "X", "Ha")
Function ICE09() On Error Resume Next Set recInfo=Installer.CreateRecord(1) If Err <> 0 Then ICE09 = 1 Exit Function End If 'Give description of test recInfo.StringData(0)="ICE09" & Chr(9) & "3" & Chr(9) & "ICE09 - Checks for components whose Directory is the System directory but aren't set as system components " Message &h03000000, recInfo 'Give creation data recInfo.StringData(0)="ICE09" & Chr(9) & "3" & Chr(9) & "Created 05/21/98. Last Modified 10/09/2000." Message &h03000000, recInfo 'Is there a Component table in the database? iStat = Database.TablePersistent("Component") If 1 <> iStat Then recInfo.StringData(0)="ICE09" & Chr(9) & "3" & Chr(9) & "'Component' table missing. ICE09 cannot continue its validation." Message &h03000000, recInfo ICE09 = 1 Exit Function End If 'process table Set view=Database.OpenView("SELECT `Component`, `Attributes` FROM `Component` WHERE `Directory_`='SystemFolder' OR `Directory_`='System16Folder' OR `Directory_`='System64Folder'") view.Execute If Err <> 0 Then recInfo.StringData(0)="ICE09" & Chr(9) & "0" & Chr(9) & "view.Execute_1 API Error" Message &h03000000, recInfo ICE09=1 Exit Function End If Do Set rec=view.Fetch If rec Is Nothing Then Exit Do 'check for permanent attribute. If (rec.IntegerData(2) AND 16)=0 Then rec.StringData(0)="ICE09" & Chr(9) & "2" & Chr(9) & "Component: [1] is a non-permanent system component" & Chr(9) & "" & Chr(9) & "Component" & Chr(9) & "Component" & Chr(9) & "[1]" Message &h03000000,rec End If Loop 'Return iesSuccess ICE09 = 1 Exit Function End Function
<gh_stars>1-10 Option Explicit '-------------------------------------------------- Sub varargs(ParamArray a()) Dim n As Long, m As Long Debug.Assert VarType(a) = (vbVariant Or vbArray) For n = LBound(a) To UBound(a) If IsArray(a(n)) Then For m = LBound(a(n)) To UBound(a(n)) Debug.Print a(n)(m) Next m Else Debug.Print a(n) End If Next End Sub '-------------------------------------------------- Sub Main() Dim v As Variant Debug.Print "call 1" varargs 1, 2, 3 Debug.Print "call 2" varargs 4, 5, 6, 7, 8 v = Array(9, 10, 11) Debug.Print "call 3" varargs v ReDim v(0 To 2) v(0) = 12 v(1) = 13 v(2) = 14 Debug.Print "call 4" varargs 11, v Debug.Print "call 5" varargs v(2), v(1), v(0), 11 End Sub
VERSION 5.00 Begin VB.Form Form1 Caption = "Form1" ClientHeight = 2265 ClientLeft = 60 ClientTop = 600 ClientWidth = 2175 LinkTopic = "Form1" ScaleHeight = 2265 ScaleWidth = 2175 StartUpPosition = 3 'Windows Default Begin VB.CommandButton cmdDec Caption = "Decrement" Enabled = 0 'False Height = 495 Left = 120 TabIndex = 2 Top = 1680 Width = 1215 End Begin VB.CommandButton cmdInc Caption = "Increment" Height = 495 Left = 120 TabIndex = 1 Top = 1080 Width = 1215 End Begin VB.TextBox txtValue Height = 495 Left = 120 TabIndex = 0 Text = "0" Top = 240 Width = 1215 End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False '-----user-written code begins here; everything above this line is hidden in the GUI----- Private Sub cmdDec_Click() If Val(txtValue.Text) > 0 Then txtValue.Text = Val(txtValue.Text) - 1 End Sub Private Sub cmdInc_Click() If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1 End Sub Private Sub txtValue_Change() Select Case Val(txtValue.Text) Case Is < 0 txtValue.Enabled = False cmdInc.Enabled = True cmdDec.Enabled = False Case Is > 9 txtValue.Enabled = False cmdInc.Enabled = False cmdDec.Enabled = True Case 0 txtValue.Enabled = True cmdInc.Enabled = True cmdDec.Enabled = False Case Else txtValue.Enabled = False cmdInc.Enabled = True cmdDec.Enabled = True End Select End Sub
Set dict = CreateObject("Scripting.Dictionary") os = Array("Windows", "Linux", "MacOS") owner = Array("Microsoft", "<NAME>", "Apple") For n = 0 To 2 dict.Add os(n), owner(n) Next MsgBox dict.Item("Linux") MsgBox dict.Item("MacOS") MsgBox dict.Item("Windows")
<gh_stars>10-100 ' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor.CommandHandlers Imports Microsoft.CodeAnalysis.Editor.CSharp.CompleteStatement Imports Microsoft.CodeAnalysis.Editor.Implementation.Formatting Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Commanding Imports Microsoft.VisualStudio.Language.Intellisense Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Friend Class TestState Inherits AbstractCommandHandlerTestState Private Const timeoutMs = 60000 Private Const editorTimeoutMs = 60000 Friend Const RoslynItem = "RoslynItem" Friend ReadOnly EditorCompletionCommandHandler As ICommandHandler Friend ReadOnly CompletionPresenterProvider As ICompletionPresenterProvider Protected ReadOnly SessionTestState As IIntelliSenseTestState Private ReadOnly SignatureHelpBeforeCompletionCommandHandler As SignatureHelpBeforeCompletionCommandHandler Protected ReadOnly SignatureHelpAfterCompletionCommandHandler As SignatureHelpAfterCompletionCommandHandler Private ReadOnly FormatCommandHandler As FormatCommandHandler Protected ReadOnly CompleteStatementCommandHandler As CompleteStatementCommandHandler Public Shared ReadOnly CompositionWithoutCompletionTestParts As TestComposition = EditorTestCompositions.EditorFeaturesWpf. AddExcludedPartTypes( GetType(IIntelliSensePresenter(Of ISignatureHelpPresenterSession, ISignatureHelpSession)), GetType(FormatCommandHandler)). AddParts( GetType(TestSignatureHelpPresenter), GetType(IntelliSenseTestState), GetType(MockCompletionPresenterProvider)) Friend ReadOnly Property CurrentSignatureHelpPresenterSession As TestSignatureHelpPresenterSession Get Return SessionTestState.CurrentSignatureHelpPresenterSession End Get End Property ' Do not call directly. Use TestStateFactory Friend Sub New(workspaceElement As XElement, excludedTypes As IEnumerable(Of Type), extraExportedTypes As IEnumerable(Of Type), includeFormatCommandHandler As Boolean, workspaceKind As String, Optional makeSeparateBufferForCursor As Boolean = False, Optional roles As ImmutableArray(Of String) = Nothing) MyBase.New(workspaceElement, GetComposition(excludedTypes, extraExportedTypes, includeFormatCommandHandler), workspaceKind:=workspaceKind, makeSeparateBufferForCursor, roles) ' The current default timeout defined in the Editor may not work on slow virtual test machines. ' Need to use a safe timeout there to follow real code paths. MyBase.TextView.Options.GlobalOptions.SetOptionValue(DefaultOptions.ResponsiveCompletionThresholdOptionId, editorTimeoutMs) Dim languageServices = Me.Workspace.CurrentSolution.Projects.First().LanguageServices Dim language = languageServices.Language Me.SessionTestState = GetExportedValue(Of IIntelliSenseTestState)() Me.SignatureHelpBeforeCompletionCommandHandler = GetExportedValue(Of SignatureHelpBeforeCompletionCommandHandler)() Me.SignatureHelpAfterCompletionCommandHandler = GetExportedValue(Of SignatureHelpAfterCompletionCommandHandler)() Me.FormatCommandHandler = If(includeFormatCommandHandler, GetExportedValue(Of FormatCommandHandler)(), Nothing) Me.CompleteStatementCommandHandler = Workspace.ExportProvider.GetCommandHandler(Of CompleteStatementCommandHandler)(NameOf(CompleteStatementCommandHandler)) CompletionPresenterProvider = GetExportedValues(Of ICompletionPresenterProvider)(). Single(Function(e As ICompletionPresenterProvider) e.GetType().FullName = "Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense.MockCompletionPresenterProvider") EditorCompletionCommandHandler = GetExportedValues(Of ICommandHandler)(). Single(Function(e As ICommandHandler) e.GetType().Name = PredefinedCompletionNames.CompletionCommandHandler) End Sub Private Overloads Shared Function GetComposition( excludedTypes As IEnumerable(Of Type), extraExportedTypes As IEnumerable(Of Type), includeFormatCommandHandler As Boolean) As TestComposition Dim composition = CompositionWithoutCompletionTestParts. AddExcludedPartTypes(excludedTypes). AddParts(extraExportedTypes) If includeFormatCommandHandler Then composition = composition.AddParts(GetType(FormatCommandHandler)) End If Return composition End Function #Region "Editor Related Operations" Protected Overloads Sub ExecuteTypeCharCommand(args As TypeCharCommandArgs, finalHandler As Action, context As CommandExecutionContext, completionCommandHandler As IChainedCommandHandler(Of TypeCharCommandArgs)) Dim sigHelpHandler = DirectCast(SignatureHelpBeforeCompletionCommandHandler, IChainedCommandHandler(Of TypeCharCommandArgs)) Dim formatHandler = DirectCast(FormatCommandHandler, IChainedCommandHandler(Of TypeCharCommandArgs)) If formatHandler Is Nothing Then sigHelpHandler.ExecuteCommand( args, Sub() completionCommandHandler.ExecuteCommand( args, Sub() CompleteStatementCommandHandler.ExecuteCommand(args, finalHandler, context), context), context) Else formatHandler.ExecuteCommand( args, Sub() sigHelpHandler.ExecuteCommand( args, Sub() completionCommandHandler.ExecuteCommand( args, Sub() CompleteStatementCommandHandler.ExecuteCommand(args, finalHandler, context), context), context), context) End If End Sub Public Overloads Sub SendTab() Dim handler = GetHandler(Of IChainedCommandHandler(Of TabKeyCommandArgs))() MyBase.SendTab(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() EditorOperations.InsertText(vbTab)) End Sub Public Overloads Sub SendReturn() Dim handler = GetHandler(Of IChainedCommandHandler(Of ReturnKeyCommandArgs))() MyBase.SendReturn(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() EditorOperations.InsertNewLine()) End Sub Public Overrides Sub SendBackspace() Dim compHandler = GetHandler(Of IChainedCommandHandler(Of BackspaceKeyCommandArgs))() MyBase.SendBackspace(Sub(a, n, c) compHandler.ExecuteCommand(a, n, c), AddressOf MyBase.SendBackspace) End Sub Public Overrides Sub SendDelete() Dim compHandler = GetHandler(Of IChainedCommandHandler(Of DeleteKeyCommandArgs))() MyBase.SendDelete(Sub(a, n, c) compHandler.ExecuteCommand(a, n, c), AddressOf MyBase.SendDelete) End Sub Public Sub SendDeleteToSpecificViewAndBuffer(view As IWpfTextView, buffer As ITextBuffer) Dim compHandler = GetHandler(Of IChainedCommandHandler(Of DeleteKeyCommandArgs))() compHandler.ExecuteCommand(New DeleteKeyCommandArgs(view, buffer), AddressOf MyBase.SendDelete, TestCommandExecutionContext.Create()) End Sub Private Overloads Sub ExecuteTypeCharCommand(args As TypeCharCommandArgs, finalHandler As Action, context As CommandExecutionContext) Dim compHandler = GetHandler(Of IChainedCommandHandler(Of TypeCharCommandArgs))() ExecuteTypeCharCommand(args, finalHandler, context, compHandler) End Sub Public Overloads Sub SendTypeChars(typeChars As String) MyBase.SendTypeChars(typeChars, Sub(a, n, c) ExecuteTypeCharCommand(a, n, c)) End Sub Public Overloads Sub SendEscape() MyBase.SendEscape(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, Sub() SignatureHelpAfterCompletionCommandHandler.ExecuteCommand(a, n, c), c), Sub() Return) End Sub Public Overloads Sub SendDownKey() MyBase.SendDownKey( Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, Sub() SignatureHelpAfterCompletionCommandHandler.ExecuteCommand(a, n, c), c), Sub() EditorOperations.MoveLineDown(extendSelection:=False) End Sub) End Sub Public Overloads Sub SendUpKey() MyBase.SendUpKey( Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, Sub() SignatureHelpAfterCompletionCommandHandler.ExecuteCommand(a, n, c), c), Sub() EditorOperations.MoveLineUp(extendSelection:=False) End Sub) End Sub Public Overloads Sub SendPageUp() Dim handler = DirectCast(EditorCompletionCommandHandler, ICommandHandler(Of PageUpKeyCommandArgs)) MyBase.SendPageUp(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return) End Sub Public Overloads Sub SendCut() MyBase.SendCut(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return) End Sub Public Overloads Sub SendPaste() MyBase.SendPaste(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return) End Sub Public Overloads Sub SendInvokeCompletionList() MyBase.SendInvokeCompletionList(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return) End Sub Public Overloads Sub SendInsertSnippetCommand() MyBase.SendInsertSnippetCommand(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return) End Sub Public Overloads Sub SendSurroundWithCommand() MyBase.SendSurroundWithCommand(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return) End Sub Public Overloads Sub SendSave() MyBase.SendSave(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return) End Sub Public Overloads Sub SendSelectAll() MyBase.SendSelectAll(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return) End Sub Public Overrides Sub SendDeleteWordToLeft() Dim compHandler = DirectCast(EditorCompletionCommandHandler, ICommandHandler(Of WordDeleteToStartCommandArgs)) MyBase.SendWordDeleteToStart(Sub(a, n, c) compHandler.ExecuteCommand(a, n, c), AddressOf MyBase.SendDeleteWordToLeft) End Sub Public Overloads Sub SendToggleCompletionMode() Dim handler = DirectCast(EditorCompletionCommandHandler, ICommandHandler(Of ToggleCompletionModeCommandArgs)) MyBase.SendToggleCompletionMode(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return) End Sub Protected Function GetHandler(Of T As ICommandHandler)() As T Return DirectCast(EditorCompletionCommandHandler, T) End Function #End Region #Region "Completion Operations" Public Async Function SendCommitUniqueCompletionListItemAsync() As Task Await WaitForAsynchronousOperationsAsync() ' When we send the commit completion list item, it processes asynchronously; we can find out when it's complete ' by seeing that either the items are updated or the list is dismissed. We'll use a TaskCompletionSource to track ' when it's done which will release an async token. Dim sessionComplete = New TaskCompletionSource(Of Object)() Dim asynchronousOperationListenerProvider = Workspace.ExportProvider.GetExportedValue(Of AsynchronousOperationListenerProvider)() Dim asyncToken = asynchronousOperationListenerProvider.GetListener(FeatureAttribute.CompletionSet) _ .BeginAsyncOperation("SendCommitUniqueCompletionListItemAsync") #Disable Warning BC42358 ' Because this call is not awaited, execution of the current method continues before the call is completed sessionComplete.Task.CompletesAsyncOperation(asyncToken) #Enable Warning BC42358 ' Because this call is not awaited, execution of the current method continues before the call is completed Dim itemsUpdatedHandler = Sub(sender As Object, e As Data.ComputedCompletionItemsEventArgs) ' If there is 0 or more than one item left, then it means this was the filter operation that resulted and we're done. ' Otherwise we know a Dismiss operation is coming so we should wait for it. If e.Items.Items.Count() <> 1 Then Task.Run(Sub() Thread.Sleep(5000) sessionComplete.TrySetResult(Nothing) End Sub) End If End Sub Dim sessionDismissedHandler = Sub(sender As Object, e As EventArgs) sessionComplete.TrySetResult(Nothing) Dim session As IAsyncCompletionSession Dim addHandlers = Sub(sender As Object, e As Data.CompletionTriggeredEventArgs) AddHandler e.CompletionSession.ItemsUpdated, itemsUpdatedHandler AddHandler e.CompletionSession.Dismissed, sessionDismissedHandler session = e.CompletionSession End Sub Dim asyncCompletionBroker As IAsyncCompletionBroker = GetExportedValue(Of IAsyncCompletionBroker)() session = asyncCompletionBroker.GetSession(TextView) If session Is Nothing Then AddHandler asyncCompletionBroker.CompletionTriggered, addHandlers Else ' A session was already active so we'll fake the event addHandlers(asyncCompletionBroker, New Data.CompletionTriggeredEventArgs(session, TextView)) End If MyBase.SendCommitUniqueCompletionListItem(Sub(a, n, c) EditorCompletionCommandHandler.ExecuteCommand(a, n, c), Sub() Return) Await WaitForAsynchronousOperationsAsync() RemoveHandler session.ItemsUpdated, itemsUpdatedHandler RemoveHandler session.Dismissed, sessionDismissedHandler RemoveHandler asyncCompletionBroker.CompletionTriggered, addHandlers ' It's possible for the wait to bail and give up if it was clear nothing was completing; ensure we clean up our ' async token so as not to interfere with later tests. sessionComplete.TrySetResult(Nothing) End Function Public Async Function AssertNoCompletionSession() As Task Await WaitForAsynchronousOperationsAsync() Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView) If session Is Nothing Then Return End If If session.IsDismissed Then Return End If Dim completionItems = session.GetComputedItems(CancellationToken.None) ' During the computation we can explicitly dismiss the session or we can return no items. ' Each of these conditions mean that there is no active completion. Assert.True(session.IsDismissed OrElse completionItems.Items.Count() = 0, "AssertNoCompletionSession") End Function Public Sub AssertNoCompletionSessionWithNoBlock() Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView) If session Is Nothing Then Return End If If session.IsDismissed Then Return End If ' If completionItems cannot be calculated in 5 seconds, no session exists. Dim task1 = Task.Delay(5000) Dim task2 = Task.Run( Sub() Dim completionItems = session.GetComputedItems(CancellationToken.None) ' In the non blocking mode, we are not interested for a session appeared later than in 5 seconds. If task1.Status = TaskStatus.Running Then ' During the computation we can explicitly dismiss the session or we can return no items. ' Each of these conditions mean that there is no active completion. Assert.True(session.IsDismissed OrElse completionItems.Items.Count() = 0) End If End Sub) Task.WaitAny(task1, task2) End Sub Public Async Function AssertCompletionSession(Optional projectionsView As ITextView = Nothing) As Task Await WaitForAsynchronousOperationsAsync() Dim view = If(projectionsView, TextView) Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(view) Assert.NotNull(session) End Function Public Async Function AssertCompletionItemsDoNotContainAny(ParamArray displayText As String()) As Task Await WaitForAsynchronousOperationsAsync() Dim items = GetCompletionItems() Assert.False(displayText.Any(Function(v) items.Any(Function(i) i.DisplayText = v))) End Function Public Async Function AssertCompletionItemsContainAll(ParamArray displayText As String()) As Task Await WaitForAsynchronousOperationsAsync() Dim items = GetCompletionItems() Assert.True(displayText.All(Function(v) items.Any(Function(i) i.DisplayText = v))) End Function Public Async Function AssertCompletionItemsContain(displayText As String, displayTextSuffix As String) As Task Await WaitForAsynchronousOperationsAsync() Dim items = GetCompletionItems() Assert.True(items.Any(Function(i) i.DisplayText = displayText AndAlso i.DisplayTextSuffix = displayTextSuffix)) End Function Public Sub AssertItemsInOrder(expectedOrder As String()) Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView) Assert.NotNull(session) Dim items = session.GetComputedItems(CancellationToken.None).Items Assert.Equal(expectedOrder.Count, items.Count) For i = 0 To expectedOrder.Count - 1 Assert.Equal(expectedOrder(i), items(i).DisplayText) Next End Sub Public Sub AssertItemsInOrder(expectedOrder As (String, String)()) Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView) Assert.NotNull(session) Dim items = session.GetComputedItems(CancellationToken.None).Items Assert.Equal(expectedOrder.Count, items.Count) For i = 0 To expectedOrder.Count - 1 Assert.Equal(expectedOrder(i).Item1, items(i).DisplayText) Assert.Equal(expectedOrder(i).Item2, items(i).Suffix) Next End Sub Public Async Function AssertSelectedCompletionItem( Optional displayText As String = Nothing, Optional displayTextSuffix As String = Nothing, Optional description As String = Nothing, Optional isSoftSelected As Boolean? = Nothing, Optional isHardSelected As Boolean? = Nothing, Optional shouldFormatOnCommit As Boolean? = Nothing, Optional inlineDescription As String = Nothing, Optional automationText As String = Nothing, Optional projectionsView As ITextView = Nothing) As Task Await WaitForAsynchronousOperationsAsync() Dim view = If(projectionsView, TextView) Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(view) Assert.NotNull(session) Dim items = session.GetComputedItems(CancellationToken.None) If isSoftSelected.HasValue Then If isSoftSelected.Value Then Assert.True(items.UsesSoftSelection, "Current completion is not soft-selected. Expected: soft-selected") Else Assert.False(items.UsesSoftSelection, "Current completion is soft-selected. Expected: not soft-selected") End If End If If isHardSelected.HasValue Then If isHardSelected.Value Then Assert.True(Not items.UsesSoftSelection, "Current completion is not hard-selected. Expected: hard-selected") Else Assert.True(items.UsesSoftSelection, "Current completion is hard-selected. Expected: not hard-selected") End If End If If displayText IsNot Nothing Then Assert.NotNull(items.SelectedItem) If displayTextSuffix IsNot Nothing Then Assert.NotNull(items.SelectedItem) Assert.Equal(displayText + displayTextSuffix, items.SelectedItem.DisplayText) Else Assert.Equal(displayText, items.SelectedItem.DisplayText) End If End If If shouldFormatOnCommit.HasValue Then Assert.Equal(shouldFormatOnCommit.Value, GetRoslynCompletionItem(items.SelectedItem).Rules.FormatOnCommit) End If If description IsNot Nothing Then Dim itemDescription = Await GetSelectedItemDescriptionAsync() Assert.Equal(description, itemDescription.Text) End If If inlineDescription IsNot Nothing Then Assert.Equal(inlineDescription, items.SelectedItem.Suffix) End If If automationText IsNot Nothing Then Assert.Equal(automationText, items.SelectedItem.AutomationText) End If End Function Public Async Function GetSelectedItemDescriptionAsync() As Task(Of CompletionDescription) Dim document = Me.Workspace.CurrentSolution.Projects.First().Documents.First() Dim service = CompletionService.GetService(document) Dim roslynItem = GetSelectedItem() Return Await service.GetDescriptionAsync(document, roslynItem) End Function Public Sub AssertCompletionItemExpander(isAvailable As Boolean, isSelected As Boolean) Dim presenter = DirectCast(CompletionPresenterProvider.GetOrCreate(Me.TextView), MockCompletionPresenter) Dim expander = presenter.GetExpander() If Not isAvailable Then Assert.False(isSelected) Assert.Null(expander) Else Assert.NotNull(expander) Assert.Equal(expander.IsSelected, isSelected) End If End Sub Public Sub SetCompletionItemExpanderState(isSelected As Boolean) Dim presenter = DirectCast(CompletionPresenterProvider.GetOrCreate(Me.TextView), MockCompletionPresenter) Dim expander = presenter.GetExpander() Assert.NotNull(expander) presenter.SetExpander(isSelected) End Sub Public Async Function AssertSessionIsNothingOrNoCompletionItemLike(text As String) As Task Await WaitForAsynchronousOperationsAsync() Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView) If Not session Is Nothing Then Await AssertCompletionItemsDoNotContainAny(text) End If End Function Public Function GetSelectedItem() As CompletionItem Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView) Assert.NotNull(session) Dim items = session.GetComputedItems(CancellationToken.None) Return GetRoslynCompletionItem(items.SelectedItem) End Function Public Sub CalculateItemsIfSessionExists() Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView) If session IsNot Nothing Then Dim item = session.GetComputedItems(CancellationToken.None).SelectedItem End If End Sub Public Function GetCompletionItems() As IList(Of CompletionItem) Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView) Assert.NotNull(session) Return session.GetComputedItems(CancellationToken.None).Items.Select(Function(item) GetRoslynCompletionItem(item)).ToList() End Function Private Shared Function GetRoslynCompletionItem(item As Data.CompletionItem) As CompletionItem Return If(item IsNot Nothing, DirectCast(item.Properties(RoslynItem), CompletionItem), Nothing) End Function Public Sub RaiseFiltersChanged(args As ImmutableArray(Of Data.CompletionFilterWithState)) Dim presenter = DirectCast(CompletionPresenterProvider.GetOrCreate(Me.TextView), MockCompletionPresenter) Dim newArgs = New Data.CompletionFilterChangedEventArgs(args) presenter.TriggerFiltersChanged(Me, newArgs) End Sub Public Function GetCompletionItemFilters() As ImmutableArray(Of Data.CompletionFilterWithState) Dim presenter = DirectCast(CompletionPresenterProvider.GetOrCreate(Me.TextView), MockCompletionPresenter) Return presenter.GetFilters() End Function Public Function HasSuggestedItem() As Boolean Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView) Assert.NotNull(session) Dim computedItems = session.GetComputedItems(CancellationToken.None) Return computedItems.SuggestionItem IsNot Nothing End Function Public Function IsSoftSelected() As Boolean Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView) Assert.NotNull(session) Dim computedItems = session.GetComputedItems(CancellationToken.None) Return computedItems.UsesSoftSelection End Function Public Sub SendSelectCompletionItem(displayText As String) Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView) Dim operations = DirectCast(session, IAsyncCompletionSessionOperations) operations.SelectCompletionItem(session.GetComputedItems(CancellationToken.None).Items.Single(Function(i) i.DisplayText = displayText)) End Sub Public Async Function WaitForUIRenderedAsync() As Task Await WaitForAsynchronousOperationsAsync() Dim tcs = New TaskCompletionSource(Of Boolean) Dim presenter = DirectCast(CompletionPresenterProvider.GetOrCreate(TextView), MockCompletionPresenter) Dim uiUpdated As EventHandler(Of Data.CompletionItemSelectedEventArgs) uiUpdated = Sub() RemoveHandler presenter.UiUpdated, uiUpdated tcs.TrySetResult(True) End Sub AddHandler presenter.UiUpdated, uiUpdated Dim ct = New CancellationTokenSource(timeoutMs) ct.Token.Register(Sub() tcs.TrySetCanceled(), useSynchronizationContext:=False) Await tcs.Task.ConfigureAwait(True) End Function Public Overloads Sub SendTypeCharsToSpecificViewAndBuffer(typeChars As String, view As IWpfTextView, buffer As ITextBuffer) For Each ch In typeChars Dim localCh = ch ExecuteTypeCharCommand(New TypeCharCommandArgs(view, buffer, localCh), Sub() EditorOperations.InsertText(localCh.ToString()), TestCommandExecutionContext.Create()) Next End Sub Public Async Function AssertLineTextAroundCaret(expectedTextBeforeCaret As String, expectedTextAfterCaret As String) As Task Await WaitForAsynchronousOperationsAsync() Dim actual = GetLineTextAroundCaretPosition() Assert.Equal(expectedTextBeforeCaret, actual.TextBeforeCaret) Assert.Equal(expectedTextAfterCaret, actual.TextAfterCaret) End Function Public Sub NavigateToDisplayText(targetText As String) Dim currentText = GetSelectedItem().DisplayText ' GetComputedItems provided by the Editor for tests does not guarantee that ' the order of items match the order of items actually displayed in the completion popup. ' For example, they put starred items (intellicode) below non-starred ones. ' And the order they display those items in the UI is opposite. ' Therefore, we do the full traverse: down to the bottom and if not found up to the top. Do While currentText <> targetText SendDownKey() Dim newText = GetSelectedItem().DisplayText If currentText = newText Then ' Nothing found on going down. Try going up Do While currentText <> targetText SendUpKey() newText = GetSelectedItem().DisplayText Assert.True(newText <> currentText, "Reached the bottom, then the top and didn't find the match") currentText = newText Loop End If currentText = newText Loop End Sub #End Region #Region "Signature Help Operations" Public Overloads Sub SendInvokeSignatureHelp() Dim handler = DirectCast(SignatureHelpBeforeCompletionCommandHandler, IChainedCommandHandler(Of InvokeSignatureHelpCommandArgs)) MyBase.SendInvokeSignatureHelp(Sub(a, n, c) handler.ExecuteCommand(a, n, c), Sub() Return) End Sub Public Overloads Async Function AssertNoSignatureHelpSession(Optional block As Boolean = True) As Task If block Then Await WaitForAsynchronousOperationsAsync() End If Assert.Null(Me.CurrentSignatureHelpPresenterSession) End Function Public Overloads Async Function AssertSignatureHelpSession() As Task Await WaitForAsynchronousOperationsAsync() Assert.NotNull(Me.CurrentSignatureHelpPresenterSession) End Function Public Overloads Function GetSignatureHelpItems() As IList(Of SignatureHelpItem) Return CurrentSignatureHelpPresenterSession.SignatureHelpItems End Function Public Async Function AssertSignatureHelpItemsContainAll(displayText As String()) As Task Await WaitForAsynchronousOperationsAsync() Assert.True(displayText.All(Function(v) CurrentSignatureHelpPresenterSession.SignatureHelpItems.Any( Function(i) GetDisplayText(i, CurrentSignatureHelpPresenterSession.SelectedParameter.Value) = v))) End Function Public Async Function AssertSelectedSignatureHelpItem(Optional displayText As String = Nothing, Optional documentation As String = Nothing, Optional selectedParameter As String = Nothing) As Task Await WaitForAsynchronousOperationsAsync() If displayText IsNot Nothing Then Assert.Equal(displayText, GetDisplayText(Me.CurrentSignatureHelpPresenterSession.SelectedItem, Me.CurrentSignatureHelpPresenterSession.SelectedParameter.Value)) End If If documentation IsNot Nothing Then Assert.Equal(documentation, Me.CurrentSignatureHelpPresenterSession.SelectedItem.DocumentationFactory(CancellationToken.None).GetFullText()) End If If selectedParameter IsNot Nothing Then Assert.Equal(selectedParameter, GetDisplayText( Me.CurrentSignatureHelpPresenterSession.SelectedItem.Parameters( Me.CurrentSignatureHelpPresenterSession.SelectedParameter.Value).DisplayParts)) End If End Function #End Region #Region "Helpers" Private Shared Function GetDisplayText(item As SignatureHelpItem, selectedParameter As Integer) As String Dim suffix = If(selectedParameter < item.Parameters.Count, GetDisplayText(item.Parameters(selectedParameter).SuffixDisplayParts), String.Empty) Return String.Join( String.Empty, GetDisplayText(item.PrefixDisplayParts), String.Join( GetDisplayText(item.SeparatorDisplayParts), item.Parameters.Select(Function(p) GetDisplayText(p.DisplayParts))), GetDisplayText(item.SuffixDisplayParts), suffix) End Function Private Shared Function GetDisplayText(parts As IEnumerable(Of TaggedText)) As String Return String.Join(String.Empty, parts.Select(Function(p) p.ToString())) End Function #End Region End Class End Namespace
option explicit function eef( b, r1, r2 ) if b then eef = r1 else eef = r2 end if end function dim a, b wscript.stdout.write "First integer: " a = cint(wscript.stdin.readline) 'force to integer wscript.stdout.write "Second integer: " b = cint(wscript.stdin.readline) 'force to integer wscript.stdout.write "First integer is " if a < b then wscript.stdout.write "less than " if a = b then wscript.stdout.write "equal to " if a > b then wscript.stdout.write "greater than " wscript.echo "Second integer." wscript.stdout.write "First integer is " & _ eef( a < b, "less than ", _ eef( a = b, "equal to ", _ eef( a > b, "greater than ", vbnullstring ) ) ) & "Second integer."
Option Explicit Main Sub Main Dim oCluster Dim oTestRes Set oCluster = CreateObject("MSCluster.Cluster") oCluster.Open ("10.0.0.1") Set oTestRes = oCluster.ResourceTypes.Item("8TestRes") oTestRes.Delete End Sub
<filename>inetsrv/iis/svcs/nntp/adminsso/scripts/rgroup.vbs REM REM LOCALIZATION REM L_SWITCH_OPERATION = "-t" L_SWITCH_SERVER = "-s" L_SWITCH_INSTANCE_ID = "-v" L_SWITCH_NEWSGROUP = "-g" L_SWITCH_MAX_RESULTS = "-n" L_SWITCH_MODERATOR = "-m" L_SWITCH_DESCRIPTION = "-d" L_SWITCH_READ_ONLY = "-r" L_SWITCH_DEFAULT_MODERATOR = "-u" L_SWITCH_PRETTY_NAME = "-p" L_SWITCH_CREATION_TIME = "-c" L_SWITCH_LOADACTIVE = "-a" L_OP_FIND = "f" L_OP_ADD = "a" L_OP_DELETE = "d" L_OP_GET = "g" L_OP_SET = "s" L_OP_LOAD = "l" L_DESC_PROGRAM = "rgroup - Manipulate NNTP newsgroups" L_DESC_ADD = "Add a newsgroup" L_DESC_DELETE = "Delete a newsgroup" L_DESC_GET = "Get a newsgroup's properties" L_DESC_SET = "Set a newsgroup's properties" L_DESC_FIND = "Find newsgroups" L_DESC_LOAD = "Load groups from active file" L_DESC_OPERATIONS = "<operations>" L_DESC_SERVER = "<server> Specify computer to configure" L_DESC_INSTANCE_ID = "<virtual server id> Specify virtual server id" L_DESC_NEWSGROUP = "<newsgroup name>" L_DESC_MAX_RESULTS = "<number of results>" L_DESC_MODERATOR = "<moderator email address>" L_DESC_DESCRIPTION = "<newsgroup description>" L_DESC_READ_ONLY = "<true/false> read-only newsgroup?" L_DESC_DEFAULT_MODERATOR = "<true/false> moderated by default moderator?" L_DESC_PRETTY_NAME = "<prettyname> response to LIST PRETTYNAMES" L_DESC_CREATION_TIME = "<date> Newsgroup creation time" L_DESC_LOADACTIVE = "<filename> name of active file" L_DESC_EXAMPLES = "Examples:" L_DESC_EXAMPLE1 = "rgroup.vbs -t f -g alt.*" L_DESC_EXAMPLE2 = "rgroup.vbs -t a -g my.new.group" L_DESC_EXAMPLE3 = "rgroup.vbs -t d -g my.old.group" L_DESC_EXAMPLE4 = "rgroup.vbs -t s -g my.old.group -p GreatGroup -m <EMAIL>" L_DESC_EXAMPLE5 = "rgroup.vbs -t l -a active.txt" L_STR_GROUP_NAME = "Newsgroup:" L_STR_GROUP_DESCRIPTION = "Description:" L_STR_GROUP_MODERATOR = "Moderator:" L_STR_GROUP_READ_ONLY = "Read only:" L_STR_GROUP_PRETTY_NAME = "Prettyname:" L_STR_GROUP_CREATION_TIME = "Creation time:" L_STR_NUM_MATCHING_GROUPS = "Number of matching groups:" L_ERR_MUST_ENTER_NEWSGROUP = "You must enter a newsgroup name" REM REM END LOCALIZATION REM REM REM --- Globals --- REM dim g_dictParms dim g_admin set g_dictParms = CreateObject ( "Scripting.Dictionary" ) set g_admin = CreateObject ( "NntpAdm.Groups" ) REM REM --- Set argument defaults --- REM g_dictParms(L_SWITCH_OPERATION) = "" g_dictParms(L_SWITCH_SERVER) = "" g_dictParms(L_SWITCH_INSTANCE_ID) = "1" g_dictParms(L_SWITCH_NEWSGROUP) = "" g_dictParms(L_SWITCH_MAX_RESULTS) = "1000000" g_dictParms(L_SWITCH_MODERATOR) = "" g_dictParms(L_SWITCH_DESCRIPTION) = "" g_dictParms(L_SWITCH_READ_ONLY) = "" g_dictParms(L_SWITCH_DEFAULT_MODERATOR) = "" g_dictParms(L_SWITCH_PRETTY_NAME) = "" g_dictParms(L_SWITCH_CREATION_TIME) = "" g_dictParms(L_SWITCH_LOADACTIVE) = "" REM REM --- Begin Main Program --- REM if NOT ParseCommandLine ( g_dictParms, WScript.Arguments ) then usage WScript.Quit ( 0 ) end if dim strNewsgroup dim i dim id dim index REM REM Debug: print out command line arguments: REM REM switches = g_dictParms.keys REM args = g_dictParms.items REM REM REM for i = 0 to g_dictParms.Count - 1 REM WScript.echo switches(i) & " = " & args(i) REM next REM g_admin.Server = g_dictParms(L_SWITCH_SERVER) g_admin.ServiceInstance = g_dictParms(L_SWITCH_INSTANCE_ID) strNewsgroup = g_dictParms(L_SWITCH_NEWSGROUP) strActiveFile = g_dictParms(L_SWITCH_LOADACTIVE) select case g_dictParms(L_SWITCH_OPERATION) case L_OP_FIND REM REM Find newsgroups: REM if strNewsgroup = "" then WScript.Echo L_ERR_MUST_ENTER_NEWSGROUP WScript.Quit 0 end if g_admin.Find strNewsgroup, g_dictParms(L_SWITCH_MAX_RESULTS) cGroups = g_admin.Count WScript.Echo L_STR_NUM_MATCHING_GROUPS & " " & cGroups for i = 0 to cGroups - 1 WScript.Echo g_admin.MatchingGroup ( i ) next case L_OP_ADD if strNewsgroup = "" then WScript.Echo L_ERR_MUST_ENTER_NEWSGROUP WScript.Quit 0 end if g_admin.Default if g_dictParms(L_SWITCH_READ_ONLY) = "" then g_dictParms(L_SWITCH_READ_ONLY) = FALSE end if if g_dictParms(L_SWITCH_DEFAULT_MODERATOR) = "" then g_dictParms(L_SWITCH_DEFAULT_MODERATOR) = FALSE end if if g_dictParms(L_SWITCH_DEFAULT_MODERATOR) then g_admin.IsModerated = BooleanToBOOL ( TRUE ) elseif g_dictParms(L_SWITCH_MODERATOR) <> "" then g_admin.IsModerated = BooleanToBOOL ( TRUE ) g_admin.Moderator = g_dictParms(L_SWITCH_MODERATOR) else g_admin.IsModerated = BooleanToBOOL ( FALSE ) g_admin.Moderator = "" end if g_admin.Newsgroup = strNewsgroup g_admin.ReadOnly = BooleanToBOOL (g_dictParms (L_SWITCH_READ_ONLY)) g_admin.Description = g_dictParms(L_SWITCH_DESCRIPTION) g_admin.PrettyName = g_dictParms(L_SWITCH_PRETTY_NAME) On Error Resume Next g_admin.Add if ( Err.Number <> 0 ) then WScript.echo " Error creating group: " & Err.Description & "(" & Err.Number & ")" else PrintNewsgroup g_admin end if case L_OP_LOAD if strActiveFile = "" then WScript.Echo L_ERR_MUST_ENTER_ACTIVEFILE WScript.Quit 0 end if set pFS = WScript.CreateObject("Scripting.FileSystemObject") set pActiveFile = pFS.GetFile(strActiveFile) set pActiveFileStream = pActiveFile.OpenAsTextStream() fInList = 0 WScript.echo "Creating groups:" while not pActiveFileStream.AtEndOfStream szLine = pActiveFileStream.ReadLine Dim rgLine rgLine = Split(szLine) if (szLine = ".") then fInList = 0 if (fInList) then WScript.echo " " & rgLine(0) g_admin.Default g_admin.Newsgroup = rgLine(0) On Error Resume Next g_admin.Add if (Err.Number <> 0) then WScript.echo " Error creating " & rgLine(0) & ": " & Err.Description & "(" & Err.Number & ")" end if end if if (rgLine(0) = "215") then fInList = 1 wend WScript.echo "Done" case L_OP_DELETE if strNewsgroup = "" then WScript.Echo L_ERR_MUST_ENTER_NEWSGROUP WScript.Quit 0 end if On Error Resume Next g_admin.Remove strNewsgroup if ( Err.Number <> 0 ) then WScript.echo " Error deleting group: " & Err.Description & "(" & Err.Number & ")" end if case L_OP_GET if strNewsgroup = "" then WScript.Echo L_ERR_MUST_ENTER_NEWSGROUP WScript.Quit 0 end if On Error Resume Next g_admin.Get strNewsgroup if ( Err.Number <> 0 ) then WScript.echo " Error getting group: " & Err.Descriptino & "(" & Err.Number & ")" else PrintNewsgroup g_admin end if case L_OP_SET if strNewsgroup = "" then WScript.Echo L_ERR_MUST_ENTER_NEWSGROUP WScript.Quit 0 end if On Error Resume Next g_admin.Get strNewsgroup if ( Err.Number <> 0 ) then if g_dictParms(L_SWITCH_MODERATOR) = "" then g_dictParms(L_SWITCH_MODERATOR) = g_admin.Moderator end if if g_dictParms(L_SWITCH_DESCRIPTION) = "" then g_dictParms(L_SWITCH_DESCRIPTION) = g_admin.Description end if if g_dictParms(L_SWITCH_READ_ONLY) = "" then g_dictParms(L_SWITCH_READ_ONLY) = BOOLToBoolean (g_admin.ReadOnly) end if if g_dictParms(L_SWITCH_DEFAULT_MODERATOR) = "" then g_dictParms(L_SWITCH_DEFAULT_MODERATOR) = FALSE end if if g_dictParms(L_SWITCH_PRETTY_NAME) = "" then g_dictParms(L_SWITCH_PRETTY_NAME) = g_admin.PrettyName end if if g_dictParms(L_SWITCH_CREATION_TIME) = "" then g_dictParms(L_SWITCH_CREATION_TIME) = g_admin.CreationTime end if if ( g_dictParms(L_SWITCH_DEFAULT_MODERATOR) ) then g_admin.IsModerated = BooleanToBOOL ( TRUE ) g_admin.Moderator = "" elseif g_dictParms(L_SWITCH_MODERATOR) <> "" then g_admin.IsModerated = BooleanToBOOL ( TRUE ) g_admin.Moderator = g_dictParms(L_SWITCH_MODERATOR) else g_admin.IsModerated = BooleanToBOOL ( FALSE ) g_admin.Moderator = "" end if g_admin.ReadOnly = BooleanToBOOL (g_dictParms (L_SWITCH_READ_ONLY)) g_admin.Description = g_dictParms(L_SWITCH_DESCRIPTION) g_admin.PrettyName = g_dictParms(L_SWITCH_PRETTY_NAME) g_admin.CreationTime = g_dictParms(L_SWITCH_CREATION_TIME) g_admin.Set PrintNewsgroup g_admin else WScript.echo "Error setting group: " & Err.Description & "(" & Err.Number & ")" end if case else usage end select WScript.Quit 0 REM REM --- End Main Program --- REM REM REM ParseCommandLine ( dictParameters, cmdline ) REM Parses the command line parameters into the given dictionary REM REM Arguments: REM dictParameters - A dictionary containing the global parameters REM cmdline - Collection of command line arguments REM REM Returns - Success code REM Function ParseCommandLine ( dictParameters, cmdline ) dim fRet dim cArgs dim i dim strSwitch dim strArgument fRet = TRUE cArgs = cmdline.Count i = 0 do while (i < cArgs) REM REM Parse the switch and its argument REM if i + 1 >= cArgs then REM REM Not enough command line arguments - Fail REM fRet = FALSE exit do end if strSwitch = cmdline(i) i = i + 1 strArgument = cmdline(i) i = i + 1 REM REM Add the switch,argument pair to the dictionary REM if NOT dictParameters.Exists ( strSwitch ) then REM REM Bad switch - Fail REM fRet = FALSE exit do end if dictParameters(strSwitch) = strArgument loop ParseCommandLine = fRet end function REM REM Usage () REM prints out the description of the command line arguments REM Sub Usage WScript.Echo L_DESC_PROGRAM WScript.Echo vbTab & L_SWITCH_OPERATION & " " & L_DESC_OPERATIONS WScript.Echo vbTab & vbTab & L_OP_FIND & vbTab & L_DESC_FIND WScript.Echo vbTab & vbTab & L_OP_ADD & vbTab & L_DESC_ADD WScript.Echo vbTab & vbTab & L_OP_DELETE & vbTab & L_DESC_DELETE WScript.Echo vbTab & vbTab & L_OP_GET & vbTab & L_DESC_GET WScript.Echo vbTab & vbTab & L_OP_SET & vbTab & L_DESC_SET WScript.Echo vbTab & vbTab & L_OP_LOAD & vbTab & L_DESC_LOAD WScript.Echo vbTab & L_SWITCH_SERVER & " " & L_DESC_SERVER WScript.Echo vbTab & L_SWITCH_INSTANCE_ID & " " & L_DESC_INSTANCE_ID WScript.Echo vbTab & L_SWITCH_NEWSGROUP & " " & L_DESC_NEWSGROUP WScript.Echo vbTab & L_SWITCH_MAX_RESULTS & " " & L_DESC_MAX_RESULTS WScript.Echo vbTab & L_SWITCH_MODERATOR & " " & L_DESC_MODERATOR WScript.Echo vbTab & L_SWITCH_DESCRIPTION & " " & L_DESC_DESCRIPTION WScript.Echo vbTab & L_SWITCH_READ_ONLY & " " & L_DESC_READ_ONLY WScript.Echo vbTab & L_SWITCH_DEFAULT_MODERATOR & " " & L_DESC_DEFAULT_MODERATOR WScript.Echo vbTab & L_SWITCH_PRETTY_NAME & " " & L_DESC_PRETTY_NAME WScript.Echo vbTab & L_SWITCH_CREATION_TIME & " " & L_DESC_CREATION_TIME WScript.Echo vbTab & L_SWITCH_LOADACTIVE & " " & L_DESC_LOADACTIVE WScript.Echo WScript.Echo L_DESC_EXAMPLES WScript.Echo L_DESC_EXAMPLE1 WScript.Echo L_DESC_EXAMPLE2 WScript.Echo L_DESC_EXAMPLE3 WScript.Echo L_DESC_EXAMPLE4 WScript.Echo L_DESC_EXAMPLE5 end sub Sub PrintNewsgroup ( admobj ) WScript.Echo L_STR_GROUP_NAME & " " & admobj.Newsgroup WScript.Echo L_STR_GROUP_DESCRIPTION & " " & admobj.Description WScript.Echo L_STR_GROUP_MODERATOR & " " & admobj.Moderator WScript.Echo L_STR_GROUP_READ_ONLY & " " & BOOLToBoolean (admobj.ReadOnly) WScript.Echo L_STR_GROUP_PRETTY_NAME & " " & admobj.PrettyName WScript.Echo L_STR_GROUP_CREATION_TIME & " " & admobj.CreationTime end sub Function BooleanToBOOL ( b ) if b then BooleanToBOOL = 1 else BooleanToBOOL = 0 end if end function Function BOOLToBoolean ( b ) BOOLToBoolean = (b = 1) end function
on error resume next const wbemPrivilegeCreateToken = 1 const wbemPrivilegePrimaryToken = 2 const wbemPrivilegeLockMemory = 3 const wbemPrivilegeIncreaseQuota = 4 const wbemPrivilegeMachineAccount = 5 const wbemPrivilegeTcb = 6 const wbemPrivilegeSecurity = 7 const wbemPrivilegeTakeOwnership = 8 const wbemPrivilegeLoadDriver = 9 const wbemPrivilegeSystemProfile = 10 const wbemPrivilegeSystemtime = 11 const wbemPrivilegeProfileSingleProcess = 12 const wbemPrivilegeIncreaseBasePriority = 13 const wbemPrivilegeCreatePagefile = 14 const wbemPrivilegeCreatePermanent = 15 const wbemPrivilegeBackup = 16 const wbemPrivilegeRestore = 17 const wbemPrivilegeShutdown = 18 const wbemPrivilegeDebug = 19 const wbemPrivilegeAudit = 20 const wbemPrivilegeSystemEnvironment = 21 const wbemPrivilegeChangeNotify = 22 const wbemPrivilegeRemoteShutdown = 23 set service = getobject ("winmgmts:{(security)}!root/scenario26") service.security_.privileges.Add wbemPrivilegeCreateToken service.security_.privileges.Add wbemPrivilegePrimaryToken service.security_.privileges.Add wbemPrivilegeLockMemory service.security_.privileges.Add wbemPrivilegeIncreaseQuota service.security_.privileges.Add wbemPrivilegeMachineAccount service.security_.privileges.Add wbemPrivilegeTcb service.security_.privileges.Add wbemPrivilegeTakeOwnership service.security_.privileges.Add wbemPrivilegeLoadDriver service.security_.privileges.Add wbemPrivilegeSystemProfile service.security_.privileges.Add wbemPrivilegeSystemTime service.security_.privileges.Add wbemPrivilegeProfileSingleProcess service.security_.privileges.Add wbemPrivilegeIncreaseBasePriority service.security_.privileges.Add wbemPrivilegeCreatePagefile service.security_.privileges.Add wbemPrivilegeCreatePermanent service.security_.privileges.Add wbemPrivilegeBackup service.security_.privileges.Add wbemPrivilegeRestore service.security_.privileges.Add wbemPrivilegeShutdown service.security_.privileges.Add wbemPrivilegeDebug service.security_.privileges.Add wbemPrivilegeAudit service.security_.privileges.Add wbemPrivilegeSystemEnvironment service.security_.privileges.Add wbemPrivilegeChangeNotify, false service.security_.privileges.Add wbemPrivilegeRemoteShutdown set obj = service.get ("Scenario26.key=""x""") if err <> 0 then WScript.Echo Hex(Err.Number), Err.Description end if
<reponame>npocmaka/Windows-Server-2003<filename>drivers/storage/wmiprov/vds/test/scripts/exclautochk.vbs '//on error resume next strNamespace = "winmgmts://./root/cimv2" set objArgs = wscript.Arguments if objArgs.count < 1 then wscript.echo "Usage exclAutoChk volume1 [volume2 ...]" wscript.quit(1) end if Dim astrVolumes() Redim astrVolumes(objArgs.count-1) For i = 0 to objArgs.count-1 astrVolumes(i) = objArgs(i) Next set Volume = GetObject(strNamespace & ":Win32_Volume") Result = Volume.ExcludeFromAutoChk(astrVolumes) strMessage = MapErrorCode("Win32_Volume", "ExcludeFromAutoChk", Result) wscript.echo "Volume.ExcludeFromAutoChk 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
<reponame>JavascriptID/sourcerer-app ' ------------------------------------------------------------------------- ' Distributed by VXIplug&play Systems Alliance ' Do not modify the contents of this file. ' ------------------------------------------------------------------------- ' Title : VPPTYPE.BAS ' Date : 02-14-95 ' Purpose : VXIplug&play instrument driver header file ' ------------------------------------------------------------------------- Global Const VI_NULL = 0 Global Const VI_TRUE = 1 Global Const VI_FALSE = 0 ' - Completion and Error Codes -------------------------------------------- Global Const VI_WARN_NSUP_ID_QUERY = &H3FFC0101& Global Const VI_WARN_NSUP_RESET = &H3FFC0102& Global Const VI_WARN_NSUP_SELF_TEST = &H3FFC0103& Global Const VI_WARN_NSUP_ERROR_QUERY = &H3FFC0104& Global Const VI_WARN_NSUP_REV_QUERY = &H3FFC0105& Global Const VI_ERROR_PARAMETER1 = &HBFFC0001& Global Const VI_ERROR_PARAMETER2 = &HBFFC0002& Global Const VI_ERROR_PARAMETER3 = &HBFFC0003& Global Const VI_ERROR_PARAMETER4 = &HBFFC0004& Global Const VI_ERROR_PARAMETER5 = &HBFFC0005& Global Const VI_ERROR_PARAMETER6 = &HBFFC0006& Global Const VI_ERROR_PARAMETER7 = &HBFFC0007& Global Const VI_ERROR_PARAMETER8 = &HBFFC0008& Global Const VI_ERROR_FAIL_ID_QUERY = &HBFFC0011& Global Const VI_ERROR_INV_RESPONSE = &HBFFC0012& ' - Additional Definitions ------------------------------------------------ Global Const VI_ON = 1 Global Const VI_OFF = 0
<reponame>npocmaka/Windows-Server-2003<gh_stars>10-100 on error resume next set service = GetObject("winmgmts:/root") if err <> 0 then WScript.Echo err.Description, Err.Number, Err.source end if
<filename>Task/String-append/VBA/string-append.vba Function StringAppend() Dim s As String s = "foo" s = s & "bar" Debug.Print s End Function
Private Function zeckendorf(ByVal n As Integer) As Integer Dim r As Integer: r = 0 Dim c As Integer Dim fib As New Collection fib.Add 1 fib.Add 1 Do While fib(fib.Count) < n fib.Add fib(fib.Count - 1) + fib(fib.Count) Loop For i = fib.Count To 2 Step -1 c = n >= fib(i) r = r + r - c n = n + c * fib(i) Next i zeckendorf = r End Function Public Sub main() Dim i As Integer For i = 0 To 20 Debug.Print Format(i, "@@"); ":"; Format(WorksheetFunction.Dec2Bin(zeckendorf(i)), "@@@@@@@") Next i End Sub
<filename>admin/wmi/wbem/scripting/test/vbscript/servmkr.vbs on error resume next set service = GetObject("winmgmts://ludlow") if err <> 0 then WScript.Echo err.description, err.number, err.source end if
<filename>admin/wmi/wbem/scripting/test/vbscript/impersonation.vbs on error resume next Set Locator = CreateObject("WbemScripting.SWbemLocator") Set Service = Locator.ConnectServer("ludlow", "root\cimv2") WScript.Echo "Service initial settings:" WScript.Echo "Authentication: " & Service.Security_.AuthenticationLevel WScript.Echo "Impersonation: " & Service.Security_.ImpersonationLevel WScript.Echo "" Service.Security_.AuthenticationLevel = 2 'wbemAuthenticationLevelConnect Service.Security_.ImpersonationLevel = 3 'wbemImpersonationLevelImpersonate WScript.Echo "Service modified settings (expecting {2,3}):" WScript.Echo "Authentication: " & Service.Security_.AuthenticationLevel WScript.Echo "Impersonation: " & Service.Security_.ImpersonationLevel WScript.Echo "" 'Now get a class Set aClass = Service.Get("Win32_LogicalDisk") WScript.Echo "Class initial settings (expecting {2,3}):" WScript.Echo "Authentication: " & aClass.Security_.AuthenticationLevel WScript.Echo "Impersonation: " & aClass.Security_.ImpersonationLevel WScript.Echo "" aClass.Security_.AuthenticationLevel = 6 'wbemAuthenticationLevelPktPrivacy aClass.Security_.ImpersonationLevel = 2 'wbemImpersonationLevelIdentify WScript.Echo "Class modified settings (expecting {6,2}):" WScript.Echo "Authentication: " & aClass.Security_.AuthenticationLevel WScript.Echo "Impersonation: " & aClass.Security_.ImpersonationLevel WScript.Echo "" 'Now get an enumeration from the object Set Disks = aClass.Instances_ WScript.Echo "Collection A initial settings (expecting {6,2}):" WScript.Echo "Authentication: " & Disks.Security_.AuthenticationLevel WScript.Echo "Impersonation: " & Disks.Security_.ImpersonationLevel WScript.Echo "" 'For grins print them out For Each Disk In Disks WScript.Echo Disk.Path_.DisplayName WScript.Echo Disk.Security_.AuthenticationLevel & ":" & Disk.Security_.ImpersonationLevel Next WScript.Echo "" Disks.Security_.AuthenticationLevel = 4 'wbemAuthenticationLevelPkt Disks.Security_.ImpersonationLevel = 1 'wbemImpersonationLevelAnonymous WScript.Echo "Collection A modified settings (expecting {4,1}):" WScript.Echo "Authentication: " & Disks.Security_.AuthenticationLevel WScript.Echo "Impersonation: " & Disks.Security_.ImpersonationLevel WScript.Echo "" 'Now get an enumeration from the service Set Services = Service.InstancesOf("Win32_service") WScript.Echo "Collection B initial settings (expecting {2,3}):" WScript.Echo "Authentication: " & Services.Security_.AuthenticationLevel WScript.Echo "Impersonation: " & Services.Security_.ImpersonationLevel WScript.Echo "" 'For grins print them out For Each MyService In Services WScript.Echo MyService.Path_.DisplayName WScript.Echo MyService.Security_.AuthenticationLevel & ":" & MyService.Security_.ImpersonationLevel Next WScript.Echo "" Services.Security_.AuthenticationLevel = 3 'wbemAuthenticationLevelCall Services.Security_.ImpersonationLevel = 4 'wbemImpersonationLevelDelegate WScript.Echo "Collection B modified settings (expecting {3,4} or {4,4}):" WScript.Echo "Authentication: " & Services.Security_.AuthenticationLevel WScript.Echo "Impersonation: " & Services.Security_.ImpersonationLevel WScript.Echo "" 'Print out again as settings should have changed For Each MyService In Services WScript.Echo MyService.Path_.DisplayName WScript.Echo MyService.Security_.AuthenticationLevel & ":" & MyService.Security_.ImpersonationLevel Next WScript.Echo "" 'Now get an event source Set Events = Service.ExecNotificationQuery _ ("select * from __instancecreationevent where targetinstance isa 'Win32_NTLogEvent'") WScript.Echo "Event Source initial settings (expecting {2,3}):" WScript.Echo "Authentication: " & Events.Security_.AuthenticationLevel WScript.Echo "Impersonation: " & Events.Security_.ImpersonationLevel WScript.Echo "" Events.Security_.AuthenticationLevel = 5 'wbemAuthenticationLevelPktIntegrity Events.Security_.ImpersonationLevel = 4 'wbemImpersonationLevelDelegate WScript.Echo "Event Source modified settings (expecting {5,4}):" WScript.Echo "Authentication: " & Events.Security_.AuthenticationLevel WScript.Echo "Impersonation: " & Events.Security_.ImpersonationLevel WScript.Echo "" 'Now generate an error from services Set Class2 = Service.Get("NoSuchClassss") If Err <> 0 Then Set MyError = CreateObject("WbemScripting.SWbemLastError") WScript.Echo "ERROR: " & Err.Description & "," & "0x" & Hex(Err.Number) & "," & Err.Source WScript.Echo "Error object initial settings (expecting {2,3}):" WScript.Echo "Authentication: " & MyError.Security_.AuthenticationLevel WScript.Echo "Impersonation: " & MyError.Security_.ImpersonationLevel WScript.Echo "" Err.Clear End If WScript.Echo "FINAL SETTINGS" WScript.Echo "==============" WScript.Echo "" WScript.Echo "Service settings (expected {2,3}) = {" & Service.Security_.AuthenticationLevel _ & "," & Service.Security_.ImpersonationLevel & "}" WScript.Echo "" WScript.Echo "Class settings (expected {6,2}) = {" & aClass.Security_.AuthenticationLevel _ & "," & aClass.Security_.ImpersonationLevel & "}" WScript.Echo "" WScript.Echo "Collection A settings (expected {4,1}) = {" & Disks.Security_.AuthenticationLevel _ & "," & Disks.Security_.ImpersonationLevel & "}" WScript.Echo "" WScript.Echo "Collection B settings (expected {4,4} or {3,4}) = {" & Services.Security_.AuthenticationLevel _ & "," & Services.Security_.ImpersonationLevel & "}" WScript.Echo "" WScript.Echo "Event Source settings (expected {5,4}) = {" & Events.Security_.AuthenticationLevel _ & "," & Events.Security_.ImpersonationLevel & "}" If Err <> 0 Then WScript.Echo "ERROR: " & Err.Description & "," & "0x" & Hex(Err.Number) & "," & Err.Source End If WScript.Echo Services.Count & "+" & Disks.Count
Option Explicit Public Sub Nb_Classifications() Dim A As New Collection, D As New Collection, P As New Collection Dim n As Long, l As Long, s As String, t As Single t = Timer 'Start For n = 1 To 20000 l = SumPropers(n): s = CStr(n) Select Case n Case Is > l: D.Add s, s Case Is < l: A.Add s, s Case l: P.Add s, s End Select Next 'End. Return : Debug.Print "Execution Time : " & Timer - t & " seconds." Debug.Print "-------------------------------------------" Debug.Print "Deficient := " & D.Count Debug.Print "Perfect := " & P.Count Debug.Print "Abundant := " & A.Count End Sub Private Function SumPropers(n As Long) As Long 'returns the sum of the proper divisors of n Dim j As Long For j = 1 To n \ 2 If n Mod j = 0 Then SumPropers = j + SumPropers Next End Function
<filename>admin/pchealth/authtools/prodtools/unused/winme_hhtfix01/frmmain.frm VERSION 5.00 Object = "{F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0"; "comdlg32.ocx" Begin VB.Form frmMain Caption = "Windows ME HHT Fix" ClientHeight = 1140 ClientLeft = 60 ClientTop = 345 ClientWidth = 5970 LinkTopic = "Form1" ScaleHeight = 1140 ScaleWidth = 5970 StartUpPosition = 3 'Windows Default Begin MSComDlg.CommonDialog dlg Left = 3480 Top = 600 _ExtentX = 847 _ExtentY = 847 _Version = 393216 End Begin VB.CommandButton cmdBrowse Caption = "&Browse..." Height = 375 Left = 5040 TabIndex = 3 Top = 120 Width = 855 End Begin VB.CommandButton cmdClose Caption = "&Close" Height = 375 Left = 5040 TabIndex = 2 Top = 600 Width = 855 End Begin VB.CommandButton cmdGo Caption = "&OK" Height = 375 Left = 4080 TabIndex = 1 Top = 600 Width = 855 End Begin VB.TextBox txtCabFile Height = 375 Left = 120 TabIndex = 0 Top = 120 Width = 4815 End Begin VB.Label lblProgress Height = 375 Left = 240 TabIndex = 4 Top = 600 Width = 3735 End End Attribute VB_Name = "frmMain" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Option Explicit ' Utility Stuff, all this could go to a COM Object and be distributed ' like this. Private m_WsShell As IWshShell ' Used to Shell and Wait for Sub-Processes Private m_fso As Scripting.FileSystemObject ' For filesystem operations Private Sub Form_Initialize() Set m_WsShell = CreateObject("Wscript.Shell") Set m_fso = New Scripting.FileSystemObject End Sub Private Sub Form_Load() If (Len(Trim$(Command$)) > 0) Then Me.txtCabFile = Command$ Me.txtCabFile.Enabled = False Me.cmdBrowse.Enabled = False Me.cmdGo.Enabled = False Me.Show Modal:=False cmdGo_Click cmdClose_Click End If End Sub Function Cab2Folder(ByVal strCabFile As String) Cab2Folder = "" ' We grab a Temporary Filename and create a folder out of it Dim strFolder As String strFolder = Environ("TEMP") + "\" + m_fso.GetTempName m_fso.CreateFolder strFolder ' We uncab CAB contents into the Source CAB Contents dir. Dim strCmd As String strCmd = "cabarc X " + strCabFile + " " + strFolder + "\" m_WsShell.Run strCmd, True, True Cab2Folder = strFolder End Function Sub Folder2Cab( _ ByVal strFolder As String, _ ByVal strCabFile As String _ ) ' We recab using the Destination directory contents ' cabarc -r -p -s 6144 N ..\algo.cab *.* m_fso.DeleteFile strCabFile, force:=True Dim strCmd As String strCmd = "cabarc -r -p -s 6144 N " + strCabFile + " " + strFolder + "\*.*" m_WsShell.Run strCmd, True, True End Sub ' ============ END UTILITY STUFF ======================== ' ============ BoilerPlate Form Code Private Sub cmdBrowse_Click() dlg.Filter = "All Files (*.*)|*.*|Cab Files (*.cab)|*.cab" dlg.FilterIndex = 2 dlg.ShowOpen If (Len(dlg.FileName) > 0) Then Me.txtCabFile = dlg.FileName End If End Sub Private Sub cmdClose_Click() Unload Me End Sub Private Sub cmdGo_Click() Me.txtCabFile.Text = Trim$(Me.txtCabFile.Text) If (Len(Me.txtCabFile.Text) > 0) Then FixCab Me.txtCabFile.Text End If End Sub Sub FixCab(ByVal strCabFile As String) Dim strErrMsg As String: strErrMsg = "" If (Not m_fso.FileExists(strCabFile)) Then MsgBox "Cannot find " & strCabFile GoTo Common_Exit End If Dim strCabFolder As String lblProgress = "Uncabbing " & strCabFile: DoEvents strCabFolder = Cab2Folder(strCabFile) lblProgress = "Applying Fixes ": DoEvents If (FixPerSe(strCabFolder)) Then lblProgress = "Recabbing " & strCabFile Folder2Cab strCabFolder, strCabFile Else MsgBox "Error: Fix Failed", Title:=App.EXEName End If ' Now we delete the Temporary Folders lblProgress = "Deleting Temporary Files": DoEvents m_fso.DeleteFolder strCabFolder, force:=True Common_Exit: lblProgress = "Done" + IIf(Len(strErrMsg) > 0, " - " + strErrMsg, "") End Sub ' ============= End BoilerPlate Form Code ================ Function FixPerSe(ByVal strCabFolder As String) As Boolean FixPerSe = False ' Now we parse Package_Description.xml to find the HHT Files ' For each HHT File ' IF Node Creation is being performed in this HHT - THEN ' Delete this HHT from the Destination Directory ' Create 2 HHT Files in out Package_Description.XML ' Split Source HHT into 2 destination HHTs ' - 1 HHT for Node creation ' - 1 HHT for Content ' Write the 2 newly created Destination HHTs ' ENDIF ' END FOR Each ' ' Save Resulting Package_Description.xml Dim oElem As IXMLDOMElement ' Used for all element Creation Dim oDomPkg As DOMDocument: Set oDomPkg = New DOMDocument Dim strPkgFile As String: strPkgFile = strCabFolder + "\package_description.xml" oDomPkg.async = False oDomPkg.Load strPkgFile If (oDomPkg.parseError <> 0) Then GoTo Common_Exit ' Let's check whether this fix was applied Dim oFixNode As IXMLDOMNode Set oFixNode = oDomPkg.selectSingleNode("HELPCENTERPACKAGE/package_fixes/fix[@id='1']") If (Not oFixNode Is Nothing) Then GoTo Common_Exit ' now, if it is the first time we run we have to create the Package_fixes ' NODE. If (oDomPkg.selectSingleNode("HELPCENTERPACKAGE/package_fixes") Is Nothing) Then Set oElem = oDomPkg.createElement("package_fixes") oDomPkg.selectSingleNode("HELPCENTERPACKAGE").appendChild oElem End If ' We record the fact that this fix was already applied Set oElem = oDomPkg.createElement("fix") oDomPkg.selectSingleNode("HELPCENTERPACKAGE/package_fixes").appendChild oElem oElem.setAttribute "id", "1" oElem.setAttribute "description", _ "Fix for Windows ME HCUPDATE where nodes cannot " + _ "be created in the same HHT as Content" Dim oMetadataNode As IXMLDOMNode Set oMetadataNode = oDomPkg.selectSingleNode("HELPCENTERPACKAGE/METADATA") Dim oMetadataCopy As IXMLDOMNode Set oMetadataCopy = oMetadataNode.cloneNode(deep:=True) Dim oDomHhtNode As IXMLDOMNode For Each oDomHhtNode In oMetadataCopy.selectNodes("HHT") Dim strHhtFile As String strHhtFile = oDomHhtNode.Attributes.getNamedItem("FILE").Text ' Let's load the HHT Dim oDomHht As DOMDocument: Set oDomHht = New DOMDocument oDomHht.async = False oDomHht.Load strCabFolder + "\" + strHhtFile If (oDomHht.parseError <> 0) Then GoTo Common_Exit ' And check whether Node Creation entries exist. Dim oNodeCreationEntries As IXMLDOMNodeList Set oNodeCreationEntries = oDomHht.selectNodes("METADATA/TAXONOMY_ENTRIES/TAXONOMY_ENTRY[@ENTRY]") If (Not oNodeCreationEntries Is Nothing) Then ' it means there are node Creation Entries ' So, we delete the HHT entry in Package Description.xml oMetadataNode.removeChild oMetadataNode.selectSingleNode("HHT[@FILE='" + strHhtFile + "']") ' oDomHhtNode ' and we replace the above with 2 new Entries in Package_description.xml ' for the new HHTs we are going to create. Dim strExt As String: strExt = FileExtension(strHhtFile) Set oElem = oDomPkg.createElement("HHT") Dim strHhtF1 As String: strHhtF1 = FilenameNoExt(strHhtFile) + "_1." + strExt oElem.setAttribute "FILE", strHhtF1 oMetadataNode.appendChild oElem Set oElem = oDomPkg.createElement("HHT") Dim strHhtF2 As String: strHhtF2 = FilenameNoExt(strHhtFile) + "_2." + strExt oElem.setAttribute "FILE", strHhtF2 oMetadataNode.appendChild oElem ' Now, in the second HHT we delete all Node Creation Entries ' We use the currently loaded HHT in the oDomHht for this. Dim oDomTaxoEntry As IXMLDOMNode For Each oDomTaxoEntry In oNodeCreationEntries oDomTaxoEntry.parentNode.removeChild oDomTaxoEntry Next oDomHht.Save strCabFolder + "\" + strHhtF2 ' and In the first HHT we delete ALL content addition entries. oDomHht.Load strCabFolder + "\" + strHhtFile If (oDomHht.parseError <> 0) Then GoTo Common_Exit Dim oTaxoEntries As IXMLDOMNodeList Set oTaxoEntries = oDomHht.selectNodes("METADATA/TAXONOMY_ENTRIES/TAXONOMY_ENTRY") Debug.Print "There are " & oTaxoEntries.length & " taxonomy entries" For Each oDomTaxoEntry In oTaxoEntries If (oDomTaxoEntry.Attributes.getNamedItem("ENTRY") Is Nothing) Then oDomTaxoEntry.parentNode.removeChild oDomTaxoEntry End If Next oDomHht.Save strCabFolder + "\" + strHhtF1 ' we delete the old HHT from the directory ' m_fso.DeleteFile strCabFolder + "\" + strHhtFile End If Next ' Now we save the resulting package_description.xml oDomPkg.Save strPkgFile FixPerSe = True Common_Exit: Exit Function End Function '============= File Utilities ============= Public Function FilenameNoExt(ByVal sPath As String) As String FilenameNoExt = sPath If "" = sPath Then Exit Function Dim bDQ As Boolean bDQ = (Left$(sPath, 1) = Chr(34)) Dim iDot As Long iDot = InStrRev(sPath, ".") If iDot > 0 Then FilenameNoExt = Left$(sPath, iDot - 1) & IIf(bDQ, Chr(34), "") End If End Function Public Function FileExtension(ByVal sPath As String) As String FileExtension = "" If "" = sPath Then Exit Function Dim bDQ As Boolean bDQ = (Right$(sPath, Len(sPath) - 1) = Chr(34)) If bDQ Then sPath = Left$(sPath, Len(sPath) - 1) Dim iDot As Long iDot = InStrRev(sPath, ".") If iDot > 0 Then FileExtension = UCase$(Right$(sPath, Len(sPath) - iDot)) End If End Function
Private Function medianq(s As Variant) As Double Dim res As Double, tmp As Integer Dim l As Integer, k As Integer res = 0 l = UBound(s): k = WorksheetFunction.Floor_Precise((l + 1) / 2, 1) If l Then res = quick_select(s, k) If l Mod 2 = 0 Then tmp = quick_select(s, k + 1) res = (res + tmp) / 2 End If End If medianq = res End Function Public Sub main2() s = [{4, 2, 3, 5, 1, 6}] Debug.Print medianq(s) End Sub
Public Sub case_sensitivity() 'VBA does not allow variables that only differ in case 'The VBA IDE vbe will rename variable 'dog' to 'DOG' 'when trying to define a second variable 'DOG' Dim DOG As String DOG = "Benjamin" DOG = "Samba" DOG = "Bernie" Debug.Print "There is just one dog named " & DOG End Sub
<reponame>LaudateCorpus1/RosettaCodeData Option Explicit ---- Sub DisplayFileSize(ByVal Path As String, ByVal Filename As String) Dim i As Long If InStr(Len(Path), Path, "\") = 0 Then Path = Path & "\" End If On Error Resume Next 'otherwise runtime error if file does not exist i = FileLen(Path & Filename) If Err.Number = 0 Then Debug.Print "file size: " & CStr(i) & " Bytes" Else Debug.Print "error: " & Err.Description End If End Sub ---- Sub Main() DisplayFileSize CurDir(), "input.txt" DisplayFileSize CurDir(), "innputt.txt" DisplayFileSize Environ$("SystemRoot"), "input.txt" End Sub
<filename>admin/darwin/src/msitools/scripts/wifeatur.vbs ' Windows Installer utility to list feature composition in an MSI database ' For use with Windows Scripting Host, CScript.exe or WScript.exe ' Copyright (c) Microsoft Corporation. All rights reserved. ' Demonstrates the use of adding temporary columns to a read-only database ' Option Explicit Public isGUI, installer, database, message, featureParam, nextSequence 'global variables accessed across functions Const msiOpenDatabaseModeReadOnly = 0 Const msiDbNullInteger = &h80000000 Const msiViewModifyUpdate = 2 ' Check if run from GUI script host, in order to modify display If UCase(Mid(Wscript.FullName, Len(Wscript.Path) + 2, 1)) = "W" Then isGUI = True ' Show help if no arguments or if argument contains ? Dim argCount:argCount = Wscript.Arguments.Count If argCount > 0 Then If InStr(1, Wscript.Arguments(0), "?", vbTextCompare) > 0 Then argCount = 0 If argCount = 0 Then Wscript.Echo "Windows Installer utility to list feature composition in an installer database." &_ vbLf & " The 1st argument is the path to an install database, relative or complete path" &_ vbLf & " The 2nd argument is the name of the feature (the primary key of Feature table)" &_ vbLf & " If the 2nd argument is not present, all feature names will be listed as a tree" &_ vbLf & " If the 2nd argument is ""*"" then the composition of all features will be listed" &_ vbLf & " Large databases or features are better displayed by using CScript than WScript" &_ vbLf & " Note: The name of the feature, if provided, is case-sensitive" &_ vbNewLine &_ vbNewLine & "Copyright (C) Microsoft Corporation. All rights reserved." Wscript.Quit 1 End If ' Connect to Windows Installer object On Error Resume Next Set installer = Nothing Set installer = Wscript.CreateObject("WindowsInstaller.Installer") : CheckError ' Open database Dim databasePath:databasePath = Wscript.Arguments(0) Set database = installer.OpenDatabase(databasePath, msiOpenDatabaseModeReadOnly) : CheckError REM Set database = installer.OpenDatabase(databasePath, 1) : CheckError If argCount = 1 Then 'If no feature specified, then simply list features ListFeatures False ShowOutput "Features for " & databasePath, message ElseIf Left(Wscript.Arguments(1), 1) = "*" Then 'List all features ListFeatures True Else QueryFeature Wscript.Arguments(1) End If Wscript.Quit 0 ' List all table rows referencing a given feature Function QueryFeature(feature) ' Get feature info and format output header Dim view, record, header, parent Set view = database.OpenView("SELECT `Feature_Parent` FROM `Feature` WHERE `Feature` = ?") : CheckError Set featureParam = installer.CreateRecord(1) featureParam.StringData(1) = feature view.Execute featureParam : CheckError Set record = view.Fetch : CheckError Set view = Nothing If record Is Nothing Then Fail "Feature not in database: " & feature parent = record.StringData(1) header = "Feature: "& feature & " Parent: " & parent ' List of tables with foreign keys to Feature table - with subsets of columns to display DoQuery "FeatureComponents","Component_" ' DoQuery "Condition", "Level,Condition" ' DoQuery "Billboard", "Billboard,Action" 'Ordering QueryFeature = ShowOutput(header, message) message = Empty End Function ' Query used for sorting and corresponding record field indices const irecParent = 1 'put first in order to use as query parameter const irecChild = 2 'primary key of Feature table const irecSequence = 3 'temporary column added for sorting const sqlSort = "SELECT `Feature_Parent`,`Feature`,`Sequence` FROM `Feature`" ' Recursive function to resolve parent feature chain, return tree level (low order 8 bits of sequence number) Function LinkParent(childView) Dim view, record, level On Error Resume Next Set record = childView.Fetch If record Is Nothing Then Exit Function 'return Empty if no record found If Not record.IsNull(irecSequence) Then LinkParent = (record.IntegerData(irecSequence) And 255) + 1 : Exit Function 'Already resolved If record.IsNull(irecParent) Or record.StringData(irecParent) = record.StringData(irecChild) Then 'Root node level = 0 Else 'child node, need to get level from parent Set view = database.OpenView(sqlSort & " WHERE `Feature` = ?") : CheckError view.Execute record : CheckError '1st param is parent feature level = LinkParent(view) If IsEmpty(level) Then Fail "Feature parent does not exist: " & record.StringData(irecParent) End If record.IntegerData(irecSequence) = nextSequence + level nextSequence = nextSequence + 256 childView.Modify msiViewModifyUpdate, record : CheckError LinkParent = level + 1 End Function ' List all features in database, sorted hierarchically Sub ListFeatures(queryAll) Dim viewSchema, view, record, feature, level On Error Resume Next Set viewSchema = database.OpenView("ALTER TABLE Feature ADD Sequence LONG TEMPORARY") : CheckError viewSchema.Execute : CheckError 'Add ordering column, keep view open to hold temp columns Set view = database.OpenView(sqlSort) : CheckError view.Execute : CheckError nextSequence = 0 While LinkParent(view) : Wend 'Loop to link rows hierachically Set view = database.OpenView("SELECT `Feature`,`Title`, `Sequence` FROM `Feature` ORDER BY Sequence") : CheckError view.Execute : CheckError Do Set record = view.Fetch : CheckError If record Is Nothing Then Exit Do feature = record.StringData(1) level = record.IntegerData(3) And 255 If queryAll Then If QueryFeature(feature) = vbCancel Then Exit Sub Else If Not IsEmpty(message) Then message = message & vbLf message = message & Space(level * 2) & feature & " (" & record.StringData(2) & ")" End If Loop End Sub ' Perform a join to query table rows linked to a given feature, delimiting and qualifying names to prevent conflicts Sub DoQuery(table, columns) Dim view, record, columnCount, column, output, header, delim, columnList, tableList, tableDelim, query, joinTable, primaryKey, foreignKey, columnDelim On Error Resume Next tableList = Replace(table, ",", "`,`") tableDelim = InStr(1, table, ",", vbTextCompare) If tableDelim Then ' need a 3-table join joinTable = Right(table, Len(table)-tableDelim) table = Left(table, tableDelim-1) foreignKey = columns Set record = database.PrimaryKeys(joinTable) primaryKey = record.StringData(1) columnDelim = InStr(1, columns, ",", vbTextCompare) If columnDelim Then foreignKey = Left(columns, columnDelim - 1) query = " AND `" & foreignKey & "` = `" & primaryKey & "`" End If columnList = table & "`." & Replace(columns, ",", "`,`" & table & "`.`") query = "SELECT `" & columnList & "` FROM `" & tableList & "` WHERE `Feature_` = ?" & query If database.TablePersistent(table) <> 1 Then Exit Sub Set view = database.OpenView(query) : CheckError view.Execute featureParam : CheckError Do Set record = view.Fetch : CheckError If record Is Nothing Then Exit Do If IsEmpty(output) Then If Not IsEmpty(message) Then message = message & vbLf message = message & "----" & table & " Table---- (" & columns & ")" & vbLf End If output = Empty columnCount = record.FieldCount delim = " " For column = 1 To columnCount If column = columnCount Then delim = vbLf output = output & record.StringData(column) & delim Next message = message & output Loop End Sub Sub CheckError Dim message, errRec If Err = 0 Then Exit Sub message = Err.Source & " " & Hex(Err) & ": " & Err.Description If Not installer Is Nothing Then Set errRec = installer.LastErrorRecord If Not errRec Is Nothing Then message = message & vbLf & errRec.FormatText End If Fail message End Sub Function ShowOutput(header, message) ShowOutput = vbOK If IsEmpty(message) Then Exit Function If isGUI Then ShowOutput = MsgBox(message, vbOKCancel, header) Else Wscript.Echo "> " & header Wscript.Echo message End If End Function Sub Fail(message) Wscript.Echo message Wscript.Quit 2 End Sub
'from http://www.roesler-ac.de/wolfram/hello.htm 'Hello World in Visual Basic .NET (VB.NET) Imports System.Console Class HelloWorld Public Shared Sub Main() WriteLine("Hello, world!") End Sub End Class
' 12 lines 6 code 3 comments 3 blanks Attribute VB_Name = "Module1" Public Function SayHello(Name As String) ' Create a response string Dim Response As String Response = "Hello " & Name 'Return response string SayHello = Response End Function
on Error resume next while true Set c = GetObject("winmgmts://./root/cimv2:win32_logicaldisk") d = c.Derivation_ for x = LBound(d) to UBound(d) WScript.Echo d(x) Next if err <> 0 then WScript.Echo Err.Description end if wend
<filename>Task/Pig-the-dice-game/VBA/pig-the-dice-game.vba Option Explicit Sub Main_Pig() Dim Scs() As Byte, Ask As Integer, Np As Boolean, Go As Boolean Dim Cp As Byte, Rd As Byte, NbP As Byte, ScBT As Byte 'You can adapt these Const, but don't touch the "¤¤¤¤" Const INPTXT As String = "Enter number of players : " Const INPTITL As String = "Numeric only" Const ROL As String = "Player ¤¤¤¤ rolls the die." Const MSG As String = "Do you want to ""hold"" : " Const TITL As String = "Total if you keep : " Const RES As String = "The die give you : ¤¤¤¤ points." Const ONE As String = "The die give you : 1 point. Sorry!" & vbCrLf & "Next player." Const WIN As String = "Player ¤¤¤¤ win the Pig Dice Game!" Const STW As Byte = 100 Randomize Timer NbP = Application.InputBox(INPTXT, INPTITL, 2, Type:=1) ReDim Scs(1 To NbP) Cp = 1 Do ScBT = 0 Do MsgBox Replace(ROL, "¤¤¤¤", Cp) Rd = Int((Rnd * 6) + 1) If Rd > 1 Then MsgBox Replace(RES, "¤¤¤¤", Rd) ScBT = ScBT + Rd If Scs(Cp) + ScBT >= STW Then Go = True Exit Do End If Ask = MsgBox(MSG & ScBT, vbYesNo, TITL & Scs(Cp) + ScBT) If Ask = vbYes Then Scs(Cp) = Scs(Cp) + ScBT Np = True End If Else MsgBox ONE Np = True End If Loop Until Np If Not Go Then Np = False Cp = Cp + 1 If Cp > NbP Then Cp = 1 End If Loop Until Go MsgBox Replace(WIN, "¤¤¤¤", Cp) End Sub
<filename>Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-4.vba Sub Main_Ethiopian() Dim result As Long result = Ethiopian_Multiplication(17, 34) ' or : 'result = Ethiopian_Multiplication_Non_Optimized(17, 34) Debug.Print result End Sub
on error resume next set service = GetObject("winmgmts:") set s2 = service.open ("win32_logicaldisk='C:'", &H10, "WIn32_SystemDevices") if err <> 0 then WScript.Echo "Error!", Hex(Err.Number), Err.Description
Select Case Expression Case Value1: statement Case Value2: statement ... Case ValueN: statement Case Else: statement End Select Select Case Expression Case Value1 statements Case Value2 statements ... Case ValueN statements Case Else statements End Select
<reponame>npocmaka/Windows-Server-2003 ' ' Copyright (c) 1997-1999 Microsoft Corporation ' ' This script lists the ADSI path to the group objects ' that a given user belongs to ' This is a routine that prints the groups that a specified user belongs to Sub FindUserMembership ( objService , user ) On Error Resume Next Dim objInstance Dim objEnumerator Dim userFound userFound = 0 ' Enumerate the users Set objEnumerator = objService.InstancesOf ( "ds_user" ) If Err = 0 Then ' Go thru the users looking for the correct one For Each objInstance In objEnumerator Dim propertyEnumerator Set propertyEnumerator = objInstance.Properties_ If propertyEnumerator("DS_sAMAccountName") = user Then userFound = 1 Wscript.Echo "User: " + propertyEnumerator.Item("DS_sAMAccountName") + " belongs to:" For x = LBound(propertyEnumerator("DS_memberOf")) To UBound(propertyEnumerator("DS_memberOf")) Wscript.Echo propertyEnumerator("DS_memberOf")(x) Next End If Next Else WScript.Echo "Err = " + Err.Number + " " + Err.Description End If If( userFound = 0) Then Wscript.Echo "User not found: " + user End If End Sub ' Start of script ' Create a locator and connect to the namespace where the DS Provider operates Dim objLocator Set objLocator = CreateObject("WbemScripting.SWbemLocator") Dim objService Set objService = objLocator.ConnectServer(".", "root\directory\LDAP") ' Set the impersonation level objService.Security_.ImpersonationLevel = 3 ' The first argument should be the user Set objArgs = Wscript.Arguments If objArgs.Count <> 0 Then FindUserMembership objService , objArgs(0) Else Wscript.Echo "Usage: userBelongsTo <user>" End If
<reponame>mullikine/RosettaCodeData 5/02/2010 2:35:36 PM woof
<reponame>mullikine/RosettaCodeData<filename>Task/Check-that-file-exists/Visual-Basic/check-that-file-exists.vb 'declarations: Public Declare Function GetFileAttributes Lib "kernel32" _ Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long Public Const INVALID_FILE_ATTRIBUTES As Long = -1 Public Const ERROR_SHARING_VIOLATION As Long = 32& 'implementation: Public Function FileExists(ByVal Filename As String) As Boolean Dim l As Long l = GetFileAttributes(Filename) If l <> INVALID_FILE_ATTRIBUTES Then FileExists = ((l And vbDirectory) = 0) ElseIf Err.LastDllError = ERROR_SHARING_VIOLATION Then FileExists = True End If End Function
<reponame>npocmaka/Windows-Server-2003 '********************************************************************* ' ' sysprop.vbs ' ' Purpose: test system property functionality ' ' Parameters: none ' ' Returns: 0 - success ' 1 - failure ' '********************************************************************* on error resume next set scriptHelper = CreateObject("WMIScriptHelper.WSC") scriptHelper.logFile = "c:\temp\sysprop.txt" scriptHelper.loggingLevel = 3 scriptHelper.testName = "SYSPROP" scriptHelper.testStart '***************************** ' Get a disk '***************************** set disk = GetObject ("winmgmts:root\cimv2:Win32_LogicalDisk='C:'") if err <> 0 then scriptHelper.writeErrorToLog err, "Failed to get test instance" else scriptHelper.writeToLog "Test instance retrieved correctly", 2 end if '***************************** ' Get the __CLASS property '***************************** className = disk.SystemProperties_("__CLASS") if err <> 0 then scriptHelper.writeErrorToLog err, "Failed to get __CLASS" elseif "Win32_LogicalDisk" <> className then scriptHelper.writeErrorToLog null, "__CLASS value is incorrect" else scriptHelper.writeToLog "__CLASS retrieved correctly", 2 end if '***************************** ' Try to add a property - should fail '***************************** disk.SystemProperties_.Add "__FRED", 8 if err <> 0 then scriptHelper.writeToLog "Expected failure to add a system property", 2 err.clear else scriptHelper.writeErrorToLog null, "Unexpectedly successful addition of system property" end if '***************************** ' Iterate through the system properties '***************************** EnumerateProperties disk '***************************** ' Count the system properties '***************************** spCount = disk.SystemProperties_.Count if err <> 0 then scriptHelper.writeErrorToLog err, "Error retrieving Count" else scriptHelper.writeToLog "There are " & spCount & " system properties", 2 end if '***************************** ' Get an empty class '***************************** set emptyClass = GetObject("winmgmts:root\default").Get if err <> 0 then scriptHelper.writeErrorToLog err, "Failed to get empty test class" else scriptHelper.writeToLog "Empty test class retrieved correctly", 2 end if '***************************** ' Set the __CLASS property '***************************** emptyClass.SystemProperties_("__CLASS").Value = "Stavisky" if err <> 0 then scriptHelper.writeErrorToLog err, "Failed to set __CLASS in empty class" else scriptHelper.writeToLog "__CLASS set in empty class correctly", 2 end if if emptyClass.Path_.Class <> "Stavisky" then scriptHelper.writeErrorToLog null, "Incorrect class name set in path" else scriptHelper.writeToLog "Class name set in path correctly", 2 end if scriptHelper.testComplete if scriptHelper.statusOK then WScript.Echo "PASS" WScript.Quit 0 else WScript.Echo "FAIL" WScript.Quit 1 end if Sub EnumerateProperties (obj) scriptHelper.writeToLog "Enumerating all properties...", 2 for each property in obj.SystemProperties_ scriptHelper.writeToLog " " & property.Name & " - " & property.CIMType, 2 value = property.Value if IsNull(value) then scriptHelper.writeToLog " Value: <null>", 2 elseif property.IsArray then valueStr = "[" for i = LBound(value) to UBound(value) valueStr = valueStr + value(i) if i < UBound(value) then valueStr = valueStr + ", " next valueStr = valueStr + "]" scriptHelper.writeToLog " Value: " & valueStr, 2 else scriptHelper.writeToLog " Value: " & property.Value, 2 end if if err <> 0 then scriptHelper.writeErrorToLog err, "Hmm" next if err <> 0 then scriptHelper.writeErrorToLog err, "...Failed to enumerate" else scriptHelper.writeToLog "...Enumeration complete", 2 end if End Sub