Get hardware manufacturer and system model number in VB.net? - vb.net

I'm trying to get the hardware manufacturer (e.g. "Dell") and the model number (e.g. "Latitude E6320") using vb.net but I'm having no luck.
I've tried
Dim opSearch As New ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem")
Dim opInfo As ManagementObject
For Each opInfo In opSearch.Get()
Return opInfo("manufacturer").ToString()
Next
Though this returns "Microsoft Corporation" not "Dell".

You are polling the wrong WMI class/hive. Of course Microsoft is the OS manufacturer; what you need is Win32_ComputerSystem:
Imports System.Management
cs = New ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem")
For Each objMgmt In cs.Get
_Manufacturer = objMgmt("manufacturer").ToString()
_Model = objMgmt("model").ToString()
_SystemType = objMgmt("systemtype").ToString
_totalMem = objMgmt("totalphysicalmemory").ToString()
Next
Manufacturer will be something like "Dell, Inc", Model comes out spot on with mine, but has been known to sometimes include internal sub model identifiers. System type comes back as "x64-based PC" on mine.
MS has a WMI query builder somewhere to help fnd and use the right query, though it generates very wordy code.

Give this a try in a console application. Just remember to add the System.Management reference to your project. You need to access the Win32_ComputerSystem not the Win32_OperatingSystem.
Sub Main()
Dim objCS As Management.ManagementObjectSearcher
Dim manufacturerName As String
'objOS = New Management.ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem")
objCS = New Management.ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem")
For Each objMgmt In objCS.Get
manufacturerName = objMgmt("manufacturer").ToString()
Next
Debug.WriteLine("Manufacturer: " & manufacturerName)
End Sub
Hope it helps.

Related

VB.net insert .msg file into access database [duplicate]

I'm writing a VB application where I need to store an image in the database. The user selects the image on their computer, which gives me the path as a string. Here's my attempt at it, however I'm getting the error "An INSERT INTO query cannot contain a multi-valued field."
Here is my code:
Dim buff As Byte() = Nothing
Public Function ReadByteArrayFromFile(ByVal fileName As String) As Byte()
Dim fs As New FileStream(fileName, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fs)
Dim numBytes As Long = New FileInfo(fileName).Length
buff = br.ReadBytes(CInt(numBytes))
Return buff
End Function
Sub ....
Dim connImg As New OleDbConnection
Dim sConnString As String
Dim cmdImg As New OleDbCommand
sConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Settings.DB & ";Persist Security Info=False;"
connImg = New OleDbConnection(sConnString)
connImg.Open()
cmdImg.Connection = connImg
cmdImg.CommandType = CommandType.Text
If d.slogo <> "" Then
cmdImg.CommandText = "INSERT INTO Logo ( refId, [type], [img] ) VALUES(#refId, #type, #imgBinary)"
cmdImg.Parameters.Add("#refId", OleDbType.Double).Value = refId
cmdImg.Parameters.Add("#type", OleDbType.Double).Value = 0
cmdImg.Parameters.Add("#imgBinary", OleDbType.VarBinary).Value = ReadByteArrayFromFile(PathToImage)
cmdImg.ExecuteNonQuery()
End If
....
End Sub
I've tried searching for other solutions online, but it seems everything I find is VB6 or VBA code. And I know people are going to argue that images should not be stored in the database, but in this case, it is my only option.
Thank-you for any help!
As you have discovered, you cannot use a SQL statement to insert files into an Attachment field in an Access database. You have to use the LoadFromFile() method of an ACE DAO Field2 object. The following C# code works for me. It is adapted from the Office Blog entry here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Access.Dao;
namespace daoConsoleApp
{
class Program
{
static void Main(string[] args)
{
// This code requires the following COM reference in your project:
//
// Microsoft Office 14.0 Access Database Engine Object Library
//
var dbe = new DBEngine();
Database db = dbe.OpenDatabase(#"C:\__tmp\testData.accdb");
try
{
Recordset rstMain = db.OpenRecordset(
"SELECT refId, img FROM Logo WHERE refId = 1",
RecordsetTypeEnum.dbOpenDynaset);
if (rstMain.EOF)
{
// record does not already exist in [Logo] table, so add it
rstMain.AddNew();
rstMain.Fields["refId"].Value = 1;
}
else
{
rstMain.Edit();
}
// retrieve Recordset2 object for (potentially multi-valued) [img] field
// of the current record in rstMain
Recordset2 rstAttach = rstMain.Fields["img"].Value;
rstAttach.AddNew();
Field2 fldAttach =
(Field2)rstAttach.Fields["FileData"];
fldAttach.LoadFromFile(#"C:\__tmp\testImage.jpg");
rstAttach.Update();
rstAttach.Close();
rstMain.Update();
rstMain.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
I did the same thing based off of the above code and the blog entry from here.
Here is my vb.net code which allows me to do an OpenFileDialog and multiple selections and the function will handle storing multiple files just fine. Though I did have to add a reference to my project for Microsoft Office 15.0 Access database engine Object Library to get it to work properly. I think you can go down to 12.0 or 14.0 as well.
Private Sub AddAttachment(ByVal Files() As String)
Const Caller = "AddAttachment"
Dim dbe = New Microsoft.Office.Interop.Access.Dao.DBEngine()
Dim db As Microsoft.Office.Interop.Access.Dao.Database
db = dbe.OpenDatabase(dbPath)
Try
Dim rstMain As Microsoft.Office.Interop.Access.Dao.Recordset
rstMain = db.OpenRecordset("SELECT ID, fieldName FROM tableName WHERE ID = " + (dt.Rows(currentRow).Item("ID").ToString), Microsoft.Office.Interop.Access.Dao.RecordsetTypeEnum.dbOpenDynaset)
If (rstMain.EOF) Then
rstMain.AddNew()
rstMain.Fields("ID").Value = 1
Else
For Each value As String In Files
rstMain.Edit()
Dim rstAttach As Microsoft.Office.Interop.Access.Dao.Recordset2
rstAttach = rstMain.Fields("ATTACHMENTS").Value
rstAttach.AddNew()
Dim fldAttach As Microsoft.Office.Interop.Access.Dao.Field2
fldAttach = rstAttach.Fields("FileData")
fldAttach.LoadFromFile(value)
rstAttach.Update()
rstAttach.Close()
Next
rstMain.Update()
rstMain.Close()
End If
Catch ex As Exception
If Err.Number <> 3820 Then
MsgBox(ex.Message)
Else
MsgBox("File of same name already attached", MsgBoxStyle.Critical, "Cannot attach file" & Caller)
MessageBox.Show(ex.Message)
End If
End Try
End Sub
I'm now working on the functions to RemoveAttachments and save files from the attachements field. I'll post those here later.
Another thing to add to this. If your database is encrypted then you will need to add to the OpenDatabase command.
This is the code I used in C# but the VB.NET code will be very similiar.
db = dbe.OpenDatabase(dbPath, false, false,"MS Access;PWD=password");
It took me ages to try and track this down on my own and I will try break down the various parts of the method. The MSDN Article for it can be found here.
1st Argument: dbPath, that's the same as the usage in the original post. The location and filename of the database you want to open.
2nd Argument: false. This is a true/false argument that if true opens the database in Exclusive-Mode. So that only this single program can use it. Most of the time this should be false. Only use exclusive mode if you have to.
3rd Argument: false. This is another true/false argument. This time if it's true then it opens the database in Read-only mode.This means you can only use recordsets to read information and you cannot use the Edit, Add or Delete methods. This can be true or false depending on your needs.
4th Argument: This sets specific properties in how to open the database. In this case. It says to set the Microsoft Access property 'PWD' to 'password'. In this property setting will tell method to open up an encrypted database using the password 'password'. Of course you will need to change "password" to whatever the database's actual password is to open but I'd been hunting this down for a while.
I hope this helps.

Pulling Hardware Serial Number via Visual Basic?

I am writing an application in Visual Basic that pulls basic information about the computer and outputs the data onto a form. Currently, I am trying to pull the serial number for the machine I would be using. For example, pulling a serial number of a laptop from the BIOS. I have looked around the internet and haven't really found how to do this in Visual Basic without using WMI or C. Is there a way to do this in Visual Basic?
Below is what I have currently in the form, so you can get an idea of what I am trying to do:
TextBoxComputerName.Text = Environment.MachineName
TextBoxOSVersion.Text = System.Environment.OSVersion.ToString
TextBoxOSFullName.Text = My.Computer.Info.OSFullName
TextBoxCurrentUser.Text = System.Environment.UserName
TextBox64Bit.Text = System.Environment.Is64BitOperatingSystem
TextBoxSystemDirectory.Text = System.Environment.SystemDirectory
TextBoxDomain.Text = System.Environment.UserDomainName
' CHECK SERIAL NUMBER HERE.
Thank you all so much!
This will work for you just great! First add reference to System.Management and then make sure to import it at the top of your class as well. I did this on a form load event, but you can put it anywhere...
Imports System.Management
Dim q As New SelectQuery("Win32_bios")
Dim search As New ManagementObjectSearcher(q)
Dim info As New ManagementObject
For Each info In search.Get
MessageBox.Show("Serial Number: " & info("serialnumber").ToString & vbNewLine & vbNewLine & "Bios Version: " & info("version").ToString)
Next
You can declare a string first if you would like and then set it to: info("serialnumber").ToString and the set that to you txtSerial.Text = your declared string
Here is what I get...
This is VBScript but should be pastable into VB6.
You do know this field is blank on many computers?
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_BIOS")
For Each objItem in colItems
msgbox objItem.SerialNumber
Next
From a command prompt (but I don't think home editions get the console program wmic)
wmic bios get /format:list
or
wmic bios get serialnumber /format:list
Try to use Treek's Licecnsing Library. It has class for generating hardware serial.
http://msdn.treekslicensinglibrary.com/html/f2bfa10c-d5d9-25ac-39c2-46e2393c0fbe.htm
Here is a class that will return:
*) Computer Name
*) Assembly Name
*) Login User Name
*) Serial No
Imports System.Management
'''
''' Provides the Methods and Properties to retrieve and make available to the
''' Application the:
''' *) Computer Name
''' *) Assembly Name
''' *) Login User Name
''' *) PC Serial Number
'''
'''
Public Class clsGetComputerInformation
Private ReadOnly mstrClsTitle As String = "clsGetComputerInformation"
Public ReadOnly Property pstrComputerName() As String
Get
Return Environment.MachineName
End Get
End Property
Public ReadOnly Property pstrUserName() As String
Get
Return System.Security.Principal.WindowsIdentity.GetCurrent.Name
End Get
End Property
Public ReadOnly Property pstrAssemblyName() As String
Get
Return My.Application.Info.AssemblyName
End Get
End Property
Public Function pstrSystemSerialNumber() As String
Dim query As New SelectQuery("Win32_bios")
Dim search As New ManagementObjectSearcher(query)
Dim info As ManagementObject
Dim lstrSerialNo As String = ""
For Each info In search.Get()
lstrSerialNo = info("SerialNumber").ToString()
Next
Return lstrSerialNo
End Function
End Class
I found a way to get to this a bit backwards in VBA, using the FileSystemObject. You will need to set a reference to the Windows Scripting Runtime.
Option Explicit
Public Sub GetHDSerial()
Dim objFSO As FileSystemObject
Dim objFolder As Folder
Dim strComputer As String
strComputer = "myComputer"
Set objFSO = New FileSystemObject
Set objFolder = objFSO.GetFolder("\\" & strComputer & "\c$")
Debug.Print Hex(objFolder.Drive.SerialNumber)
Set objFSO = Nothing
Set objFolder = Nothing
End Sub
This does not account for multiple physical drives, which wasn't a problem in my environment.

VB.NET Remove user from active directory

Hi I am trying to create a VB.NET application which will (hopefully) reduce some time spent on some of my departments helpdesk calls. The part that I am stuck with is how to use VB.NET to remove a user from a group. The following is code that I have been playing with:
Public Shared Sub RemoveUserFromGroup(ByVal deUser As String, ByVal GroupName As String)
Dim entry As DirectoryEntry = ADEntry()
Dim mySearcher As DirectorySearcher = New DirectorySearcher(entry)
mySearcher.Filter = "(&(ObjectClass=Group)(CN=" & GroupName & "))"
mySearcher.PropertiesToLoad.Add("OrganizationalUnit")
mySearcher.PropertiesToLoad.Add("DistinguishedName")
mySearcher.PropertiesToLoad.Add("sAMAccountName")
Dim searchResults As SearchResultCollection = mySearcher.FindAll()
If searchResults.Count > 0 Then
Dim group As New DirectoryEntry(searchResults(0).Path)
Dim members As Object = group.Invoke("Members", Nothing)
For Each member As Object In CType(members, IEnumerable)
Dim x As DirectoryEntry = New DirectoryEntry(member)
MessageBox.Show(x.Properties("sAMAccountName").Value)
If x.Properties("sAMAccountName").Value = deUser Then
MessageBox.Show(searchResults.Item(0).Path.ToString)
MessageBox.Show(x.Properties("sAMAccountName").Value)
'group.Invoke("Remove", New Object() {x.Properties("OrganizationalUnit").Value})
group.Properties("member").Remove(x.Properties("OrganizationalUnit").Value)
End If
Next
End If
When I run the program, I recevie a COMException was unhandled, unspecified error at the group.properties line. When using group.invoke I receive the error TargetInvocationException was unhandled.
My aim is to pass as a string the username (sAMAccountName) and the groupname (sAMAccountName) to the function which will locate the user and remove them from the group.
I am new to VB.NET and would appreciate any assistance people can provide.
I am coding in .NET 2.0 as I am unsure if the server it will live on will have 3.5 installed.
Well the error message 0x80004005 E_FAIL Unspecified failure is not very helpful. I often get frustrated when working with Active Directory.
Try changing line:
group.Properties("member").Remove(x.Properties("OrganizationalUnit").Value)
to
group.Invoke("Remove", New Object() {x.Path.ToString()})
If you need more reference take a look at this article on VB.net Heaven by Erika Ehrli. The article covers various use cases with Active Directory.
I hope that helps.

Getting a list of users on a network domain

I want to get back to get a list of users on a network domain using VB.Net.
I will have the domain name available to me for use.
Thanks in advance.
It might throw an error in the select query.
Please check this:
Did you add a reference to the System.Management assembly to your project? If you haven't, do this:
In VS, click on Project menu > add reference.
On the .Net tab, scroll down until you see System.Management. Click on it to select, then click OK.
Now back in your code, at the very top of your class, put in "Imports System.Management", and you should be all set.
Source:
http://www.vbforums.com/showthread.php?t=560422
It worked for me without any issues. I am able to get all user names for the domain.
Something like this might point you in the right direction, using System.DirectoryServices and System.DirectoryServices.ActiveDirectory:
Private Function GetDomainUsers(ByVal domainDirectoryEntry As DirectoryEntry, ByRef userList As IList) As Integer
Try
userList = New ArrayList()
Using domainDirectoryEntry
Dim ds As New DirectorySearcher(domainDirectoryEntry, "(&(objectCategory=person)(objectClass=user))", New String() {"distinguishedName"})
Using src As SearchResultCollection = ds.FindAll()
For Each sr As SearchResult In src
userList.Add(sr.Properties("distinguishedName")(0))
Next
End Using
End Using
Return userList.Count
Catch generatedExceptionName As Exception
userList = Nothing
Return -1
Finally
domainDirectoryEntry = Nothing
End Try
End Function
Imports System.Management
Imports System.Management.Instrumentation
Sub PrintDomainUsers()
Dim domainName As String = System.Environment.UserDomainName.ToString
Dim userQuery As SelectQuery = New SelectQuery("Win32_UserAccount", "Domain='" & domainName & "'")
Try
Dim userSearch As ManagementObjectSearcher = New ManagementObjectSearcher(userQuery)
For Each domainUser In userSearch.Get
Console.WriteLine(domainUser("Name"))
Next
Catch ex As Exception
Throw ex
End Try
End Sub
This works but how do i filter by a certain group. Im getting THOUSANDS of resutls
Another option would be exploring System.Management and System.Management.Instrumentation.Here is a short snippet of how you pull the users of a particular domain using these namespaces.
Imports System.Management
Imports System.Management.Instrumentation
Sub PrintDomainUsers()
Dim domainName As String = System.Environment.UserDomainName.ToString
Dim userQuery As SelectQuery = New SelectQuery("Win32_UserAccount", "Domain='" & domainName & "'")
Try
Dim userSearch As ManagementObjectSearcher = New ManagementObjectSearcher(userQuery)
For Each domainUser In userSearch.Get
Console.WriteLine(domainUser("Name"))
Next
Catch ex As Exception
Throw ex
End Try
End Sub

How to do Mailmerge in Openoffice using Vb.net

Its 5th Question and apart of one I didn't get response from the experts....
Hope this time I will get the helping hand.
I want to do mailmerge in openoffice using Vb.net and I am totally new with openoffice.
I searched on net for some help to understand how to use openoffice with vb.net but all I get is half info.....So can you please help me and give me code for mailmerge in vb.net for openoffice.
Well i have list of workers in DB and there is this facility that if they want to mail to all or some of the workers then they can do it.I have completed this task using Microsoft Office now as a Add in we are providing the facility to perform the same task using Open Office.
What they have to do is just select the List of workers and click on a button and it will automate the mailmerge using the field of those workers data from DB. The Code of mine is as shown below
Public Sub OpenOfficeMail(ByVal StrFilter As String)
Dim oSM ''Root object for accessing OpenOffice from VB
Dim oDesk, oDoc As Object ''First objects from the API
Dim arg(-1) ''Ignore it for the moment !
''Instanciate OOo : this line is mandatory with VB for OOo API
oSM = CreateObject("com.sun.star.ServiceManager")
''Create the first and most important service
oDesk = oSM.createInstance("com.sun.star.frame.Desktop")
''Create a new doc
oDoc = oDesk.loadComponentFromURL("private:factory/swriter", "_blank", 0, arg)
''Close the doc
oDoc.Close(True)
oDoc = Nothing
''Open an existing doc (pay attention to the syntax for first argument)
oDoc = oDesk.loadComponentFromURL("file:///C:\Users\Savan\Documents\1.odt", "_blank", 0, arg)
Dim t_OOo As Type
t_OOo = Type.GetTypeFromProgID("com.sun.star.ServiceManager")
Dim objServiceManager As New Object
objServiceManager = System.Activator.CreateInstance(t_OOo)
Dim oMailMerge As New Object
oMailMerge = t_OOo.InvokeMember("createInstance", Reflection.BindingFlags.InvokeMethod, Nothing, _
objServiceManager, New [Object]() {"com.sun.star.text.MailMerge"}) 'com.sun.star.text.MailMerge"})
oMailMerge.DocumentURL = "file:///C:\Users\Savan\Documents\1.odt"
oMailMerge.DataSourceName = CreateSource(StrFilter)''Function that will return the datasource name which will be a text file's path
oMailMerge.CommandType = 0
oMailMerge.Command = "file:///C:\Mail.txt"
oMailMerge.OutputType = 2
oMailMerge.execute(New [Object]() {})**---->I am getting Error here**
End Sub