Hanging VBScript on query - vbscript

I inherited a piece of code from a recently-retired colleague that gets the total physical memory on a box and, when I perform the following on Windows XP and Server 2003, it works fine:
memSize = 0
set colItems = wmi.execQuery("select * from Win32_LogicalMemoryConfiguration")
for objItem in colItems
memSize = memSize + objItem.TotalPhysicalMemory
next
On Windows Server 2008 however, it appears to hang in the for statement (based on copious debugging statements after every line which are not shown in the example).
Any ideas why?

The Win32_LogicalMemoryConfiguration class has been deprecated. Try the Win32_OperatingSystem class instead. It should give the proper results on Server 2008.
I believe the property you're interested in is TotalVisibleMemorySize.

Related

Enumerating WMI on Windows Server 2016 is significantly slower

I am using a simple vb script to get CPU0's load percentage, but the WMI enumeration is significantly slower on Windows Server 2016 then older versions and I need to optimize the speed.
Here's my short script:
Option Explicit
Dim objWMIService, processItems, objitem, loadpercentage
loadpercentage= 0
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set processItems = objWMIService.ExecQuery("SELECT * FROM Win32_Processor _
WHERE DeviceID='CPU0'", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
For Each objItem In processItems
loadpercentage = objItem.LoadPercentage
Next
There's a 10 second delay between setting processItems and entering the For Each loop. This same script on older versions of Windows Servers takes 2 seconds. Can anything be done to optimize the WMI enumeration? Thanks in advance.
Try to not use * in your WQL queries. No filtering by any property just slows WMI queries very much. Instead of that, specify exacly the properties you need and nothing else:
SELECT LoadPercentage FROM Win32_Processor WHERE DeviceID='CPU0'

Find MAC address using VB6

I want to find the MAC address of network adopter, I have a working code too but my problem is it only works if IP addres is enabled otherwise it won't get the address is there any solution to find MAC address even if IP Enabled is false
if its possible update me with sample code
Here is my code to find MAC
Dim myWMI As Object, myObj As Object, Itm
Set myWMI = GetObject("winmgmts:\\.\root\cimv2")
Set myObj = myWMI.ExecQuery("SELECT * FROM " & _
"Win32_NetworkAdapterConfiguration " & _
"WHERE IPEnabled = True")
For Each Itm In myObj
Dim macme As String
Dim NewMac As String
macme = Itm.MACAddress
NewMac = Replace(macme, ":", "")
Text1.Text = NewMac
Exit For
Next
Querying the heavyweight WMI service is not the best choice for application programs. It is a convenience feature meant only for admin scripting. The service could be disabled or even uninstalled on older versions of Windows.
Instead you can go directly to the source. The GetAdaptersInfo function is one of the more obvious candidates.
Using this involves more code than can be conveniently inlined here. Look for the many examples of use in VB6 posted with working source code at more programmer-friendly sites that permit uploaded attachments.
No matter how you go about it the value of doing this is questionable anyway. Many integrated network adapters allow users to insert their own MAC Address values anyway. Quite a few PCs today rely on USB network adapters that are not even plugged in all the time and may get swapped around between devices.

Adding dummy Printers to Windows 7

I want to add around 40 printers to my machine in order to test the performance of the application which uses WMI for printer functions.
What I want is a way to add dummy/fake printers (Not only 1 printer but more than 1 printers) through some sort of script or programming.
Please note that I have gone through most of the options to add virtual Printer to the system but none of them says how to add Printers. Reason behind asking it to be done by script or programming is that, if I have one, I can test it on multiple machines.
Unfortunately Windows 7 does not feature the really nice Add-Printer Function Powershell introduced in Windows 8.1 but you can do this via WMI.
In VBScript some example code would look like this:
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set objPrinter = objWMIService.Get("Win32_Printer").SpawnInstance_
For i = 1 to 40
name = "Testprinter" & i
objPrinter.DeviceID = name
objPrinter.Caption = name
objPrinter.DriverName = "Microsoft XPS Document Writer"
objPrinter.PortName = "XPSPort:"
objPrinter.Put_
Next
This will Create 40 Printers with the name "Testprinter" which are copies of Microsofts XPS Document Writer basically.
Please note that in the "Device and Printers" View Windows 7 would group them all together due to them having the same port, but I doubt that would influence your testing.

Classic ASP : C0000005 Error on execution

I'm trying to execute classic ASP pages on a windows 2008 64 bit R2 box.
Initially the problem was with registering dlls; that's now fixed.
Register DLL file on Windows Server 2008 R2
Now when I try to access the page I get this error
Active Server Pages error 'ASP 0241'
CreateObject Exception
index.asp
The CreateObject of '(null)' caused exception C0000005.
Server object error 'ASP 0177 : c0000005'
When I change the code from Server.CreateObject to CreateObject, I end up with this error
Active Server Pages error 'ASP 0115' Unexpected error
index.asp
A trappable error (C0000005) occurred in an external object. The script cannot continue running.
I checked everything I could - Access and admin rights etc.
The application pool are set to No Managed Code + Classic mode.
Any ideas to fix this?
You're not going to fix this in ASP. The C0000005 is the Access Violation Exception. This occurs when code attempts to read memory that it hasn't allocated.
The dll is doing something bad when it loads or during the construction of the object.
Have you tested the dll with a simple .vbs file?
I had exactly the same error.
In my case the C0000005 error was caused by a missing dependancy.
ProcessMonitor help me finding it. (Filter by process, and check "Name not found")
Copying the needed file in the right place solved my problem. (In my case VB6FR.dll was a needed dependancy for vb6 in french.)
I spent several hours chasing this down as well.
In my case, it was caused by reusing a recordset object several times without closing it between DB calls. The code was working without apparent issue in several similar instances, and then one of them just stopped tolerating the process.
The error occurred when I attempted to close the recordset at the end of the page, which made troubleshooting more difficult.
I cleaned up the code, ensuring the recordset was closed between calls, and this resolved the issue.
I had the same problem happen sometime after KB4093114 was installed on a server. (I'm not 100% sure that the KB caused the problem but I suspect so because the scripting engine was updated.)
The problem was caused by a recordset that output a varchar(max) field to the markup. Even though the error does not provide a line number, I was able to pinpoint it to the outputting of the varchar(max) field through trial and error.
<%
...
rs.Open "SELECT LongDescription FROM Table1"
while (not rs.EOF)
%> <p><%= rs("LongDescription") %></p> <% ' ERROR HAPPENS BECAUSE OF THIS LINE
rs.MoveNext
wend
%>
Removing that line fixes the problem. Also, casting the field to a non-max varchar also fixes it:
rs.Open "SELECT LongDescription = Cast(LongDescription as varchar(4000)) FROM Table1"
To make matters worse, I found that once the error happens, even if you fix it you need to recycle the app pool to make the error go away.
I'm running some very old ASP code in IIS on a new Windows 10 1803 installation, and had it briefly running correctly then started to get this error message after running a repair in Office to fix an Outlook issue.
In this case, reinstalling the Microsoft Access Database Engine fixed the problem.
I had same error while loading the csv file data more than once.
Step 1 - Firstly create a temp table to transfer the csv data into temp table and then move to main table and delete temp table once data is moved. This has to be done programmatically.
Step 2 - Go to mysql and select the database and use this query SHOW FULL PROCESSLIST; use without brakets. this will show the status of running objects. If you find any object with status set to Sleep clear it before 2nd attempt to upload the file. Usually the default wait time is about 28000 second. You need to reduce it as per requirement. The code to reduce the wait time is SET GLOBAL wait_timeout=5;. Set it via mysql. This will re-set your global wait time to 5 sec. and change as per your needs. This should resolve your problem. All the best.
For my experience, you are using AVG Free, and after an update, you got this kind of error.
Just ran into this same error while trying to use my own com control and in my case it turned out to be caused by my dll being compiled in debug mode.
There are two ways around that:
Run IIS in debug mode. For 32 bit you use the following line:
C:\Windows\SysWOW64\inetsrv>w3wp.exe -debug
Note that you have to stop the IIS service and for 64 bit you use the one in System32.
Compile a release version :)
I'm adding this answer here, though I realise this is very much later than when the question was first answered. I'm putting the answer here in case it saves anyone else the hassle I've just been through.
I too was getting this error on my ASP page after I had re-installed Windows 10. Previously on my localhost IIS setup, the same page did not error. However - now it did - with the following error:
Active Server Pages error 'ASP 0115' Unexpected error index.asp
A trappable error (C0000005) occurred in an external object. The script cannot continue running.
I tried lots of things to try and sort it, such as:
Reinstalling Windows 10 again
Reinstalling IIS on the new Windows 10 installation
Trying all sorts of combinations of versions of MySQL and the ODBC Connector
Checking for missing files in Windows Process Monitor as per one of the answers on this page
Messing about with Application Pools
Messing about with lots of versions of Microsoft Visual C++ Redistributables
My problem was with an SQL Insert - when it ran, I got the error.
This is a cut down version of it:
sql = ""
sql = sql & " INSERT INTO my_table ( "
sql = sql & " card_sender, "
sql = sql & " senders_email, "
sql = sql & " recipients_email, "
sql = sql & " card_body, "
sql = sql & " session_id, "
sql = sql & " replyID) VALUES ( "
sql = sql & " ?, "
sql = sql & " ?, "
sql = sql & " ?, "
sql = sql & " ?, "
sql = sql & " ?, "
sql = sql & " ?) "
Set stmt = Server.CreateObject("ADODB.Command")
stmt.ActiveConnection = oConn
stmt.Prepared = true
stmt.commandtext = sql
stmt.Parameters.Append stmt.CreateParameter("#001_card_sender", adVarChar, adParamInput, 255, card_sender)
stmt.Parameters.Append stmt.CreateParameter("#002_senders_email", adVarChar, adParamInput, 255, senders_email)
stmt.Parameters.Append stmt.CreateParameter("#003_recipients_email", adVarChar, adParamInput, 255, recipients_email)
stmt.Parameters.Append stmt.CreateParameter("#004_card_body", adLongVarChar, adParamInput, 256665, card_body)
stmt.Parameters.Append stmt.CreateParameter("#sessionsessionID", adVarChar, adParamInput, 255, session.sessionID)
stmt.Parameters.Append stmt.CreateParameter("#replyID", adVarChar, adParamInput, 255, session("replyID"))
stmt.Execute
Set stmt = Nothing
Via a process of building up the SQL and finding which line triggered the error, I found this line caused the problem:
stmt.Parameters.Append stmt.CreateParameter("#replyID", adVarChar, adParamInput, 255, session("replyID"))
In my example, the session("replyID") value was not set, and that triggered the error.
When I changed the code to check if the session variable was set, it fixed the issue:
...
foo = session("replyID")
if foo = "" then foo = 1
...
stmt0003.Parameters.Append stmt0003.CreateParameter("#replyID", adVarChar, adParamInput, 255, foo)
More testing confirmed that the error would happen for any variable which was null, so I had to add in an if statement for every variable and set it to something if it was null, to prevent these errors which I didn't used to get on a previous Windows 10 installation on the same PC.
After spending about a day working on it, it was a relief to get to the bottom of it.
Did you just do a Windows update? I did, abouts 2021-11-20 to 21H2 19044.1387. Somehow the update along with other updates made my code constantly crash. I found that I could code around some errors, but the database (MariaDB 10.1) returned values that did not match up. I found I could declare my sql calls differently to get the right returns -- but quickly stopped re-coding. Somehow NULL was handled differently.
I was getting suspect that the driver to the database was not working the same way it used to be. I changed all connections from Server.CreateObject to CreateObject. And ended up updating the database (I am now on MariaDB 10.6) and I am using new dedicated MySQL 8.0 Unicode 64-bit driver. I am connecting via DSN.
UPDATE: These (C0000005) errors kept appearing when using Server.CreateObject. With just CreateObject it is now finally starting to look promising.
I was using this code to get the image height and width on every page and it is WIA that somehow had a memory leak and would randomly crash IIS application pool:
SET objFSO= CreateObject("Scripting.FileSystemObject")
If objFSO.fileExists(is_blog_img) and InStr(is_blog_img,".webp") = 0 Then
dim oIMG
SET oIMG = CreateObject("WIA.ImageFile") '<< do not use this!
oIMG.loadFile(is_blog_img)
og_image_h = "" & oIMG.Height
og_image_w = "" & oIMG.Width
SET oIMG = nothing
if og_image_h & "" <> "" then
%>
<meta property="og:image:width" content="<%=og_image_w %>" />
<meta property="og:image:height" content="<%=og_image_h %>" />
<%
end if
else
response.write("<!-- no file is_blog_img -->")
og_image_w = "0"
og_image_h = "0"
end if
SET objFSO = Nothing
You might want to check out this blog entry, titled "Classic ASP (ASP 3.0) doesn’t work on 64bit with 32bit COM objects" http://blogs.msdn.com/b/robgruen/archive/2005/05/26/422328.aspx
it's a bit dated and the author incorrectly refers to the ASP handler as an ISAPI filter (it's an extension, not a filter), but otherwise the information seems good.
if the asp handler is only compiled as 64bit, you will not be able to load a 32bit COM object into it no matter what you do.
the author does mention something about a COM+ solution. I have a feeling that a 32bit out of process COM+ package would be able to load this 32bit COM object and your ASP page could make cross process calls to this COM+ package.
good luck,
Mark

Is there any way to tell if the Windows Directory is writeable without actually writing to it to test?

I have some old vb6 code that checks to see if the Windows directory is writeable by WRITING to it then reading a value back.
But... we have a virus scanner that's viewing that as suspicious behavior so I want to check it without touching it.
Any Windows API calls for that? (Ideally for Win 98 and above)
Something to remember here is that the file system is volatile. About the only way I can see this code being used is to first do a check if a folder is writable, and then try to write something you wanted to write. The problem here is that with a volatile file system things might change in between when you make your check and when you try to write. As a consequence, you still have to be able to handle an exception if your write fails. That means the initial check is pretty much wasted. Better to put your effort into writing a better exception handler.
Additionally, for windows 2000 and later the Windows directly should only ever be writable if the user is running as an administrator. For a very long time running as an administrator was common practice, but people are starting to get the hint that this isn't a good idea. Long term, it's not a good idea for your program to do anything that requires running that way.
In fact, starting with Windows Vista, the user doesn't run anything as administrator by default, even when logged in to the administrator account. Instead, they have to manually choose to run the program as administrator or wait a security check to fail the system can prompt them to elevate.
If you have the VB6 code, you should take the time to fix it so that it does NOT need to write to the Windows directory at all because regardless of whether or not you are an administrator - unless you work at Microsoft you should consider that directory off limits.
However, you should consider that on Windows 98, the user will always have the ability to write to the Windows directory. On Windows XP, local administrators will. On Windows Vista and Seven, even administrators will not unless your application has been elevated.
So you can check for whether or not the user is in the built-in role BUILTIN\Administrators using CheckTokenMembership. This will be false for non-admins or non-elevated processes. It does not guarantee you can write to the Windows directory but it will be right most of the time. You can then add error handling logic for when the call actually fails.
But again, you should take the opportunity to fix the code and not use the Windows directory.
For Windows 2000 and above you could use GetNamedSecurityInfo() and AccessCheck(), but I would imagine those are a pain to call from VB.
Here is a function that will do it. I adapted this from some other code kind of quickly so if you use it you need to add error handling, (for instance a directory that doesn't exist just returns False. I have no idea if your anti-virus software is going to like this or not.
Function FolderIsReadOnly(ByVal FolderSpec As String) As Boolean
Dim rst As Long
Dim udtW32FindD As WIN32_FIND_DATA
Dim lngFHandle As Long
Dim strFolder As String 'set to FolderSpec parameter so I can change it
If Len(FolderSpec) = 0 Then
FolderIsReadOnly = False
Exit Function
End If
strFolder = FolderSpec
If Right$(strFolder, 1) <> "\" Then
strFolder = strFolder & "\"
End If
strFolder = strFolder & "*" 'add the wildcard allows finding share roots
lngFHandle = FindFirstFile(strFolder, udtW32FindD)
If lngFHandle <> INVALID_HANDLE_VALUE Then
Call FindClose(lngFHandle)
FolderIsReadOnly = (udtW32FindD.dwFileAttributes And FILE_ATTRIBUTE_READONLY) = FILE_ATTRIBUTE_READONLY
End If
End Function
Function IsPathAccessible(ByVal sPath As String) As Boolean
On Error GoTo ErrHandler
FileSystem.SetAttr sPath, vbNormal
IsPathAccessible = True
Exit Function
ErrHandler:
IsPathAccessible = False
End Function

Resources