Getting a NullReferenceException when adding something to a list - vb.net

I get a null reference exception when I try to use this webservice I'm working on. I have two fields in the object ipadarticle called fullname and tags, which are declared to be lists, so that ipadarticle can return multiple tags and authors. The null reference exception points to
ipadarticle2.FullName.Add(a_var.firstname + " " + a_var.lastname)
ipadarticle2.Tag.Add(a_var.tagtext)
I'm pretty new to vb programming, so I'm not really to sure what is causing this. To clarify, what is going on is that this stored procedure is fetching entries from a db, which has a list of articles with -among other things- tags and authors associated with it. Since articles have multiple tags and authors there are multiple entries for each article. When I return the info in the web service I am trying to make it so that only one ipadarticle object is returned for reach article, and then that contains a list of the multiple tags and authors associated with each article. I'm having a headache trying to figure this out.
Dim lq As New lqDFDataContext
Dim var = lq.mobile_IpadGetSavedArticlesAR(simpuser.UserID, tempParamKW(0), tempParamKW(1), tempParamKW(2), tempParamKW(3), tempParamKW(4), pageNum, pageLen)
Dim ipadarticle2 As New ipadArticle()
For Each a_var In var
If a_var.articleID <> temp Then
If flag = 0 Then
result.add(ipadarticle2)
Dim ipadarticle1 As New ipadArticle()
ipadarticle2 = ipadarticle1
End If
ipadarticle2.ArticleID = a_var.articleID
ipadarticle2.PublishedOn = a_var.publicationdate
ipadarticle2.Title = a_var.title
ipadarticle2.MedAbbr = a_var.medabbr.Replace(" ", "-").ToLower()
ipadarticle2.FullName.Add(a_var.firstname + " " + a_var.lastname)
ipadarticle2.Tag.Add(a_var.tagtext)
flag = 1
Else
ipadarticle2.Tag.Add(a_var.tagtext)
ipadarticle2.FullName.Add(a_var.firstname + " " + a_var.lastname)
flag = 0
End If
temp = a_var.articleID
Next
End If
Return result
ipadArticle class:
Imports Microsoft.VisualBasic
Public Class ipadArticle
Inherits SimpleObject
Public Sub New()
End Sub
Private _ArticleID As Integer
Public Property ArticleID() As Integer
Get
Return _ArticleID
End Get
Set(ByVal value As Integer)
_ArticleID = value
End Set
End Property
Private _Title As String
Public Property Title() As String
Get
Return _Title
End Get
Set(ByVal value As String)
_Title = value
End Set
End Property
Private _PublishedOn As String
Public Property PublishedOn() As String
Get
Return _PublishedOn
End Get
Set(ByVal value As String)
_PublishedOn = value
End Set
End Property
Private _MedAbbr As String
Public Property MedAbbr() As String
Get
Return _MedAbbr
End Get
Set(ByVal value As String)
_MedAbbr = value
End Set
End Property
Private _Tag As List(Of String)
Public Property Tag() As List(Of String)
Get
Return _Tag
End Get
Set(ByVal value As List(Of String))
_Tag = value
End Set
End Property
Private _FullName As List(Of String)
Public Property FullName() As List(Of String)
Get
Return _FullName
End Get
Set(ByVal value As List(Of String))
_FullName = value
End Set
End Property
End Class

The most likely cause is that the objects FullName and Tag have not been created (are Nothing) in ipadarticle2. These should most likely be created as new objects in the class constructor.
EDIT:
Based on the posted class, the above assumption was correct: FullName and Tag are defined as List(Of String), but the backing members are never created.
This can be fixed in a couple of ways:
1) Instantiate the backing member variables directly in their definition, i.e.:
Private _FullName As New List(Of String)
2) Instantiate the backing member variables in the constructor:
Public Sub New()
_FullName = New List(Of String)
_Tag = New List(Of String)
End Sub
3) Instantiate the backing member variable in the getter if it is nothing:
Public Property Tag() As List(Of String)
Get
If _Tag Is Nothing Then
_Tag = New List(Of String)
End If
Return _Tag
End Get
Basically, any variable types other than simple data types must be instantiated before they can be used (unless you test them for Nothingness).

Related

how to append one class to another of same in vb.net

PropertyPolicy is a class that defines a collection of several fields/entities. Sometimes two separate functions are needed to build out the collection. (LoadEstateAIN and LoadAIN). I need to combine the results of both classes but have tried concat but get a cast exception. What would work here?
Public Class PropertyPolicy
Private agentfield As Entity
Private aininsuredfield() As Entity
Private billinginfofield As BillingInfo
Private cancellationdatefield As Date
Private claimsfield() As Claims
Public Property Agent As Entity
Get
Return Me.agentfield
End Get
Set(ByVal value As Entity)
Me.agentfield = value
End Set
End Property
Public Property AINInsured() As Entity()
Get
Return Me.aininsuredfield
End Get
Set(ByVal value As Entity())
Me.aininsuredfield = value
End Set
End Property
Public Property BillingInfo As BillingInfo
Get
Return Me.billinginfofield
End Get
Set(ByVal value As BillingInfo)
Me.billinginfofield = value
End Set
End Property
Public Property CancellationDate As Date
Get
Return Me.cancellationdatefield
End Get
Set(ByVal value As Date)
Me.cancellationdatefield = value
End Set
End Property
Public Property Claims() As Claims()
Get
Return Me.claimsfield
End Get
Set(ByVal value As Claims())
Me.claimsfield = value
End Set
End Property
End Class
Dim propTemp1 As New PropertyPolicy
Dim propTemp2 As New PropertyPolicy
Dim propTempComb As New PropertyPolicy
propTemp1.AINInsured = LoadEstateAIN(policyid, asofDate, lob, NINclientid, estatecompany)
propTemp2.AINInsured = LoadAIN(policyid, asofDate, lob, NINclientid, estatecompany)
propTempComb.AINInsured = propTemp1.AINInsured.Concat(propTemp2.AINInsured)
The result of Concat is not an array; it is an IEnumerable(Of T). In your case it is an IEnumerable(Of Entity). You just need to add ToArray() to the end of the Concat if you want to assign it back to an array.
propTempComb.AINInsured = propTemp1.AINInsured.Concat(propTemp2.AINInsured).ToArray()
Breaking down this line of code:
[instance3].[property] = [instance1].[property].Concat([instance2].[property])
Assigns the result of the Concat to the property, but the property is an array so you need to change the result of Concat which is an IEnumerable(Of Entity) into an array which is trivial with ToArray.
I could go further and recommend that you don't use arrays as public members, rather IEnumerable. Also, auto-properties would be a better choice for some of these Public/Public properties.
Public Class PropertyPolicy
Private aininsuredfield As Entity()
Private claimsfield As Claims()
Public Property Agent As Entity
Public Property BillingInfo As BillingInfo
Public Property CancellationDate As Date
Public Property AINInsured() As IEnumerable(Of Entity)
Get
Return aininsuredfield
End Get
Set(value As IEnumerable(Of Entity))
aininsuredfield = value.ToArray()
End Set
End Property
Public Property Claims() As IEnumerable(Of Claims)
Get
Return claimsfield
End Get
Set(value As IEnumerable(Of Claims))
claimsfield = value.ToArray()
End Set
End Property
End Class
And btw, that would cause your original code to work without ToArray()
propTempComb.AINInsured = propTemp1.AINInsured.Concat(propTemp2.AINInsured)

Predefined class properties if need expand or shrink quantity of them on each app start

Public Class Products
Private zCriteria As String
Public Property Criteria As String
Get
Return zCriteria
End Get
Set(value As String)
zCriteria = value
End Set
End Property
Private zProductList As New List(Of Product)
Public Property ProductList As List(Of Product)
Get
Return zProductList
End Get
Set(value As List(Of Product))
zProductList = value
End Set
End Property
End Class
Public Class Product
Private zCriteriaList As List(Of Criterias)
Public Property CriteriaList As List(Of Criterias)
Get
Return zCriteriaList
End Get
Set(value As List(Of Criterias))
zCriteriaList = value
End Set
End Property
End Class
Public Class Criterias
Private zCrPropName As String
Public Property CrPropName As String
Get
Return zCrPropName
End Get
Set(value As String)
zCrPropName = value
End Set
End Property
Private zCritCode As String
Public Property CritCode As String
Get
Return zCritCode
End Get
Set(value As String)
zCritCode = value
End Set
End Property
Private zcrPropValue As String
Public Property crPropValue As String
Get
Return zcrPropValue
End Get
Set(value As String)
zcrPropValue = value
End Set
End Property
End Class
For Each oProducts As Products In oAssigment.ProductsList
For Each oproduct As Product In oProducts.ProductList
For Each cr As Criterias In oproduct.CriteriaList
cr.CrPropName = "Product Name" 'some object property name
cr.CritCode = "PN"
cr.crPropValue = "" ' Value of property "Product Name"
Next
Next
Next
It is all made to have different properties of some object depending on options set in text file. It is only a sample o usage.
conditions:
Criterias on applications start is same for all objects (=Product) i want to read.
Every time on start, application read options file where is defined few property names and codes (values i want get from objects). So every run can be initiated different quantity of properties to read. It means i can not have hard-coded names of properties.
Someone can advice me how to predefine "CrPropName" and "CritCode" on app start so many times how much property names defined in options and after that populate it so many times as how many objects exist from which i read these property values.
p.s. I am not very professional at coding and sorry for my language

How to convert a list of different data types into string in vb.net

I created a list using a class which has different data types. It is populated as follows:
[1/16/2015 10:30:14 PM] 241.167.2.72:5
[1/17/2015 11:30:06 PM] 100.133.2.55:6
[1/18/2015 12:30:33 PM] 206.140.3.10:7
Now I just want to display this in a textbox on a page. But get this:
ClientWebApp.DedicatedServerApi.Formatted_DDoS_SampleFlows
ClientWebApp.DedicatedServerApi.Formatted_DDoS_SampleFlows
ClientWebApp.DedicatedServerApi.Formatted_DDoS_SampleFlows
I'm using this line of code with the ToString()...but obviously it is not correct.
strSampleFlowLine = formattedDDoSSampleFlow.ToString() & vbCrLf & vbCrLf
Any Ideas?
The code (and classes) that attempts to populate the text box on the page:
Dim ddosDetailsInfoResult As New DedicatedServerApi.DDoSDetailsInfoResult
Dim formattedDDoSSampleFlow As New DedicatedServerApi.Formatted_DDoS_SampleFlows
' Create a list field - an array of the DDoS sample flows.
Dim formattedDDoSSampleFlowsList As New List(Of DedicatedServerApi.Formatted_DDoS_SampleFlows)
If ddosDetailsInfoResult.DDoS_Details.Formattted_DDoS_SampleFlows_List.Count > 0 Then
' Note: had to add .ToList() as it was giving a syntax error: cannot be converted to a 1-dimensional array.
' Does not make sense as the "Formattted_DDoS_SampleFlows_List" variable is defined exactly like the receiving field.
formattedDDoSSampleFlowsList = ddosDetailsInfoResult.DDoS_Details.Formattted_DDoS_SampleFlows_List.ToList()
For Each formattedDDoSSampleFlow In formattedDDoSSampleFlowsList
' Example of entry in the list: [1/16/2015 10:30:14 PM] 241.167.2.72:5
strSampleFlowLine = formattedDDoSSampleFlow.ToString() & vbCrLf & vbCrLf
' Build the sample flow list textbox.
txtGDHDApiSampleFlowList.Text = txtGDHDApiSampleFlowList.Text & strSampleFlowLine
Next
Else
'An empty list.
txtGDHDApiSampleFlowList.Text = ""
End If
'+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
' Holds formatted DDoS sample flows settings.
' [1/16/2015 10:30:14 PM] 241.167.2.72:5
'+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Public Class Formatted_DDoS_SampleFlows
Private _open_bracket_delimeter As String
Public Property Open_Bracket_Delimeter() As String
Get
Return _open_bracket_delimeter
End Get
Set(value As String)
_open_bracket_delimeter = value
End Set
End Property
Private _time_received As Date
Public Property Time_Received() As Date
Get
Return _time_received
End Get
Set(value As Date)
_time_received = value
End Set
End Property
Private _close_backet_and_space_delimeter As String
Public Property Close_Bracket_And_Space_Delimeter() As String
Get
Return _close_backet_and_space_delimeter
End Get
Set(value As String)
_close_backet_and_space_delimeter = value
End Set
End Property
Private _source_ip As String
Public Property Source_IP() As String
Get
Return _source_ip
End Get
Set(value As String)
_source_ip = value
End Set
End Property
Private _colon1_delimeter As String
Public Property Colon1_Delimeter() As String
Get
Return _colon1_delimeter
End Get
Set(value As String)
_colon1_delimeter = value
End Set
End Property
Private _source_port As String
Public Property Source_Port() As String
Get
Return _source_port
End Get
Set(value As String)
_source_port = value
End Set
End Property
End Class
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
' Holds DDoSDetailsInfoResult.
'+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Public Class DDoSDetailsInfoResult
Private _message As String
Public Property Message() As String
Get
Return _message
End Get
Set(value As String)
_message = value
End Set
End Property
Private _ddos_details As New DDoS_Details
Public Property DDoS_Details() As DDoS_Details
Get
Return _ddos_details
End Get
Set(ByVal value As DDoS_Details)
_ddos_details = value
End Set
End Property
End Class
'+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
' Holds DDoS details.
'+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Public Class DDoS_Details
Private _formatted_ddos_sampleflows_list As New List(Of Formatted_DDoS_SampleFlows)
Public Property Formattted_DDoS_SampleFlows_List() As List(Of Formatted_DDoS_SampleFlows)
Get
Return _formatted_ddos_sampleflows_list
End Get
Set(ByVal value As List(Of Formatted_DDoS_SampleFlows))
_formatted_ddos_sampleflows_list = value
End Set
End Property
End Class
Your Formatted_DDoS_SampleFlows class need to define what ToString does.
Something like:
Class Formatted_DDoS_SampleFlows
Public Overrides ToString() As String
Return _open_bracket_delimeter & _time_received.ToString() & _close_backet_and_space_delimeter & _source_ip
End Sub
End Class
use CDate to convert the original value into a Date. The ToString is being operated on the entire class. Then use String.Format to output the date into the correct format you want. Should look something closer to this:
strSampleFlowLine = String.Format("MM/dd/yyyy", CDate(formattedDDoSSampleFlow.something)) & vbCrLf & vbCrLf

How to add item when using List (Of)?

I created a class where i declared some properties.
Public Class BlogPost
Dim _postTitleUrl As String = String.Empty
Dim _pageGUID As String = String.Empty
Property postTitleUrl() As String
Get
Return _postTitleUrl
End Get
Set(ByVal value As String)
_postTitleUrl = value
End Set
End Property
Property pageGUID() As String
Get
Return _pageGUID
End Get
Set(ByVal value As String)
_pageGUID = value
End Set
End Property
End Class
Now, I have another class where I want to set the values.
Public Class SetBlogData
Public blogPostList As New List(Of BlogPost)
Public dataCounter as integer = 0
blogPostList(dataCounter).pageGUID = mainBlogSPWeb.ID.ToString
....
This gives me an error about Index was out of range. Hpw can I properly access the properties in BlogPost class?
Because your list has nothing .
You should use add method to add your new item. Like ...
Dim blogPostList = New List(Of BlogPost)
Dim blogPost = New BlogPost
blogPost.pageGUID = mainBlogSPWeb.ID.ToString
blogPostList.Add(blogPost)
You need to put a BlogPost in your list by writing blogPost.List.Add(New BlogPost())
I find this a good way of inserting into a list:
1) Check if the list is nothing
2) If so instantiate a new list
3) Add the value to list.
Below is an example.
Private Sub ExampleAddValueToList(ByVal value as BlogPost)
Try
If _blogPostList Is Nothing Then
_blogPostList = New List(Of BlogPost)
End If
_blogPostList.Add(value)
Catch ex As Exception
debug.write(ex.message)
End Try
End Sub

Deserialize complex JSON (VB.NET)

I'm trying to deserialize json returned by some directions API similar to Google Maps API. My JSON is as follows (I'm using VB.NET 2008):
jsontext =
{
"version":0.3,
"status":0,
"route_summary":
{
"total_distance":300,
"total_time":14,
"start_point":"43",
"end_point":"42"
},
"route_geometry":[[51.025421,18.647631],[51.026131,18.6471],[51.027802,18.645639]],
"route_instructions": [["Head northwest on 43",88,0,4,"88 m","NW",334.8],["Continue on 42",212,1,10,"0.2 km","NW",331.1,"C",356.3]]
}
So far I came up with the following code:
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim lstTextAreas As Output_CloudMade() = js.Deserialize(Of Output_CloudMade())(jsontext)
I'm not sure how to define complex class, i.e. Output_CloudMade.
I'm trying something like:
Public Class RouteSummary
Private mTotalDist As Long
Private mTotalTime As Long
Private mStartPoint As String
Private mEndPoint As String
Public Property TotalDist() As Long
Get
Return mTotalDist
End Get
Set(ByVal value As Long)
mTotalDist = value
End Set
End Property
Public Property TotalTime() As Long
Get
Return mTotalTime
End Get
Set(ByVal value As Long)
mTotalTime = value
End Set
End Property
Public Property StartPoint() As String
Get
Return mStartPoint
End Get
Set(ByVal value As String)
mStartPoint = value
End Set
End Property
Public Property EndPoint() As String
Get
Return mEndPoint
End Get
Set(ByVal value As String)
mEndPoint = value
End Set
End Property
End Class
Public Class Output_CloudMade
Private mVersion As Double
Private mStatus As Long
Private mRSummary As RouteSummary
'Private mRGeometry As RouteGeometry
'Private mRInstructions As RouteInstructions
Public Property Version() As Double
Get
Return mVersion
End Get
Set(ByVal value As Double)
mVersion = value
End Set
End Property
Public Property Status() As Long
Get
Return mStatus
End Get
Set(ByVal value As Long)
mStatus = value
End Set
End Property
Public Property Summary() As RouteSummary
Get
Return mRSummary
End Get
Set(ByVal value As RouteSummary)
mRSummary = value
End Set
End Property
'Public Property Geometry() As String
' Get
' End Get
' Set(ByVal value As String)
' End Set
'End Property
'Public Property Instructions() As String
' Get
' End Get
' Set(ByVal value As String)
' End Set
'End Property
End Class
but it does not work. The problem is with complex properties, like route_summary. It is filled with "nothing". Other properties, like "status" or "version" are filled properly.
Any ideas, how to define class for the above JSON?
Can you share some working code for deserializing JSON in VB.NET?
Thanks,
Below is a sample Converter class that will take an incoming stream of JSON and convert to to an object you specify. I should note the below code is .Net 4.0. The JSON serializer in 4 is much easier to use. Let me know if you can't use 4 and I'll see if I can dig up a 3.5 version. Basically you need to create a class structure to map the JSON to a Class. I created the Route and RouteSummary classes for you. I left route_geometry and route_instructions as objects. You should create class definitions for each but this should get you started.
Imports System.IO
Imports System.Runtime.Serialization.Json
Imports System.Runtime.Serialization
<DataContract(Namespace:="")> _
Public Class Route
<DataMember(Name:="version")>
Public Property version As Double
<DataMember(Name:="status")>
Public Property status As Double
<DataMember(Name:="route_summary")>
Public Property route_summary As route_summary
<DataMember(Name:="route_geometry")>
Public Property route_geometry As Object()
<DataMember(Name:="route_instructions")>
Public Property route_instructions() As Object
End Class
<DataContract(Name:="route_summary", Namespace:="")> _
Public Class route_summary
<DataMember(Name:="total_distance")>
Public Property total_distance As Double
<DataMember(Name:="total_time")>
Public Property total_time As Double
<DataMember(Name:="start_point")>
Public Property start_point As Double
<DataMember(Name:="end_point")>
Public Property end_point As Double
End Class
Public Class Converter(Of t)
Public Function ReturnJSON(ByRef sreader As StreamReader) As t
If GetType(t).Equals(GetType(String)) Then
Dim result As Object = sreader.ReadToEnd.Replace("""", "")
Return result
Else
Dim ds As New DataContractJsonSerializer(GetType(t))
Dim result As t = DirectCast(ds.ReadObject(sreader.BaseStream), t)
ds = Nothing
Return result
End If
End Function
End Class
Sub Main()
Dim json As String = "{""version"":0.3, ""status"":0, ""route_summary"": { ""total_distance"":300, ""total_time"":14, ""start_point"":""43"", ""end_point"":""42"" }, ""route_geometry"":[[51.025421,18.647631],[51.026131,18.6471],[51.027802,18.645639]], ""route_instructions"": [[""Head northwest on 43"",88,0,4,""88 m"",""NW"",334.8],[""Continue on 42"",212,1,10,""0.2 km"",""NW"",331.1,""C"",356.3]]}"
Dim encoding As New System.Text.UTF8Encoding
Dim bytes() As Byte = encoding.GetBytes(json)
Using os As New MemoryStream
os.Write(bytes, 0, bytes.Length)
os.Position = 0
Using reader As New StreamReader(os)
Dim converter As New Converter(Of Route)
Dim output As Route
output = converter.ReturnJSON(reader)
'output contains data
End Using
End Using
End Sub
See this page for a detailed description of how to read the JSON data. http://www.json.org/