How to determine windows build number using vb.net or c#? - vb.net

How to determine windows build number using vb.net or c#? I do not want to use win32 API.

System.OperatingSystem osInfo = System.Environment.OSVersion;
http://support.microsoft.com/kb/304283
more detailed blog post : http://andrewensley.com/2009/06/c-detect-windows-os-part-1/

The HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion registry key should contain it. I'm not sure if you can reference it without the win32 API, but you might be able to...

corsiKa got me on the right track, but it very much depends on what you need. I wanted the full build number, which changes with every Windows 10 Cumulative Update. (ex. 16299.192)
The WMI method is good, but only gets you 10.0.16299, which is the overall release. I used the WMI Code Creator to poke around, but couldn't find the "192" part in WMI.
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\UBR
Has the 192 part of the build number.
I settled on this code to get 10.0.16299.192:
Function GetOSVersion() As String
Dim strBuild1, strBuild2, strBuild3, strBuild4 As String
Dim regKey As Microsoft.Win32.RegistryKey
regKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion")
strBuild1 = regKey.GetValue("CurrentMajorVersionNumber")
strBuild2 = regKey.GetValue("CurrentMinorVersionNumber")
strBuild3 = regKey.GetValue("CurrentBuild")
strBuild4 = regKey.GetValue("UBR")
Return strBuild1 & "." & strBuild2 & "." & strBuild3 & "." & strBuild4
End Function

You can get it through WMI. .Net 2.0
Imports System.Management
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Call GetOSVersion()
End Sub
Private Sub GetOSVersion()
Dim sCaption As String = String.Empty
Dim sVersion As String = String.Empty
Dim searcher As New ManagementObjectSearcher("root\CIMV2", _
"SELECT * FROM Win32_OperatingSystem")
For Each queryObj As ManagementObject In searcher.Get()
sCaption = DirectCast(queryObj("Caption"), String)
sVersion = DirectCast(queryObj("Version"), String)
Next
Debug.WriteLine("OS: " & sCaption & " Ver " & sVersion)
End Sub
End Class

Related

VB.NET: Can't load audio from resources

I'm trying to add multiple sounds on an application using a Public function... When I use the absolute path for my sounds everything works perfectly, but when I'm trying to load them from Resources I don't get any sound output.. Any ideas what's wrong?
Public Class Form1
Public Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer
Dim musicAlias As String = "myAudio"
'Dim musicPath As String = "C:\Users\Teo\Documents\Visual Studio 2015\Projects\test\test\Resources\sound.mp3"
'Dim musicPath As String = "Resources\sound.mp3"
'Dim musicPath As String = My.Resources.ResourceManager.GetObject("sound.mp3")
Dim musicPath2 As String = "C:\Users\Teo\Desktop\sound.mp3"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
mciSendString("Open " & musicPath & " alias " & musicAlias, CStr(0), 0, 0)
mciSendString("play " & musicAlias, CStr(0), 0, 0)
End Sub
End Class
The last one works perfectly, I tried every one of the above... The three comments above are different ways I tried to make it work, but all failed...
You can load the file from resources and cache them locally and play them.
Open Resources.resx file under My Project. Then add your file for example YourFileName.mp3 to the resources by choosing Add Existing File... then when you want to play the file, use this code:
Dim file As String = System.IO.Path.Combine(Application.StartupPath, "YourFileName.mp3")
If (Not System.IO.File.Exists(file)) Then
System.IO.File.WriteAllBytes(file, My.Resources.YourFileName)
End If
'Now the file exists locally
'Play the file here
I know this has an answer marked correct, but once you have a sound file in your Resources, it's much easier this way:
My.Computer.Audio.Play(My.Resources.MyCoolSound, AudioPlayMode.Background)
No reason to use an API call.

how to get the argument of ffmpeg process in vb.net?

i am writing a simple program to get the all the properties of a process like ffmpeg . i got most properties of predefined functions but i want to know the argument which i gave to the ffmpeg in vb.net?
For Each prog As Process In Process.GetProcesses
If prog.ProcessName = "ffmpeg" Then
al.Add(prog.Id)
End If
Next
For Each id In al
Dim p As Process = Process.GetProcessById(id)
listBox3.Items.Add(Process.GetProcessById(id).ProcessName)
ListBox3.Items.Add(p.BasePriority)
ListBox3.Items.Add(p.HandleCount)
ListBox3.Items.Add(p.Id)
ListBox3.Items.Add(p.MainWindowTitle)
ListBox3.Items.Add(p.MaxWorkingSet)
ListBox3.Items.Add(p.MinWorkingSet)
ListBox3.Items.Add(p.PriorityBoostEnabled)
ListBox3.Items.Add(p.PriorityClass)
ListBox3.Items.Add(p.PrivilegedProcessorTime)
ListBox3.Items.Add(p.ProcessName)
ListBox3.Items.Add(p.ProcessorAffinity)
ListBox3.Items.Add(p.StartTime)
ListBox3.Items.Add(p.TotalProcessorTime)
ListBox3.Items.Add(p.UserProcessorTime)
lastBox3.Items.Add(p.WaitForInputIdle)
ListBox3.Items.Add("========================")
Next id
Using Jesse Slicer's code as a base from here:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each proc As Process In Process.GetProcessesByName("ffmpeg")
Debug.Print("ID: " & proc.Id)
Debug.Print("Arguments: " & proc.GetCommandLine)
Debug.Print("------------------------------")
Next
End Sub
End Class
Public Module Extensions
<Runtime.CompilerServices.Extension()>
Public Function GetCommandLine(ByVal proc As Process) As String
' Project --> Add Reference --> System.Management
Dim arguments As New System.Text.StringBuilder
Using searcher As New Management.ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " & proc.Id)
For Each arg In searcher.Get
arguments.Append(arg("CommandLine") & " ")
Next
End Using
Return arguments.ToString.Trim
End Function
End Module
Note that you need to add the System.Management reference, and I made the function an extension method of the Process class.
ffmpeg is open source, so Might it will be useful:
https://ffmpeg.org/documentation.html

Windows webserivce starts and stops automatically

This message is displayed when running my windows service.
The [service name] service on local computer started and then stopped.
Some Services stop automatically if they are not in use by another services or programs.
I am not sure what is causing this error. Below is the code for my service. My code uses another class called MagentoSalesOrder. I ran this code as a console application first and it worked just fine. I believe this what is causing the error. When I comment out the lines that use that class my service runs fine for printing test to a file.
Imports MyFirstService.MagentoSalesOrder
Public Class MyFirstService
Dim WithEvents timer1 As New System.Timers.Timer
Protected Overrides Sub OnStart(ByVal args() As String)
timer1.Interval = 10000
timer1.Start()
WriteLog(Me.ServiceName & " has started ...")
End Sub
Protected Overrides Sub OnStop()
WriteLog(Me.ServiceName & " has stopped ...")
End Sub
Private Sub timer1_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles timer1.Elapsed
WriteLog(Me.ServiceName & " is running ...")
End Sub
Private Sub WriteLog(ByVal strMessage As String)
Dim strPath As String, file As System.IO.StreamWriter
Dim test As New MagentoSalesOrder()
strPath = AppDomain.CurrentDomain.BaseDirectory & "\MyService.log"
file = New System.IO.StreamWriter(strPath, True)
Dim arr = test.BuildPreOrder()
If (arr.Length > 0) Then
For Each element As Long In arr
file.WriteLine("PreOrder created: " + element)
Next
Else
file.WriteLine("No orders to process")
End If
'file.WriteLine("Test")
file.Close()
End Sub
End Class
So I found out my error was coming from the file.writeline in my foreach loop.
Changing element to element.toString in my writefile fixed my service.
The problem came from trying to concatenate a Long to a String.
Changing element to element.toString in my writefile fixed my service.

How to display IPv4 address using VB.net

I found this code on youtube and follow exactly like it. The MAC address and the nic name showed but the IPv4 wont show. Basically i want to show ipv4 address for all network interface inside my computer with the either its connected or not. Here the code
Private Sub getinterface()
'get all network interface available in system
Dim nics As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
If nics.Length < 0 Or nics Is Nothing Then
MsgBox("No network interfaces found")
Exit Sub
End If
'if interfaces are found let list them. first clear the listview items
ListView1.Items.Clear()
For Each netadapter As NetworkInterface In nics
'next lets set variable to get interface properties for later use
Dim intproperties As IPInterfaceProperties = netadapter.GetIPProperties()
'now add the network adaptername to the list
ListView1.Items.Add(netadapter.Name)
'now get the mac address of this interface
Dim paddress As PhysicalAddress = netadapter.GetPhysicalAddress()
Dim addbyte As Byte() = paddress.GetAddressBytes()
Dim macaddress As String = ""
'now loop through the bytes value and change it to hex
For i = 0 To addbyte.Length - 1
macaddress &= addbyte(i).ToString("X2") 'change string to hex
'now let separate hex value with -except last one
If i <> addbyte.Length - 1 Then
macaddress &= "-"
End If
Next
'ount item in listview
Dim icount As Integer = ListView1.Items.Count
'use try
Try
With ListView1.Items(icount - 1).SubItems
.Add(macaddress)
'.Add(intproperties.UnicastAddresses(2).Address.ToString)
.Add(intproperties.AnycastAddresses(2).Address.ToString)
.Add(intproperties.UnicastAddresses(2).IPv4Mask.ToString)
.Add(intproperties.UnicastAddresses(0).Address.ToString)
.Add(intproperties.UnicastAddresses(1).Address.ToString)
'.Add( IPAddress.Parse(a).AddressFamily == AddressFamily.InterNetwork )
End With
Catch ex As Exception
End Try
Next
'now lets make auto size columns
ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
getinterface()
End Sub
Is there a solution for this code or there is another simpler way to do this for display all nic name with its ipv4 address? currently using visual basic express 2010 express
Use WMI queries for this - it will be a lot simpler.
There are some useful classes available - Win32_NetworkAdapterConfiguration & Win32_NetworkAdapter for getting these details. For easy WMI code creation, search for WMI Code Creator
Imports System
Imports System.Management
Imports System.Windows.Forms
Namespace WMISample
Public Class MyWMIQuery
Public Overloads Shared Function Main() As Integer
Try
Dim searcher As New ManagementObjectSearcher( _
"root\CIMV2", _
"SELECT * FROM Win32_NetworkAdapterConfiguration")
For Each queryObj As ManagementObject in searcher.Get()
Console.WriteLine("-----------------------------------")
Console.WriteLine("Win32_NetworkAdapterConfiguration instance")
Console.WriteLine("-----------------------------------")
If queryObj("IPAddress") Is Nothing Then
Console.WriteLine("IPAddress: {0}", queryObj("IPAddress"))
Else
Dim arrIPAddress As String()
arrIPAddress = queryObj("IPAddress")
For Each arrValue As String In arrIPAddress
Console.WriteLine("IPAddress: {0}", arrValue)
Next
End If
Console.WriteLine("IPEnabled: {0}", queryObj("IPEnabled"))
Console.WriteLine("MACAddress: {0}", queryObj("MACAddress"))
Next
Catch err As ManagementException
MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
End Try
End Function
End Class
End Namespace

Cannot load temporary file in VBCodeProvider

Here's my script code:
Imports System.Diagnostics
Public Class Script
Implements IScript
Public Sub DoWork(w As WebBrowser, f As Form1) Implements IScript.DoWork
w.Navigate("http://www.google.com")
wait("5000")
w.Document.All("input").InvokeMember("click")
w.Document.All("input").SetAttribute("value", "Torrenter is the best!")
wait("2000")
w.Document.All("421").InvokeMember("click")
wait("1000")
End Sub
Public Sub wait(ByVal interval As Integer)
Dim sw As New Stopwatch
sw.Start()
Do While sw.ElapsedMilliseconds < interval
' Allows UI to remain responsive
Application.DoEvents()
Loop
sw.Stop()
End Sub
End Class
In-code:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If int1.Text = "1" Then
int1.Text = "0"
Dim script As IScript = GenerateScript(File.ReadAllText(ListBox2.Items.Item(int2).ToString()))
script.DoWork(WebBrowser1, Me) 'Object reference not set to an instance of an object.
int2 = int2 + 1
int1.Text = "1"
End If
End Sub
Why? :(
It's supposed to start the next script after the first was done. I tried 4 methods but I can't understand why.
The problem is that your script code is failing to compile, but then you are trying to instantiate an object from the compiled assembly anyway. Since it failed to compile, the assembly doesn't actually exist, hence the error. If you modify the Return line in the GenerateScript method, so that it shows the compile errors, the actual problem will be more clear:
Dim results As CompilerResults = provider.CompileAssemblyFromSource(parameters, codes)
If results.Errors.HasErrors Then
Dim builder As New StringBuilder()
builder.AppendLine("Script failed to compile due to the following errors:")
For Each i As CompilerError In results.Errors
builder.AppendFormat("Line {0}: {1}", i.Line, i.ErrorText)
builder.AppendLine()
Next
Throw New Exception(builder.ToString())
Else
Return CType(results.CompiledAssembly.CreateInstance("Script"), IScript)
End If
I suspect that one of the reasons it's failing to compile is because the script uses IScript which is undefined. The reason it would complain that it's undefined is for two reasons. First, you declared the IScript interface as nested inside the Form1 class. You should move that outside of the form class so that it's not nested inside of any other type. Second, you are not specifying the full namespace nor importing the namespace in your script. You can automatically add the Imports line to the beginning of the script code before compiling it, like this:
Dim interfaceNamespace As String = GetType(IScript).Namespace
Dim codes As String = "Imports " & interfaceNamespace & Environment.NewLine & code
As I mentioned in the comments above, you really ought to be passing a string array into the CompileAssemblyFromSource method, not a string. I'm not sure how that even compiles, unless that's something having Option Strict Off somehow allows? In any case, it expects an array, so you should really be giving it one, like this:
Dim interfaceNamespace As String = GetType(IScript).Namespace
Dim codeArray() As String = New String() {"Imports " & interfaceNamespace & Environment.NewLine & code}
Dim results As CompilerResults = provider.CompileAssemblyFromSource(parameters, codeArray)
Another obvious reason why the script would fail to compile is because you have it using methods and properties of your Form1 class, as if it were a member of that class. Remember, the Script class defined by the script file source code is a completely separate class in a separate assembly. It will have no reference to the form unless you give it a reference, for instance, you could define the interface like this:
Public Interface IScript
Sub DoWork(f As Form1)
End Interface
Then, in your script, you could do this:
Public Class Script
Implements IScript
Public Sub DoWork(f As Form1) Implements IScript.DoWork
f.WebBrowser1.Navigate("http://www.google.com")
f.wait("5000")
f.wait("4000")
f.WebBrowser1.Document.All("input").InvokeMember("click")
f.WebBrowser1.Document.All("input").SetAttribute("value", "User")
f.wait("2000")
f.WebBrowser1.Document.All("421").InvokeMember("click")
End Sub
End Class
UPDATE
Ok, since you can't get it working, and I don't want this whole conversation to be a total loss, I put together a working project and tested it. Here's what you need to do to get it to work.
Contents of IScript.vb
Public Interface IScript
Sub DoWork(w As WebBrowser)
End Interface
Contents of Form1.vb
Imports Microsoft.VisualBasic
Imports System.CodeDom.Compiler
Imports System.Reflection
Imports System.IO
Imports System.Text
Public Class Form1
Dim int1 As Integer = 0
Dim int2 As Integer = 0
Dim p As Point
Public Function GenerateScript(ByVal code As String) As IScript
Using provider As New VBCodeProvider()
Dim parameters As New CompilerParameters()
parameters.GenerateInMemory = True
parameters.ReferencedAssemblies.Add(GetType(WebBrowser).Assembly.Location)
parameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location)
Dim interfaceNamespace As String = GetType(IScript).Namespace
code = "Imports System.Windows.Forms" & Environment.NewLine & "Imports " & interfaceNamespace & Environment.NewLine & code
Dim results As CompilerResults = provider.CompileAssemblyFromSource(parameters, code)
If results.Errors.HasErrors Then
Dim builder As New StringBuilder()
builder.AppendLine("Script failed to compile due to the following errors:")
For Each i As CompilerError In results.Errors
builder.AppendFormat("Line {0}: {1}", i.Line, i.ErrorText)
builder.AppendLine()
Next
Throw New Exception(builder.ToString())
Else
Return CType(results.CompiledAssembly.CreateInstance("Script"), IScript)
End If
End Using
End Function
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each File As FileInfo In New System.IO.DirectoryInfo(Application.StartupPath & "/scripts").GetFiles
If CheckedListBox1.GetItemCheckState(int2) = CheckState.Checked Then
ListBox1.Items.Add(File.FullName)
End If
int2 = int2 + 1
Next
int2 = 0
Dim script As IScript = GenerateScript(File.ReadAllText(ListBox1.Items.Item(int2).ToString()))
script.DoWork(WebBrowser1)
End Sub
End Class
Contents of script file
Imports System.Diagnostics
Public Class Script
Implements IScript
Public Sub DoWork(w As WebBrowser) Implements IScript.DoWork
w.Navigate("http://www.google.com")
wait("5000")
wait("4000")
w.Document.All("input").InvokeMember("click")
w.Document.All("input").SetAttribute("value", "User")
wait("2000")
w.Document.All("421").InvokeMember("click")
End Sub
Public Sub wait(ByVal interval As Integer)
Dim sw As New Stopwatch
sw.Start()
Do While sw.ElapsedMilliseconds < interval
' Allows UI to remain responsive
Application.DoEvents()
Loop
sw.Stop()
End Sub
End Class