The warning is : An error occurred creating the form. See Exception.InnerException for details. The error is: Cannot load Counter Name data because an invalid index '' was read from the registry.
My Code is :
Imports System
Imports System.Management
Imports System.Diagnostics
Public Class Form1
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
Dim cpuLoad As Integer = CDec(PerformanceCounter1.NextValue.ToString())
cpuLoad = 100 - cpuLoad
Label1.Text = cpuLoad.ToString() & "%"
On Error Resume Next
ProgressBar1.Value = cpuLoad.ToString
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Timer1.Start()
Label2.Text = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\SYSTEM\CentralProcessor\0", "ProcessorNameString", Nothing)
label3.text = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\SYSTEM\CentralProcessor\0", "~MHz", Nothing) & " Mhz"
End Sub
End Class
Have a look at this question. I found this, and many more examples suggesting that your problem results from one or more corrupted registry entries. Pablissimo's answer provides an explanation of the problem, and the relevant steps to rebuild these entries.
Click Start, type cmd right click cmd.exe, and select Run as
administrator. At the prompt, type lodctr /r and press ENTER.
First of all your cpu counter gives a strange value on my pc."2 times higher than it is"
what i use is also a performance counter but the value is almost the same as in windows task manager.
Dim CpuCounter As New PerformanceCounter()
Dim CpuResult As New Integer
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
With CpuCounter
.CategoryName = "Processor"
.CounterName = "% Processor Time"
.InstanceName = "_Total"
End With
CpuResult = CpuCounter.NextValue
CpuLabel.Text = CpuResult & "%"
CpuBar.Value = CpuResult
End Sub
the other thing is ...
Your code to get the ProcessorNameString and the Mhz is working on my computer..
But you can also use it like this.
you need to Imports Microsoft.Win32 "but of course you already have that"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim cpuName As String
Dim cpuFreq As String
Dim regKey As RegistryKey
regKey = Registry.LocalMachine
regKey = regKey.OpenSubKey("HARDWARE\DESCRIPTION\System\CentralProcessor\0", False)
cpuName = regKey.GetValue("ProcessorNameString")
cpuFreq = regKey.GetValue("~MHz")
Label2.Text = cpuName
Label3.Text = cpuFreq & " MHz"
End Sub
And if this does not work you can also use WMI "ManagementObjectSearcher" for it.
you need to Imports System.Management
and Add reference System.Management to your project.
then you can use this code in the form load event to get the same info
Dim cpuName As String
Dim cpuFreq As String
Try
Dim searcher As New ManagementObjectSearcher( _
"root\CIMV2", _
"SELECT * FROM Win32_Processor")
For Each queryObj As ManagementObject In searcher.Get()
cpuName = queryObj("Name")
cpuFreq = queryObj("CurrentClockSpeed")
Label2.Text = cpuName
Label3.Text = cpuFreq & "MHz"
Next
Catch err As ManagementException
MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
End Try
Related
I am working oin a project in vb.net although I am not an expert in it, I just used it because U think it is the best for this kind of problem.
I have a project with two buttons and a label; first button is for sync windows date from a server and the other is to change the windows date to (2014, 11, 16). I am doing this because some programs I have doesn't run unless the date is this one and as you know browser must be the real time to run this is the idea of this project.
The second button is working perfectly, but the sync date button doesn't work and throws this error in my label
No connection because the target machine refused to connect
Here is my function and my server ip
Public Function GetNISTTime(ByVal host As String) As String
Dim timeStr As String = ""
Try
Dim reader As New StreamReader(New TcpClient(host, 13).GetStream)
LastSysTime = DateTime.UtcNow()
timeStr = reader.ReadToEnd()
reader.Close()
Catch ex As SocketException
GetNISTTime = ex.Message
Exit Function
Catch ex As Exception
GetNISTTime = ex.Message
Exit Function
End Try
'Dim jd As Integer = Integer.Parse(timeStr.Substring(1, 5))
'Dim yr As Integer = Integer.Parse(timeStr.Substring(7, 2))
'Dim mo As Integer = Integer.Parse(timeStr.Substring(10, 2))
'Dim dy As Integer = Integer.Parse(timeStr.Substring(13, 2))
'Dim hr As Integer = Integer.Parse(timeStr.Substring(16, 2))
'Dim mm As Integer = Integer.Parse(timeStr.Substring(19, 2))
'Dim sc As Integer = Integer.Parse(timeStr.Substring(22, 2))
'Dim Temp As Integer = CInt(AscW(timeStr(7)))
Return timeStr ' New DateTime(yr + 2000, mo, dy, hr, mm, sc)
End Function
and the button
Private Sub real_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles real.Click
GetNISTTime("mail.harf.com.sa")
Label1.Text = GetNISTTime("mail.harf.com.sa").ToString
End Sub
I think the problem is because of the server but I didn't find any dns server that does sync successfully.
This is my program download link if you want to see the problem in with your eyes (you should run it as adminstrator)
http://www.mediafire.com/file/wfw5jpag8w2hofb/Release.rar/file
Also it must be dns in Saudi Arabia time zone
Your function call is not correct.
Private Sub real_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles real.Click
GetNISTTime("mail.harf.com.sa")
Label1.Text = GetNISTTime("mail.harf.com.sa").ToString
End Sub
should be:
Private Sub real_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles real.Click
Label1.Text = GetNISTTime("mail.harf.com.sa")
End Sub
GetNISTTime is a function that returns a string, so your original first line (GetNISTTime("mail.harf.com.sa")) does the work but nothing is done with the return value. Your original second line takes a return value that is a string and then tries to convert it to a string.
In addition, your function may not return anything if an error occurs. You have used a VBA style assignment in the catch block. Instead, try:
Public Function GetNISTTime(ByVal host As String) As String
Dim timeStr As String = ""
Try
Dim reader As New StreamReader(New TcpClient(host, 13).GetStream)
LastSysTime = DateTime.UtcNow()
timeStr = reader.ReadToEnd()
reader.Close()
Catch ex As SocketException
return ex.Message
Catch ex As Exception
Return ex.Message
End Try
'any other stuff
Return timeStr
End Function
so i did like what Visual Vincent say and this is my code after editing it
and it worked perfectly with me just need administrator permissions
code
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Runtime.InteropServices
Public Class Daytime
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim d As DateTime
d = "12:52:00"
Try
Microsoft.VisualBasic.TimeOfDay = d 'Your time...
Microsoft.VisualBasic.DateString = New Date(2014, 11, 16) 'The date...
Catch ex As Exception
'You might have to run as Administrator...?
End Try
End Sub
Private Sub real_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles real.Click
Process.Start("CMD", "/C net start w32time & w32tm /resync /force & pause")
End Sub
End Class
Introduction (Warning: Bad English)
Hello everybody. I need some help with my program.
So, basically my program is made for downloading one file and extracting it to known path, for example C:\Users\ProfileName\Documents\Windward. This path is suitable for most part of people. But for some people it's wrong path (Because file need's to be installed in Documents\Windward folder). So i decided to make changeable path. I thought I making everything right, but something gone wrong. And i thing something is frong with this: Dim path As String = TextBox1.Text & "\Localization.zip", but i don't know how to fix it.
Please help me!
Error:
An unhandled exception of type System.InvalidOperationException occurred in AutoDownloadV2.exe
Additional information: Error in form creating. Exception.InnerException. Error: Object reference not set to an instance of an object.
After Debug I recieve this:
in AutoDownloadV2.My.MyProject.MyForms.Create__Instance__[T](T Instance) in :string 190
in AutoDownloadV2.My.MyApplication.OnCreateMainForm() в B:\Projects\Progs\AutoDownloadV2\AutoDownloadV2\AutoDownloadV2\My Project\Application.Designer.vb:string 35
in Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
in Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
in Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
in AutoDownloadV2.My.MyApplication.Main(String[] Args) in :string 81 The program '[5452] AutoDownloadV2.exe' has exited with code 0 (0x0).
Here is my code (I have removed the useless part of code.)
Public Class Form1
Public WithEvents download As WebClient
Dim path As String = TextBox1.Text & "\Localization.zip"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "C:\Users\" & SystemInformation.UserName & "\Documents\Windward"
ProgressBar1.Value = 0
CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
Try
My.Computer.FileSystem.DeleteFile(path)
Catch ex As Exception
End Try
download = New WebClient
download.DownloadFileAsync(New Uri("http://http://exsite.example"), path)
Catch ex As Exception
MsgBox("Error! " & ex.Message)
End Try
End Sub
Private Sub download_DownloadProgressChanged(ByVal sender As System.Object, ByVal e As System.Net.DownloadProgressChangedEventArgs) Handles download.DownloadProgressChanged
Try
Label3.Text = "Downloaded : " & e.BytesReceived / 1024 & " kb / " & e.TotalBytesToReceive / 1024 & " kb "
Label4.Text = ProgressBar1.Value & "%"
ProgressBar1.Value = e.ProgressPercentage
Catch ex As Exception
MsgBox("Error! " & ex.Message)
End Try
If e.BytesReceived = e.TotalBytesToReceive Then
Unzip()
End If
End Sub
Public Sub Unzip()
Dim startPath As String = path
Dim zipPath As String = path
Dim extractPath As String = ("C:\Users\" + SystemInformation.UserName + "\Documents\Windward\")
If My.Computer.FileSystem.FileExists(extractPath + "mods\translateMod\Localization.txt") Then
My.Computer.FileSystem.DeleteFile(extractPath + "mods\translateMod\Localization.txt")
Try
My.Computer.FileSystem.DeleteFile(extractPath + "mods\translateMod\Version.txt")
Catch e As Exception
End Try
ZipFile.ExtractToDirectory(zipPath, extractPath)
My.Computer.FileSystem.DeleteFile(path)
Else
ZipFile.ExtractToDirectory(zipPath, extractPath)
My.Computer.FileSystem.DeleteFile(path)
End If
End Sub
End Class
Move the initialization of path inside the Form1_Load after setting the initial value in TextBox1
Dim path As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "C:\Users\" & SystemInformation.UserName & "\Documents\Windward"
path = TextBox1.Text & "\Localization.zip"
ProgressBar1.Value = 0
CheckForIllegalCrossThreadCalls = False
End Sub
The problem is caused by the reference to TextBox1 in the global area of your form class. At that point the TextBox1 is still Nothing (not initialized) thus you get the NRE message (Null Reference Exception)
The system is meant to work so that whenever the gta_sa process stops running, it copies the file selected when browsing cmdFile to cmdStorage's location. Problem I have right now is that it doesn't store the new file in .txt, but rather just as .file. It's openable, but not as default.
Also, I wasn't sure how to do the detection on when gtasa process was recently closed so I had to use if the process is active. I'd really appreciate it for some help, thanks.**
EDIT: Maybe it needs to use a timer? Not sure, thanks again.
Imports System.Diagnostics
Imports System Imports System.ComponentModel
Public Class frmChatLog
Dim ofdDone
Dim fldDone
Dim Completed
Private Sub cmdStorage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdStorage.Click
Using fld As New FolderBrowserDialog()
If fld.ShowDialog() = Windows.Forms.DialogResult.OK Then
MessageBox.Show("Selected " & fld.SelectedPath)
fldDone = fld.SelectedPath
cmdStorage.Enabled = False
End If
End Using
End Sub
Private Sub cmdFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdFile.Click
Using ofd As New OpenFileDialog()
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
MessageBox.Show("Selected " & ofd.FileName)
ofdDone = ofd.FileName
cmdFile.Enabled = False
End If
End Using
End Sub
Private Sub cmdStart_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdStart.Click
If cmdFile.Enabled = False And cmdStorage.Enabled = False Then
Do Until Process.GetProcessesByName("gta_sa").Count > 0
If Process.GetProcessesByName("gta_sa").Count > 0 Then
MsgBox("Game is on")
Else
System.IO.File.Move(ofdDone, fldDone & "\" & Today.Now.ToString("ddMMyyHHmmss"))
Completed = fldDone & "\" & Today.Now.ToString("ddMMyyHHmmss")
Completed.ChangeExtension(".txt")
Exit Do
End If
Loop
End If
End Sub
End Class
Problem I have right now is that it doesn't store the new file in .txt, but rather just as .file.
To fix that, change this line near the bottom of your code:
System.IO.File.Move(ofdDone, fldDone & "\" & Today.Now.ToString("ddMMyyHHmmss"))
to this:
File.Move(ofdDone, Path.Combine(fldDone, Now.ToString("ddMMyyHHmmss") & ".txt"))
Then get rid of any line that mentions your Completed variable. You may also need to add an Imports System.IO to the top of the file.
Imports System.Net.NetworkInformation
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim pingtarget As String = "88.250.204.138"
Dim pingre As PingReply = Ping.Send(pingtarget)
If My.Computer.Network.Ping("pingtarget", 9002) Then
address.ForeColor = Color.Green
Do While My.Computer.Network.Ping("pingtarget", 9002)
Me.ListBox1.Items.Add("Response from " & pingtarget & " in " & pingre.RoundtripTime.ToString() & " ms")
My.Computer.Network.Ping("pingtarget", 9002)
Loop
Else
Timer2.Enabled = True
address.ForeColor = Color.Red
MsgBox("Connection Failed")
End If
End Sub
End Class
Hey guys, I just began trying to develop a program that will keep pinging the server and if connection is lost, the client will reboot itself. I have some questions :
1- How to count the reboots? Otherwise it will keep rebooting as long as there is no connection. Reboots will retry connecting internet again but it fails too much, there must be a way to stop it. For example after 3 reboots , the client will run even without connection.
2- In these codes, when there is no connection, I get aa error message saying "An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.VisualBasic.dll".
One obvious problem:
change this part of your code:
My.Computer.Network.Ping("pingtarget", 9002)
to this:
My.Computer.Network.Ping(pingtarget, 9002)
you are passing pingtarget as a string not a variable.
I'm trying to read a text file with multiple lines and then display it in a textbox. The problem is that my program only reads one line. Can someone point out the mistake to me?
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private BagelStreamReader As StreamReader
Private PhoneStreamWriter As StreamWriter
Dim ResponseDialogResult As DialogResult
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
'Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
'Is file already open
If PhoneStreamWriter IsNot Nothing Then
PhoneStreamWriter.Close()
End If
With OpenFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
'If ResponseDialogResult <> DialogResult.Cancel Then
' PhoneStreamWriter = New StreamWriter(OpenFileDialog1.FileName)
'End If
Try
BagelStreamReader = New StreamReader(OpenFileDialog1.FileName)
DisplayRecord()
Catch ex As Exception
MessageBox.Show("File not found or is invalid.", "Data Error")
End Try
End Sub
Private Sub DisplayRecord()
Do Until BagelStreamReader.Peek = -1
TextBox1.Text = BagelStreamReader.ReadLine()
Loop
'MessageBox.Show("No more records to display.", "End of File")
'End If
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
With SaveFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
PhoneStreamWriter.WriteLine(TextBox1.Text)
With TextBox1
.Clear()
.Focus()
End With
TextBox1.Clear()
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
PhoneStreamWriter.Close()
Me.Close()
End Sub
End Class
Here is a sample textfile:
Banana nut
Blueberry
Cinnamon
Egg
Plain
Poppy Seed
Pumpkin
Rye
Salt
Sesame seed
You're probably only getting the last line in the file, right? Your code sets TextBox1.Text equal to BagelSteramReader.ReadLine() every time, overwriting the previous value of TextBox1.Text. Try TextBox1.Text += BagelStreamReader.ReadLine() + '\n'
Edit: Though I must steal agree with Hans Passant's commented idea on this; If you want an more efficient algorithm, File.ReadAllLines() even saves you time and money...though I didn't know of it myself. Darn .NET, having so many features...
I wrote a program to both write to and read from a text file. To write the lines of a list box to a text file I used the following code:
Private Sub txtWriteToTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtWriteToTextfile.Click
Dim FileWriter As StreamWriter
FileWriter = New StreamWriter(FileName, False)
' 3. Write some sample data to the file.
For i = 1 To lstNamesList.Items.Count
FileWriter.Write(lstNamesList.Items(i - 1).ToString)
FileWriter.Write(Chr(32))
Next i
FileWriter.Close()
End Sub
And to read and write the contents of the text file and write to a multi-line text box (you just need to set the multiple lines property of a text box to true) I used the following code. I also had to do some extra coding to break the individual words from the long string I received from the text file.
Private Sub cmdReadFromTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReadFromTextfile.Click
Dim sStringFromFile As String = ""
Dim sTextString As String = ""
Dim iWordStartingPossition As Integer = 0
Dim iWordEndingPossition As Integer = 0
Dim iClearedTestLength As Integer = 0
Dim FileReader As StreamReader
FileReader = New StreamReader(FileName)
sStringFromFile = FileReader.ReadToEnd()
sTextString = sStringFromFile
txtTextFromFile.Text = ""
Do Until iClearedTestLength = Len(sTextString)
iWordEndingPossition = CInt(InStr((Microsoft.VisualBasic.Right(sTextString, Len(sTextString) - iWordStartingPossition)), " "))
txtTextFromFile.Text = txtTextFromFile.Text & (Microsoft.VisualBasic.Mid(sTextString, iWordStartingPossition + 1, iWordEndingPossition)) & vbCrLf
iWordStartingPossition = iWordStartingPossition + iWordEndingPossition
iClearedTestLength = iClearedTestLength + iWordEndingPossition
Loop
FileReader.Close()
End Sub