How to add item when using List (Of)? - vb.net

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

Related

Delete duplicates from list

I have the following class :
Public Class titlesclass
Public Property Link As String
Public Property Title As String
Public Function Clear()
Link.Distinct().ToArray()
Title.Distinct().ToArray()
End Function
End Class
And the following code :
For Each title As Match In (New Regex(pattern).Matches(content)) 'Since you are only pulling a few strings, I thought a regex would be better.
Dim letitre As New titlesclass
letitre.Link = title.Groups("Data").Value
letitre.Title = title.Groups("Dataa").Value
lestitres.Add(letitre)
'tempTitles2.Add(title.Groups("Dataa").Value)
Next
I tried to delete the duplicated strings using the simple way
Dim titles2 = lestitres.Distinct().ToArray()
And calling the class function :
lestitres.Clear()
But the both propositions didn't work , i know that i'm missing something very simple but still can't find what it is
Easier to use a class that already implements IComparable:
Dim query = From title In Regex.Matches(content, pattern).Cast(Of Match)
Select Tuple.Create(title.Groups("Data").Value, title.Groups("Dataa").Value)
For Each letitre In query.Distinct
Debug.Print(letitre.Item1 & ", " & letitre.Item2)
Next
or Anonymous Types:
Dim query = From title In Regex.Matches(content, pattern).Cast(Of Match)
Select New With {Key .Link = title.Groups("Data").Value,
Key .Title = title.Groups("Dataa").Value}
For Each letitre In query.Distinct
Debug.Print(letitre.Link & ", " & letitre.Title)
Next
Ok, Since I notice you are using a ClassHere is one option you can do in order to not add duplicate items to your List within a class.I'm using a console Application to write this example, it shouldn't be too hard to understand and convert to a Windows Form Application if need be.
Module Module1
Sub Main()
Dim titlesClass = New Titles_Class()
titlesClass.addNewTitle("myTitle") ''adds successfully
titlesClass.addNewTitle("myTitle") '' doesn't add
End Sub
Public Class Titles_Class
Private Property Title() As String
Private Property TitleArray() As List(Of String)
Public Sub New()
TitleArray = New List(Of String)()
End Sub
Public Sub addNewTitle(title As String)
Dim added = False
If Not taken(title) Then
Me.TitleArray.Add(title)
added = True
End If
Console.WriteLine(String.Format("{0}", If(added, $"{title} has been added", $"{title} already exists")))
End Sub
Private Function taken(item As String) As Boolean
Dim foundItem As Boolean = False
If Not String.IsNullOrEmpty(item) Then
foundItem = Me.TitleArray.Any(Function(c) -1 < c.IndexOf(item))
End If
Return foundItem
End Function
End Class
End Module
Another option would be to use a HashSet, It will never add a duplicate item, so even if you add an item with the same value, it wont add it and wont throw an error
Sub Main()
Dim titlesClass = New HashSet(Of String)
titlesClass.Add("myTitle") ''adds successfully
titlesClass.Add("myTitle") '' doesn't add
For Each title As String In titlesClass
Console.WriteLine(title)
Next
End Sub
With all of that aside, have you thought about using a Dictionary so that you could have the title as the key and the link as the value, that would be another way you could not have a list (dictionary) contain duplicate items

Trying to populate combobox from SQLite VB.NET Windows Universal App

I am new to SQLite and I am trying to populate a ComboBox in a Windows Universal App from the database. I did the following so far:
With cmbPaciente.Items
Try
Dim sConexao As String = Path.Combine(ApplicationData.Current.LocalFolder.Path, "\Banco\Pronto Facil.db")
Dim aConexao As New SQLite.SQLiteConnection(sConexao)
Dim Comando = aConexao.Execute("select Nome from Dados_Pessoais")
For Each item In Comando
.Add(item)
Next
Catch ex As Exception
.Add("Text 1")
.Add("Text 2")
End Try
End With
I am getting this error:
BC32023 Expression is of type 'Integer', which is not a collection type.
I understood thats because aConexao.Execute is returning an integer, but how else should I do it then?
I was using the wrong approach, this way it Works:
With cmbPaciente.Items
Dim sConexao As String = Path.Combine(ApplicationData.Current.LocalFolder.Path, "Deal.db")
Dim aConexao As New SQLiteConnection(New SQLitePlatformWinRT(), sConexao)
For Each item As Stockvb In aConexao.Table(Of Stockvb)()
Dim newlist As New Stockvb()
newlist.Id = item.Id
newlist.Symbol = item.Symbol
combolist.Add(newlist)
Next
cmbPaciente.ItemsSource = combolist
End With
And here is the Stockvb class:
Public Class Stockvb
<PrimaryKey, AutoIncrement>
Public Property Id() As Integer
Get
Return m_Id
End Get
Set
m_Id = Value
End Set
End Property
Private m_Id As Integer
<MaxLength(8)>
Public Property Symbol() As String
Get
Return m_Symbol
End Get
Set
m_Symbol = Value
End Set
End Property
Private m_Symbol As String
End Class
Special thanks to Grace Feng - MSFT

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

Image Search with Bing/Azure in VB.NET

I'm trying to do a Bing Image Search Application (Azure Version), and i can't make progress. The code language is vb.net. Basically what i'm doing is trying to edit this code, that actually worked. Any Solutions ?
Function ExecuteQuery() As Boolean
Dim esito As Boolean = False
Try
Dim query As String = System.Web.HttpUtility.UrlEncode("Inception Movie")
Dim skip As String = "10"
Dim urlBase As New Uri("https://api.datamarket.azure.com")
Dim accountKey As String = "tymv8z6jFSdo4eQ3vsS5r8SZAmFtA24e6dmfyvaLh3U"
Dim credentials As New NetworkCredential(accountKey, accountKey)
Dim dsc As New System.Data.Services.Client.DataServiceContext(urlBase)
dsc.Credentials = New NetworkCredential(accountKey, accountKey)
Dim urlSearch As Uri = New Uri(("https://api.datamarket.azure.com/Bing/Search/Image?Query=%27" + query + "%27&$skip=" + skip))
Dim webResults = dsc.Execute(Of WebResult)(urlSearch)
For Each result As WebResult In webResults
ListBox1.Items.Add(result.Title)
ListBox1.Items.Add(result.Description)
singleValue = singleValue + 1
Next
esito = True
Catch ex As Exception
esito = False
End Try
Return esito
End Function
Partial Public Class WebResult
Private _ID As Guid
Private _Title As [String]
Private _Description As [String]
Private _DisplayUrl As [String]
Private _Url As [String]
Private _MediaUrl As [String]
Public Property ID() As Guid
Get
Return Me._ID
End Get
Set(ByVal value As Guid)
Me._ID = value
End Set
End Property
Public Property Title() As [String]
Get
Return Me._Title
End Get
Set(ByVal value As [String])
Me._Title = value
End Set
End Property
Public Property Description() As [String]
Get
Return Me._Description
End Get
Set(ByVal value As [String])
Me._Description = value
End Set
End Property
Public Property DisplayUrl() As [String]
Get
Return Me._DisplayUrl
End Get
Set(ByVal value As [String])
Me._DisplayUrl = value
End Set
End Property
Public Property Url() As [String]
Get
Return Me._Url
End Get
Set(ByVal value As [String])
Me._Url = value
End Set
End Property
Public Property MediaUrl() As [String]
Get
Return Me._MediaUrl
End Get
Set(ByVal value As [String])
Me._MediaUrl = value
End Set
End Property
End Class
I now solved the puzzle, founded a simple way to do this thing just using an class file:
1 - Just download this file: http://www.getcodesamples.com/src/15958EA3/F43E1E1A
2 - Then add the same file to your project
3 - Add the following code:
Dim strBingKey As String = "xxxaccountkeyxxx"
Dim bingClass As New Bing.BingSearchContainer(New Uri("https://api.datamarket.azure.com/Bing/Search/"))
bingClass.Credentials = New NetworkCredential(strBingKey, strBingKey)
Dim query = bingClass.Image("Inception" + "Movie", Nothing, "en-us", "Off", Nothing, Nothing, Nothing)
Dim results = query.Execute()
For Each result In results
ListBox1.Items.Add(result.Title)
ListBox1.Items.Add(result.MediaUrl)
Console.WriteLine(result.Thumbnail) 'ThumbNail type, need to convert to use in result list
Next
Thank you all for the patience!

Getting a NullReferenceException when adding something to a list

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).