VB.net: Object not set to an instance of object - vb.net

I am getting a Object not set to an instance of object error. I have put a list view where all messages should be shown. I am using lumisoft sample code which I ported to vb.net
Private Sub FillMessagesList()
Me.Cursor = Cursors.WaitCursor
Try
Dim m_pPop3 As POP3_Client = Nothing
For Each message As POP3_ClientMessage In m_pPop3.Messages
Dim mime As Mail_Message = Mail_Message.ParseFromByte(message.HeaderToByte())
Dim item As New ListViewItem()
If mime.From IsNot Nothing Then
item.Text = mime.From.ToString()
Else
item.Text = "<none>"
End If
If String.IsNullOrEmpty(mime.Subject) Then
item.SubItems.Add("<none>")
Else
item.SubItems.Add(mime.Subject)
End If
item.SubItems.Add(mime.[Date].ToString())
item.SubItems.Add(CDec(message.Size / CDec(1000)).ToString("f2") & " kb")
item.Tag = message
ListView1.Items.Add(item)
Next
Catch x As Exception
MessageBox.Show(Me, "Errorssssss: " + x.Message)
End Try
Me.Cursor = Cursors.[Default]
End Sub

The problem is here:
Dim m_pPop3 As POP3_Client = Nothing
For Each message As POP3_ClientMessage In m_pPop3.Messages
You set m_pPop3 to Nothing and then try to access one of its members.
You say that you ported the code - perhaps you need to look back at the original code and port it correctly:
private POP3_Client m_pPop3 = null;
/// <summary>
/// Default constructor.
/// </summary>
public wfrm_Main()
{
InitUI();
this.Visible = true;
wfrm_Connect frm = new wfrm_Connect(
new EventHandler<WriteLogEventArgs>(Pop3_WriteLog));
if(frm.ShowDialog(this) == DialogResult.OK){
m_pPop3 = frm.POP3;
// etc...
}
private void FillMessagesList()
{
this.Cursor = Cursors.WaitCursor;
try{
foreach(POP3_ClientMessage message in m_pPop3.Messages){
// etc...
}
}
Notice that m_pPop3.Messages is a private member here, not a local variable as you have implemented it.
To correct your code I would suggest changing it to be more similar to the original. Change the local variable to a private member and set it in the constructor, just as the original C# code does.

The culprit is possibly from the code in the 2 lines:
Dim m_pPop3 As POP3_Client = Nothing
For Each message As POP3_ClientMessage In m_pPop3.Messages
You're trying to loop through the messages in "m_pPop3" but you've explicitly set it to nothing on the line directly above.

I'm guessing it's here since you're setting m_pPop3 to Nothing. If you'd stepped through the code it would show you that.
Dim m_pPop3 As POP3_Client = Nothing
For Each message As POP3_ClientMessage In m_pPop3.Messages

Related

How to return data from a WebApi using HttpClient

I have been trying without success to return data from a an internally developed WebApi. The API uses Post requests to return data the body of the request containing complex criteria. I have previously had success using a Post Request to write data via the API, but I seem to have hit a brick wall in my efforts to return data. Here is the method I have been using:
Public Async Function Request(ByVal client As HttpClient, ByVal content As String) As Task
Dim buffer = System.Text.Encoding.UTF8.GetBytes(content)
Dim byteContent = New ByteArrayContent(buffer)
byteContent.Headers.ContentType = New MediaTypeHeaderValue("application/json")
Dim response = Await client.PostAsync(client.BaseAddress, byteContent)
Dim result As String = response.Content.ReadAsStringAsync().Result
_result = result
End Function
For conveninence the results are stored in a class variable, which enables me to test the routine using MSTest. The function should return a JSON array however it doesn't even return an error, rather it just returns Nothing.
Here is the associated TestMethod:
<TestMethod()> Public Sub ShouldSuccessfullyInterrodateTheSpenHapi()
Dim da = New SPEN.ODSDataPackagerService
Dim crit As New HttpCriterion
Dim stopped As Boolean
Dim jsonString As String = Nothing
crit.StartTime = "2022-11-03T00:00:00"
crit.EndTime = "2022-11-03T00:30:00"
crit.Interval = "30m"
crit.TagAttribute = "InstrumentTag"
crit.TagFilter = "confidential"
crit.Delimiter = "~"
crit.ServerName = "SPRODA"
'Deserialize object to JSON
jsonString = da.GetCriteriaJson(crit)
Try
da.InitialiseSettings()
da.Request(da.Clients(0), jsonString)
Debug.Print(da.Result)
Assert.IsTrue(True)
Catch ex As Exception
Assert.IsTrue(False)
End Try
End Sub
What am I missing guys?
EDIT:
Ok some further experimentation with the following code, I am at least now getting an error:
Public Async Function GetVoltagesFromPI(ByVal client As HttpClient, ByVal content As String) As Task(Of PIItemList)
Dim piItems As PIItemList = New PIItemList
Dim buffer = System.Text.Encoding.UTF8.GetBytes(content)
Dim byteContent = New ByteArrayContent(buffer)
byteContent.Headers.ContentType = New MediaTypeHeaderValue("application/json")
Try
Dim response As New HttpResponseMessage
response = Await client.PostAsync(client.BaseAddress, byteContent)
If response.IsSuccessStatusCode Then
_result = New PIItemList
_result = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result)
End If
Catch ex As Exception
Throw
Finally
End Try
End Function
The function errors at:
response = Await client.PostAsync(client.BaseAddress, byteContent)
with:
System.NullReferenceException: 'Object variable or With block
But really I am no further forward with regards a solution as far as I can make out the code should work, but there is obviously smething flawed in the code implementation.
Kind Regards
Paul.
Finally... Managed to get things working, here is the bare bones working code. Would appreciate any additional input though:
''' <summary>
''' Request pi data via the specified http endpoint (baseaddress)
''' </summary>
''' <param name="client"></param>
''' <param name="content"></param>
Public Function GetVoltagesFromPI(ByVal client As HttpClient, ByVal content As String) As Task(Of PIItemList)
Dim requestMsg As New HttpRequestMessage(HttpMethod.Post, client.BaseAddress)
Dim response As HttpResponseMessage
Dim interim As Object
Try
requestMsg.Content = New StringContent(content, Text.UTF8Encoding.Default, "application/json")
response = client.SendAsync(requestMsg).Result
If (response.StatusCode = System.Net.HttpStatusCode.OK) Then
_resultSet = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result)
End If
Catch ex As Exception
Throw
Finally
End Try
End Function

Pass Dynamic connection string to another Windows Form (VB.NET)

I am creating a windows application which required Dynamic Connection String in the app starting (user need to provide db credentials through a form), After entering the connection credentials user redirected to new win form
Everything is working fine but how can I pass my dynamic connection to another form.
I tried to save it to App variable but I couldn't (I think its read only)
Also I tried save it to registry but can't retrieve values.
Is there any other option available ? like writing & retrieving ConString to a text file or XML
Thanks
This how you can get and set registry values :
Public Function GetRegistryValue(ByVal KeyName As String, Optional ByVal DefaultValue As Object = Nothing) As Object
Dim res As Object = Nothing
Try
Dim k = My.Computer.Registry.CurrentUser.OpenSubKey("Software\YourAppName", True)
If k IsNot Nothing Then
res = k.GetValue(KeyName, DefaultValue)
Else
k = My.Computer.Registry.CurrentUser.CreateSubKey("Software\YourAppName")
End If
If k IsNot Nothing Then k.Close()
Catch ' ex As Exception
'PromptMsg(ex)
End Try
Return res
End Function
Public Sub SetRegistryValue(ByVal KeyName As String, ByVal _Value As Object)
Try
Dim k = My.Computer.Registry.CurrentUser.OpenSubKey("Software\YourAppName", True)
If k IsNot Nothing Then
k.SetValue(KeyName, _Value)
Else
k = My.Computer.Registry.CurrentUser.CreateSubKey("Software\YourAppName")
k.SetValue(KeyName, _Value)
End If
If k IsNot Nothing Then k.Close()
Catch ' ex As Exception
'PromptMsg(ex)
End Try
End Sub
It's working a 100%, If you please mark this answer as Right

Referencing an Unbound DataGridView Without Specifically Naming It?

I am using 3 unbound DataGridView controls to display certain information. To load the information into those DGVs, I am pulling the information from an encrypted file, decrypting it, parsing the information, then trying to fill the DGVs with that information. The loading from the file is called by the menu item click. Here is what I have so far:
Private Sub miCLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles miCLoad.Click
Dim FilePath As String = "C:\FList\CList.clt"
Dim LoadFile As New SaveandLoad.SaveAndLoad
Dim FileRead As New Simple3Des("MyPassword")
Dim FileString As String = FileRead.ReadFile(FilePath)
With LoadFile
.WhichList = dgCourses
.FilePath = FilePath
.DecryptedString = FileRead.DecryptData(FileString)
.dgList = dgCourses
End With
Call LoadFile.LoadFile()
End Sub
Public Class SaveandLoad
Public Property WhichList As New DataGridView
Public Property FilePath As String
Public Property DecryptedString As String
Public Property EncryptedString As String
Public Property dgList As Control
Public Sub LoadFile()
Dim dgRow As DataGridViewRow
Dim dgCell As DataGridViewTextBoxCell
Dim Lines() As String = DecryptedString.Split(vbLf)
Dim LinesList As List(Of String) = Lines.ToList
LinesList.RemoveAt(Lines.Length - 1)
For Each Line As String In LinesList
Dim Fields() As String = Line.Split(",")
dgRow = New DataGridViewRow
For x = 0 To (WhichList.Columns.Count - 1) Step 1
dgCell = New DataGridViewTextBoxCell
dgCell.Value = Fields(x).ToString
dgRow.Cells.Add(dgCell)
Next
WhichList.Rows.Add(dgRow)
Next
Select Case WhichList.Name
Case "dgCourses"
frmFacultyList.dgCourses = WhichList
frmFacultyList.dgCourses.Refresh()
WhichList.Dispose()
Case "dgFList"
frmFacultyList.dgFList = WhichList
frmFacultyList.dgFList.Refresh()
WhichList.Dispose()
Case "dgSList"
frmFacultyList.dgSList = WhichList
frmFacultyList.dgSList.Refresh()
WhichList.Dispose()
End Select
MsgBox("List Successfully Loaded", vbOKOnly, "Load")
End Sub
I want to be able to reference (or fill) a DGV without using 'select case' or 'if-then' statements. This will be too inefficient once I start adding the many other DGVs, that will be added in the future. Therefore, the title is the main question. I am using VS Express 2010.
I don't know VB too much, however, I'll post my solution in C# (may be helpfull in some way....)
DataGridView myDGV;
foreach (var item in this.Controls)
{
if (item.GetType() == typeof(DataGridView))
{
if (((DataGridView)item).Name == WhichList.Name)
{
//Cannot assing to 'item' here, because it is a 'foreach iteration variable'
//However you can save the variable for later use.
myDGV = (DataGridView)item;
}
}
}
myDGV = WhichList;
// different approach
DataGridView myDGV = (DataGridView)this.Controls.Find(WhichList.Name, false).First();
myDGV = WhichList;
Here is what worked for me in VB.NET:
Dim FormControls As New frmFacultyList.ControlCollection(frmFacultyList)
For Each DGV As DataGridView In FormControls
If WhichList.Name = DGV.Name Then
DGV = WhichList
DGV.Refresh()
End If
Next
Make an instance of the control collection then search specifically for DGVs using For Each. Simple and efficient.

Visual basic "Unhandled exception"

Hello I'm getting this error, while trying to save serial number to XML File.
If the file doesn't exist, it saves the file fine, but if i change Registered tag to False in Xml file, and try again, it says "The Process Cannot acces the file ... because it is being used by another process".
In my main form i read the information from XML, and in my regform (which i open if registered tag in xml is false) i write to the file. is it because of that?! I don't think so.
Here is my Registration class:
Imports System.IO
Imports System.Xml
Public Class RegistrationClass
Public Property SerialNumber As String
Public Property Registered As Boolean = False
Public Sub Write_Reg(ByVal FileString As String, ByVal RegisterName As String, ByVal RegisterCompany As String, ByVal RegisterSerialNumber As String)
Dim Registered As Boolean = False
Dim Comment As String = "StroySoft 2012 Register Database"
Dim SerialNumber As String = "dev-xxx-123"
Dim ClientOS As String = Trim(My.Computer.Info.OSFullName)
If RegisterSerialNumber = SerialNumber Then
Dim settings As New XmlWriterSettings()
settings.Indent = True
' Initialize the XmlWriter.
Dim XmlWrt As XmlWriter = XmlWriter.Create(FileString, settings)
With XmlWrt
' Write the Xml declaration.
.WriteStartDocument()
' Write a comment.
.WriteComment(Comment)
' Write the root element.
.WriteStartElement("Data")
' Start our first person.
.WriteStartElement("Register")
' The person nodes.
.WriteStartElement("Name")
.WriteString(RegisterName.ToString())
.WriteEndElement()
.WriteStartElement("Company")
.WriteString(RegisterCompany.ToString())
.WriteEndElement()
.WriteStartElement("SerialNumber")
.WriteString(RegisterSerialNumber.ToString())
.WriteEndElement()
Registered = True
.WriteStartElement("Registered")
.WriteString(Registered)
.WriteEndElement()
.WriteStartElement("ClientOS")
.WriteString(ClientOS)
.WriteEndElement()
' The end of this person.
.WriteEndElement()
' Close the XmlTextWriter.
.WriteEndDocument()
.Close()
End With
MsgBox("Успешна регистрация! Благодарим Ви!")
MainForm.РегистрацияToolStripMenuItem.Visible = False
Else
MsgBox("Невалиден сериен номер!")
End If
End Sub
Public Sub Check_Reg(ByVal FileString As String)
If (System.IO.File.Exists(FileString)) Then
Dim document As XmlReader = New XmlTextReader(RegForm.RegFile)
While (document.Read())
Dim type = document.NodeType
If (type = XmlNodeType.Element) Then
If (document.Name = "Registered") Then
If document.ReadInnerXml.ToString() = "True" Then
Registered = True
Else
Registered = False
End If
End If
If (document.Name = "SerialNumber") Then
SerialNumber = document.ReadInnerXml.ToString()
End If
End If
End While
Else
MessageBox.Show("The filename you selected was not found.")
End If
End Sub
End Class
is it because of that?! I don't think so.
It's exactly because of that.
You should always make sure to properly dispose IDisposable resources such as Streams and Writers/Readers by wrapping them in a Using block. In your case I don't see you closing your reader. But if you wrap it in a Using block you shouldn't worry about it. Even if an exception is thrown the resource will be properly released.
Example:
Using XmlWrt As XmlWriter = XmlWriter.Create(FileString, settings)
...
End Using
You should do the same with your XmlReader:
Using document As XmlReader = XmlReader.Create(RegForm.RegFile)
...
End Using

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.