Where do you find info on vram on system? [duplicate] - vb.net

I'm writing a program that is using a validation of graphic card.
I tried using multiple ways; the closest one i found was using:
lblGrapics.Text = infotypes.VideocardName.GetName()
but the automatic return is equals 1.
how can i get the card name and other specifations?

This will allow you to poll any WMI class and get the desired values for the properties. In your case, you would select from the Win32_VideoController class. Other WMI class can be found here.
Imports System.Management
Public Class WMI
Public Shared Function GetWMISettingsDictionary(ByVal wmiClass As String,
ShoppingList() As String) As Dictionary(Of String, String)
Dim wmiInfo As New Dictionary(Of String, String)
Dim searcher As New System.Management.ManagementObjectSearcher("select * from " & wmiClass)
For Each item As System.Management.ManagementObject In searcher.Get
For Each PC As System.Management.PropertyData In item.Properties
' perform case insensitive search
For Each s As String in ShoppingList
If s.ToLowerInvariant = PC.Name.ToLowerInvariant Then
If PC.Value IsNot Nothing Then
wmiInfo.Add(PC.Name, PC.Value.ToString)
' halt search-by-name
Exit For
End If
End If
Next
Next
' Note: this is to prevent a crash when there is more than one item
' WMI reports on such as 2 display adapters; just get the first one.
Exit For
Next
Return wmiInfo
End Function
' helpful tool to see how WMI props are organized, discover the names etc
Public Shared Sub DebugWMIPropValues(wmiClass As String)
Using searcher As New Management.ManagementObjectSearcher("Select * from " & wmiClass)
Dim moReturn As Management.ManagementObjectCollection = searcher.Get
For Each mo As Management.ManagementObject In moReturn
Console.WriteLine("====")
DebugProperties(mo)
Next
End Using
End Sub
' debug tool to poll a management object to get the properties and values
Private Shared Sub DebugProperties(mo As Management.ManagementObject)
For Each pd As PropertyData In mo.Properties
If pd.Value IsNot Nothing Then
If pd.Value.GetType Is GetType(String()) Then
Dim n As Integer = 0
For Each s As String In CType(pd.Value, Array)
Console.WriteLine("{0}({1}): {2}", pd.Name, n.ToString,
If(pd.Value IsNot Nothing,
s,
"Nothing"))
n += 1
Next
Else
Console.WriteLine("{0}: {1}", pd.Name,
If(pd.Value IsNot Nothing,
pd.Value.ToString,
"Nothing"))
End If
End If
Next
End Sub
End Class
To use it you just create a "shopping list" of the properties you want and pass the WMI Class:
Dim shopList() As String = {"VideoProcessor", "Name", "AdapterRAM"}
' the return is a Dictionary to keep the Name and Value together
Dim wmiItems As Dictionary(Of String, String)
wmiItems = WMI.GetWMISettingsDictionary("Win32_VideoController", shopList)
' print them to the console window:
For Each kvp As KeyValuePair(Of String, String) In wmiItems
Console.WriteLine("Item: {0} value: {1}", kvp.Key, kvp.Value)
Next
The class includes a way to dump the property names and values for a class. To use it:
WMI.DebugWMIPropValues("Win32_VideoController")
Just look in the Output window for the results (Debug menu -> Windows -> Ouput)
Sample output for the shopping list:
Item: AdapterRAM value: 1073741824
Item: Name value: AMD Radeon HD 6450
Item: VideoProcessor value: ATI display adapter (0x6779)
Works on My SystemTM
Notes, Update: GetWMISettingsDictionary is intended for harvesting the properties for a single item. As is, it will get the settings for most things, but only the first video card, the first display etc.
There are several ways to change this depending on what you need. It could be modified to return a separate Dictionary in a List for each item. Or you could append a WHERE clause to the WMI class name to get the properties for a specific device and call it as often as needed:
wmiClass = "Win32_VideoController WHERE Name = 'FizzBar Deluxe'"
' or
wmiClass = "Win32_VideoController WHERE DeviceID = 'VideoController1'"
wmiItems = WMI.GetWMISettingsDictionary(wmiClass , shopList)
The name search is now case-insensitive.
Finally, note that with low-end video adapters, AdapterRAM will report total System RAM. This is because adapters without any on-board RAM simply use system RAM, so it is reporting correctly.

It is possible to get graphics card info using WMI. You need to reference the System.Management and import it.
WMI is a great library which contains the details about various components required for the system to operate. Hard Disk Drive related information, processor information, Network components and the list goes on. It is really easy to query the data if you know a little about the data how it is organized.
You have to use the ManagementObjectSearcher class.
Example:
Imports System.Management
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.Click
MsgBox(GetGraphicsCardName())
End Sub
Private Function GetGraphicsCardName() As String
Dim GraphicsCardName = String.Empty
Try
Dim WmiSelect As New ManagementObjectSearcher _("rootCIMV2", "SELECT * FROM Win32_VideoController")
For Each WmiResults As ManagementObject In WmiSelect.Get()
GraphicsCardName = WmiResults.GetPropertyValue("Name").ToString
If (Not String.IsNullOrEmpty(GraphicsCardName)) Then
Exit For
End If
Next
Catch err As ManagementException
MessageBox.Show(err.Message)
End Try
Return GraphicsCardName
End Function
End Class
Source

"invalid namespace" is not about System.Management, it is because the first parameter of
Dim WmiSelect As New ManagementObjectSearcher _("rootCIMV2", "SELECT * FROM
is not accepted.
Try to use another constructor without first parameter:
Dim WmiSelect As New ManagementObjectSearcher _("SELECT * FROM Win32_VideoController")

Related

Get extended file information details

How can one obtain the details of a windows file using VB.net?
The type of details I mean are those found when I right click on a file, say an MS word doc, then click "Properties" and select the "Details" tab.
I know some can be obtained via FileInfo, but not all, such as "Tags" for example.
Thanks
For that stuff you need to use Shell32. From the COM tab, find and add Microsoft Shell Controls and Automation. Here is code to create a list of property-values for a given file:
' class to hold the goodies
Friend Class ShellInfo
Public Property Name As String
Public Property Value As String
Public Sub New(n As String, v As String)
Name = n
Value = v
End Sub
Public Overrides Function ToString() As String
Return Name
End Function
End Class
Then a function to fill it up
Private Function GetXtdShellInfo(filepath As String) As List(Of ShellInfo)
' ToDo: add error checking, maybe Try/Catch and
' surely check if the file exists before trying
Dim xtd As New List(Of ShellInfo)
Dim shell As New Shell32.Shell
Dim shFolder As Shell32.Folder
shFolder = shell.NameSpace(Path.GetDirectoryName(filepath))
' its com so iterate to find what we want -
' or modify to return a dictionary of lists for all the items
Dim key As String
For Each s In shFolder.Items
' look for the one we are after
If shfolder.GetDetailsOf(s, 0).ToLowerInvariant = Path.GetFileName(file).ToLowerInvariant Then
Dim ndx As Int32 = 0
key = shfolder.GetDetailsOf(shfolder.Items, ndx)
' there are a varying number of entries depending on the OS
' 34 min, W7=290, W8=309 with some blanks
' this should get up to 310 non blank elements
Do Until String.IsNullOrEmpty(key) AndAlso ndx > 310
If String.IsNullOrEmpty(key) = False Then
xtd.Add(New ShellInfo(key,
shfolder.GetDetailsOf(s, ndx)))
End If
ndx += 1
key = shfolder.GetDetailsOf(shfolder.Items, ndx)
Loop
' we got what we came for
Exit For
End If
Next
Return xtd
End Function
Using it is simple:
Dim xtd As List(Of ShellInfo) = GetXtdShellInfo("C:\Temp\Capri.jpg")
For Each s As ShellInfo In xtd
Console.WriteLine("{0}: {1}", s.Name, s.Value)
Next
The return should be a list of ShellInfo items where the Name is the property name such as Name, BitRate, Album and the associated Value will be that returned by Shell32. e.g
Name: Capri.jpg
Size: 15.2 KB
Item type: Image File
Date modified: 7/20/2014 12:19 PM
Date created: 7/20/2014 12:17 PM
Date accessed: 7/20/2014 12:17 PM
(etc)
The actual number returned will vary depending on the OS ver
As noted in the comment Microsoft Shell Controls and Automation is renamed as Microsoft Shell Folder View Router (in Windows 8.1).
Also, the first 35 properties are fairly well known and more common, but with Win7 there are about 291. Under Windows 8, the max is 309 with some blank spots and deep into the list some property indices are changed.
See this answer related question How to read the bit rate information from a .mov video file header
Dim shellAppType = Type.GetTypeFromProgID("Shell.Application")
Dim shellApp = Activator.CreateInstance(shellAppType)
Dim folder = shellApp.NameSpace("c:\users\frank")
Dim folderitem = folder.parsename("yourfile.jpg")
Dim value = folder.GetDetailsOf(folderitem, 24) 'eg. 24 retrieves File Comments.
Just use something like :
Dim MyFileInfos as System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(PathToYourFile)
Then get infos using MyFileInfo.* (whatever you need, use IntelliSense).
Have a nice day

How do I get VBCodeProvider to return an object

I have a program that allows users to setup a client/server to control/run commands from a remote location. Now i'm trying to implement server plugins, and I'm doing that by loading every .vb file in a folder contained inside the current running directory. Everything is great, and the code from the external files compiles just fine... Only problem is, Its returning nothing when I try to compile the script and use one of the methods inside it.
Here's some code for you to check out. My error is in the 2nd. Any idea on how to fix this?
The Interaction Interface:
Public Interface LinkingInterface
Property name As String
Property statetag As String
Sub selected(ByVal Sock As Integer)
Sub deselected(ByVal Sock As Integer)
Sub load()
Function generateOutput(ByVal input As String, ByVal Sock As Integer) As String
End Interface
Detection/Loading of the "Modes" (add-ins):
For Each file In My.Computer.FileSystem.GetFiles("modes\")
Dim thisMode As LinkingInterface = LoadMode(My.Computer.FileSystem.ReadAllText(file))
thisMode.load() '<---------------------------My error is here, saying its a null ref.
modes_InterfaceCollection.Add(thisMode) 'Public modes_InterfaceCollection As New Microsoft.VisualBasic.Collection()
modes_nameIndex.Add(thisMode.name) 'Public modes_nameIndex As New Specialized.StringCollection()
Next
'LoadMode' Function
Public Function LoadMode(ByVal code As String) As LinkingInterface
Using provider As New VBCodeProvider()
Dim parameters As New CompilerParameters()
parameters.GenerateInMemory = True
parameters.ReferencedAssemblies.Add(Reflection.Assembly.GetExecutingAssembly().Location)
parameters.MainClass = "Remote_Command_Line.MainModule"
Dim interfaceNamespace As String = GetType(LinkingInterface).Namespace
Dim codeBuilder As New Text.StringBuilder
Dim namespaces() As String = New String() {"Microsoft.VisualBasic", "System", "System.Console", "System.Collections", "System.Collections.Generic", _
"System.Data", "System.Diagnostics", "Remote_Command_Line.MainModule"}
Dim codeString As New StringBuilder
For Each namespacestring As String In namespaces
codeString.AppendLine("Imports " & namespacestring)
Next
codeString.AppendLine(code)
Dim results As CompilerResults = provider.CompileAssemblyFromSource(parameters, codeString.ToString)
'I commented out this just for debugging purposes
'If results.Errors.HasErrors Then
'For Each scriptError As CompilerError In results.Errors
'WriteLine(scriptError.ToString)
'Next
'Else
Return CType(results.CompiledAssembly.CreateInstance(results.CompiledAssembly.GetType.Name), LinkingInterface)
'End If
End Using
End Function
The Testing file 'test.vb':
Public Class test_mode
'Designed for RCL mode 1.0b
'Matthew 2013
'used for managing the local filesystem.
'####################################
#Region "Properties"
'all of these properties listed are required --------------------
Implements LinkingInterface
Property name As String Implements LinkingInterface.name 'the name the client refers to you in the 'modeswitch' command
Property statetag As String Implements LinkingInterface.statetag 'short tag displayed on the client when active before the input signal '>'
'----------------------------------------------------------------
Public curDirDatabank As New Specialized.StringCollection()
#End Region
'####################################
'####################################
#Region "Subs"
'Its required to have, but not required to do anything. This load sub is here for any modes that may require an initialization
Private Sub load() Implements LinkingInterface.load 'REQUIRED
name = "file" : statetag = "file"
MsgBox("Testing: It's loaded")
End Sub
Private Sub selected(ByVal Sock As Integer) Implements LinkingInterface.selected
MsgBox("Testing: '" & Sock & "' selected the File mode")
End Sub
Private Sub deselected(ByVal Sock As Integer) Implements LinkingInterface.deselected
MsgBox("Testing: '" & Sock & "' deselected the File mode")
End Sub
Private Function generateOutput(ByVal input As String, ByVal Sock As Integer) As String Implements LinkingInterface.generateOutput 'REQUIRED
Return ("Testing: '" & Sock & "' said '" & input & "'")
End Function
#End Region
'####################################
End Class
the following line is wrong.
Return CType(results.CompiledAssembly.CreateInstance(results.CompiledAssembly.GetType.Name), LinkingInterface)
You need to search through the loaded classes for one implementing your interface (it being VB you automatically get classes generated for the My namespace objects such as My.Computer)
Try this instead
For Each t As Type In results.CompiledAssembly.GetTypes()
If t.GetInterface(GetType(LinkingInterface).Name) IsNot Nothing Then
Return CType(results.CompiledAssembly.CreateInstance(t.Name), LinkingInterface)
End If
Next
Return Nothing

Writing Entries in a VB Dictionary into a Text File

I'm working on VB in college and am running into a snag with one of my assignments. Can someone help? I'm aiming to try to take the following dictionary code:
Public Class Inventory
Public ItemInventory As New Dictionary(Of String, Item)
Public Function iItem(ByVal key As String) As Item
Return ItemInventory(key)
End Function
Public Sub addItem(ByVal item As String, ByVal Desc As String, ByVal DRate As Double, ByVal WRate As Double, _
ByVal MRate As Double, ByVal Quantity As Integer)
With ItemInventory
.Add(item, New Item(item, Desc, DRate, WRate, MRate, Quantity))
End With
End Sub
Public Sub removeItem(ByVal item As String)
With ItemInventory
.Remove(item)
End With
End Sub
Public Function returnKeys() As String()
Dim Keys() As String
With ItemInventory
Keys = .Keys.ToList.ToArray
End With
Return Keys
End Function
End Class
Not pretty, I know, but it gets the job done, that's all I aim to do. Now a bit of this also has to do with displaying a dictionary item in the program, which I'm also having issues with, however, I'd like to take this one step at a time, so we'll get to that later, if possible.
As per writing, this is my current code for reading and writing:
Imports System.IO
Public Class InventoryFile
Public Sub RFile(ByVal FPath As String, ByRef dInventory As Inventory)
Dim infile As StreamReader = File.OpenText(FPath)
Dim entireLine As String = infile.ReadLine()
Dim fields() As String = entireLine.Split(","c)
While infile.EndOfStream
Dim dItem As New Item
dItem.ID = fields(0)
dItem.Description = fields(1)
dItem.Daily = fields(2)
dItem.Weekly = fields(3)
dItem.Monthly = fields(4)
dItem.Quantity = fields(5)
'AddItem
dInventory.addItem(dItem.ID, dItem.Description, dItem.Daily, dItem.Weekly, _
dItem.Monthly, dItem.Quantity)
End While
End Sub
Public Sub WFile(ByVal FPath As String, ByRef dInventory As Inventory)
Dim outfile As StreamWriter = File.CreateText(FPath)
For Each Item As KeyValuePair(Of String, Item) In dInventory.ItemInventory
Next
End Sub
End Class
I hope that posted right. Now, reading in, as far as I understand, works just fine, in terms of a file going into a dictionary, however 'WFile', my StreamWriter, is what's got me stumped. Can someone help me with that? Likewise, its supposed to close and write to the file upon closing, and my only code for the close button is the Me.Close() command. How would I write a trigger to make the program write to the file? Know that the main form code, and my 'InventoryFile' are both separate classes, so this has to be done by referencing the other classes in question
Try this to write each dictionary key/value pair on a single line in the file:
Dim fs As FileStream
' Open the stream and write to it.
fs = File.OpenWrite(FPath)
For Each Item As KeyValuePair(Of String, Item) In dInventory.ItemInventory
fs.Write("{0}:{1}", Item.Key, Item.Value)
Next
UPDATE:
Since Item is both the variable used in the loop and the name of a class, change it to another name like singleItem and then pull out the other pieces of information from the Value portion of the key/value pair, because the Value is actually an Item class object, like this:
Dim fs As FileStream
' Open the stream and write to it.
fs = File.OpenWrite(FPath)
For Each singleItem As KeyValuePair(Of String, Item) In dInventory.ItemInventory
fs.Write("{0}:{1}:{2}:{3}:{4}:{5}:{6}", singleItem.Key, singleItem.Value.ID, singleItem.Value.Description, singleItem.Value.Daily, singleItem.Value.Weekly, singleItem.Value.Monthly, singleItem.Value.Quantity)
Next
In order to create the format your RFile procedure can read you need something like this:
For Each kvp As KeyValuePair(Of String, Item) In dInventory.ItemInventory
' using Karl's compact approach, but add commas
' since your Read expects them
outfile.Write("{0},{1},{2},{3},{4}...", kvp.Key, kvp.Value.ID, _
kvp.Value.Description, ... kvp.Value.Quantity.Tostring)
' the Value part of the fvp is another class, right? `Value.XXX` should drill
' into it to get to the members
Next
outfile.flush
outfile.close ' look into 'Using...'
Thats NOT how I would do it, look into serialization for a less fragile way to read/write the data. It is basically meant for just this sort of thing: save class data for later, and it is not that hard to use.
as for hooking it up, the button click would just call Inventory.WFile

Function call from Arraylist element not working

I am trying to get a function for a class assignment to work however as the program hits the specific line in question it dies off and nothing after this line will execute. The program does not lock up, just the current execution path dies.
I have tried running debugging but much the same happens. Once I hit the link that should call a function from the object stored in the Arraylist element the break point at the actual function that should be called is not hit and nothing further happens.
Public Structure Appliances
' Create New Appliance object
Public Sub New(name As String, pusage As Double)
aName = name
aPUsage = pusage
End Sub
' Create New Washer Object
Public Sub New(name As String, pusage As Double, wusage As Double)
aName = name
aPUsage = pusage
aWUsage = wusage
End Sub
' Functions
Public Function getAName()
Return aName
End Function
Public Function getAPUsage()
Return aPUsage
End Function
Public Function getAWUsage()
Return aWUsage
End Function
Dim aName As String ' Appliance Name
Dim aPUsage As Double ' Appliane Power Usage
Dim aWUsage As Double ' Appliance Water Usage
End Structure
...
Public Class Form1
...
Dim appList As New ArrayList() ' Create an arraylist appliance objects
Public appTemp As Appliances ' To store appliance objects until they can be added to the arraylist
...
Private Function getAppInfo()
getAppInfo = Nothing
Do While fInStream.Peek() <> -1
s = fInStream.ReadLine() ' Get a line from the file and set s to it
Dim words As String() = s.Split(New Char() {","c}) ' Split the line contents along commas and set those parts into words
words(0) = words(0).Replace("_", " ") ' Reaplce underscores with spaces
If (words.Count = 3) Then ' If words contains the washer appliance
appTemp = New Appliances(words(0), Double.Parse(words(1)), Double.Parse(words(2)))
appList.Add(appTemp)
Else ' For all other appliances
appTemp = New Appliances(words(0), Double.Parse(words(1)))
appList.Add(appTemp)
End If
Loop
End Function
Private Function setUsage(name As String)
setUsage = Nothing
' Find appliance
For i = 0 To appList.Count
If (name = appList(i).getAName()) Then
If (name = "Washer") Then
s = appList(i).getWUsage() ' !!!This is the line where the execution dies at, nothing after this line is processed and the function call is not completed
txtbGPH.Text = s
End If
MsgBox("Test 1")
Exit For
ElseIf (i = appList.Count) Then
MsgBox("Appliance could not be found")
End If
Next
End Function
End Class
Use a List(Of X) instead of ArrayList if you are going to insert only one type:
Dim appList As New List(Of Appliances)
And I recommend you to declare your temp var inside the methods unless is necessary. Anyway, in this case you don't need it, you can add your var in this way:
appList.Add(New Appliances(words(0), Double.Parse(words(1))))
With this use (using lists) you won't need to use arraylistObj.Item(i).Method() and you can simply use the common way:
s = appList(i).getWUsage()
Nevermind, I figured it out just now. I did not know that arraylists are not "arraylists" but a collection. I thought maybe it would act like other collection oriented objects and that you have to use a .item(i) to access the elements, which turns out to be the case.
txtbGPH.text = appList.item(i).getAWusage()
produces the proper behavior and the rest of the code after the problematic line indicated in the OP executes as does the break point set at the called function.

Strange error reported in this code, please explain?

I put together this bit of code from a few other samples, and I am getting an error I cant understand. On this line in the code below, on the word Observer,
Dim Results As ManagementObjectCollection = Worker.Get(Observer)
I get the error
"Value of type 'System.Management.ManagementOperationObserver' cannot be converted to 'Integer'"
Can somebody explain what this means?
There are two signatures for ManagementObjectSearcher.Get(), one has no parameters and the other has one parameter, a ManagementOperationObserver for async operation. That is what I am providing, yet the error indicates conversion involving an integer?
Public Shared Sub WMIDriveDetectionASYNC(ByVal args As String())
Dim Observer As New ManagementOperationObserver()
Dim completionHandler As New MyHandler()
AddHandler Observer.Completed, AddressOf completionHandler.Done
Dim Machine = "192.168.0.15"
Dim Scope = New ManagementScope("\\" & Machine & "\root\cimv2")
Dim QueryString = "select Name, Size, FreeSpace from Win32_LogicalDisk where DriveType=3"
Dim Query = New ObjectQuery(QueryString)
Dim Worker = New ManagementObjectSearcher(Scope, Query)
Dim Results As ManagementObjectCollection = Worker.Get(Observer) 'use parameter to make async
For Each item As ManagementObject In Results
Console.WriteLine("{0} {2} {1}", item("Name"), item("FreeSpace"), item("Size"))
Dim FullSpace As Long = (CLng(item("Size")) - CLng(item("FreeSpace"))) \ 1000000
Console.WriteLine(FullSpace)
Next
End Sub
Public Class MyHandler
Private _isComplete As Boolean = False
Public Sub Done(sender As Object, e As CompletedEventArgs)
_isComplete = True
End Sub 'Done
Public ReadOnly Property IsComplete() As Boolean
Get
Return _isComplete
End Get
End Property
End Class
Thanks for any advice!
I think that uses a reference type to get the result and put it in the object you sent as a parameter. So I think it just needs to look like:
Worker.Get(Observer)
instead of trying to set something = to that since it isn't a function that returns a value.
Then use the events you hook up to the object to handle whatever you need to do with the items you find.