Searching objects in a list - vb.net

I have a list of objects, and I want to search it to see if myobject.articleID matches a given articleID. From what I've gather using .Find(Of T) is the best way to go about this, however I am having some difficulty implementing it. Here's some code I have so far:
<WebMethod()> _
Public Function SetTagOnFavorite(ByVal articleID As Integer, ByVal tagtext As String, ByVal mobileGUID As String) As AddTagResult
Dim result As New AddTagResult
Dim userID As Long = GetUserIDByMobileGUID(mobileGUID)
If userID > 0 Then
Dim pageNum As Integer = 1
Dim pageLen As Integer = 500 'arbitrarily large number
Dim savedArticleList As New List(Of SimpleArticle)
savedArticleList = GetSavedArticles(mobileGUID, pageNum, pageLen)
If savedArticleList.Find(Function( m As SimpleArticle) m.articleID = articleID)
Dim lq As New lqDFDataContext
Dim var = lq.web_AddTagToArticle(userID, articleID, tagtext).ToList()
If var.Any() Then
Dim vRes = var.First()
result.articletagID = vRes.articletagID
result.newarticletag = vRes.newarticletag
result.newusertag = vRes.newusertag
result.usertagID = vRes.usertagID
result.resultinfo = "Success."
End If
End If
Else
result.resultinfo = STR_NoUserIDMostLikelyTheSessionTimedOut
End If
Return result
End Function
The error I get is, "value of type SimpleArticle cannot be converted to Boolean".

Because Find(Of returns the found object, you need to change this line:
If savedArticleList.Find(Function( m As SimpleArticle) m.articleID = articleID)
to
If savedArticleList.Find(Function( m As SimpleArticle) m.articleID = articleID) IsNot Nothing
or if you need the found item, store the result of Find in a local variable.

You could optimize #competent_tech's answer further as:
If savedArticleList.Any(Function(m) m.articleID = articleID))

Related

(VB.NET) Find all duplicates in a list of objects based on multiple properties

I have a list of CommissionStatement objects which i created. I need to create a new list which only holds the duplicates found in this list based on 3 properties: Firm; Provider; and Total (ie each of these 3 have to be the same in 2 or more objects for it to be recognized as a duplicate)
Object is a simple object of strings at the moment.
Private Class CommissionStatement
Property Provider As String
Property Firm As String
Property Source As String
Property Media As String
Property Total As String
Property Received As String
End Class
I have a list of all CommissionStatments as follows:
Dim fileLocation As String = importText.Text
Dim csvText As String = My.Computer.FileSystem.ReadAllText(fileLocation).Replace(", ", " ")
Dim providerString As String = ""
Dim allStatements = New List(Of CommissionStatement)
Dim countIndex As Integer = 0, maxIndex As Integer = csvText.Split(vbLf).Length
For Each line As String In csvText.Split(vbLf)
'' Remove the top row
countIndex += 1
If countIndex = 1 Then
Continue For
End If
statementProgress.Value = ((countIndex / maxIndex) * 100)
'' Build the New commissionStatement object and add it to the allStatements list
If Not line = "" Then
Dim commissionStatement = New CommissionStatement
With commissionStatement
.Provider = line.Split(",")(0)
.Firm = line.Split(",")(1)
.Source = line.Split(",")(2)
.Media = line.Split(",")(3)
.Total = line.Split(",")(4)
End With
providerString &= commissionStatement.Provider & ","
allStatements.Add(commissionStatement)
End If
Next
First post on StackOverflow so sorry if its not very clear! The duplicate list needs to also be a list of CommissionStatements which contain the duplicates from the allStatements list based on Firm Provider and Total
Your best bet is to use a lambda expression. The function below should do what you ask.
Private Function GetDuplicateCommisionStatements(tempStatement As CommissionStatement) As List(Of CommissionStatement)
Return allStatements.FindAll(Function(x) x.Firm = tempStatement.Firm And x.Provider = tempStatement.Provider And x.Total = tempStatement.Total)
End Function
And use it like this..
duplicatelist = GetDuplicateCommisionStatements(testCommisionStatement)
using your own object names of course.
Incidentally, you could shorten the sub using the With statement like below
Private Function GetDuplicateCommisionStatements(tempStatement As CommissionStatement) As List(Of CommissionStatement)
With tempStatement
Return allStatements.FindAll(Function(x) x.Firm = .Firm And x.Provider = .Provider And x.Total = .Total)
End With
End Function

visual basic multiple input boxes i only need 1

Why do I keep getting two input boxes instead of one? What am I doing wrong? Is it how I am passing values through functions? If so, how can I fix this?
Private Sub Calculate_Click(sender As Object, e As EventArgs) Handles Calculate.Click
'Dim ready_ship As Integer = GetInStock()
Dim display_spools As Integer = ReadyToShip()
Dim display_backOrders As Integer = BackOrdered()
lbl_rship.Text = display_spools.ToString()
lbl_backo.Text = display_backOrders.ToString()
End Sub
Function GetInStock() As Integer
Dim amount_Spools As String = Nothing
amount_Spools = InputBox(" Enter the number of spools currently in stock: ")
Return CInt(amount_Spools)
End Function
Function ReadyToShip() As Integer
Dim ready_ship As Integer = GetInStock()
Dim a As Integer
a = CInt(ready_ship)
Return a
End Function
Function BackOrdered() As Integer
Dim b As Integer = ReadyToShip()
Dim c As Integer
c = b - CInt(TextBox1.Text)
Return c
End Function
End Class
Your Calculate_Click event is calling ReadyToShip() and BackOrdered() functions which are both going to GetInStock() function, which is displaying the input box. So it will be displayed twice.
This class would be better served using properties, they are easier to manage and will help avoid this kind of method duplication.

How can I get hourly weather forecast in VB.net?

I've seen some questions similar to this on here, but none of them seem to help me. I don't really care what API is used, be it Google, Yahoo!, The Weather Channel, or any other. I've got code that will get the high and low of the current day, based on the location given by the user, but I can't seem to get the hourly predictions for temperature or weather condition, which is what I'm really looking for. I don't really care for wind speeds, humidity, or the "feels like" temperature, though I'll add them if I can figure out how to. I'm trying to get data that will look something like what is here. (www.weather.com/...)
I'm pretty new to parsing XML so that may be part of my problem, too. Thanks in advance for any help. I greatly appreciate it.
I have something you might enjoy:
<Runtime.CompilerServices.Extension()>
Module Weather
Public Structure WeatherInfo_Forecast
Dim DayOfWeek As String
Dim low As Double
Dim high As Double
Dim icon As String
End Structure
Public Structure WeatherInfo_Wind
Dim direction As String
Dim speed As Double
Dim unit As String
End Structure
Public Structure WeatherInfo_Typed
Dim Failed As Boolean
Dim errormessage As Exception
Dim location As String
Dim forcast_date As DateTime
Dim checked_time_date As DateTime
Dim humidity As Double
Dim highf As Double
Dim lowf As Double
Dim highc As Double
Dim lowc As Double
Dim currenttempC As Double
Dim currenttempF As Double
Dim predicted_icon As String
Dim current_icon As String
Dim current_condition As String
Dim predicted_condition As IEnumerable(Of WeatherInfo_Forecast)
Dim wind_condition As WeatherInfo_Wind
Dim day As String
End Structure
<Runtime.CompilerServices.Extension()> _
Public Function ToC(ByVal F As Double) As Double
Return ((F - 32) / 9) * 5
End Function
<Runtime.CompilerServices.Extension()> _
Public Function TryParseAsDouble(ByVal s As String) As Double
Dim rv As Double
If Double.TryParse(s, rv) = False Then rv = Double.NaN
Return rv
End Function
<Runtime.CompilerServices.Extension()> _
Public Function TryParseAsDate(ByVal s As String) As DateTime
Dim rv As DateTime
If DateTime.TryParse(s, rv) = False Then rv = Nothing
Return rv
End Function
Private Function ParseHumidity(ByVal s As String) As Double
If Not s Is Nothing Then
Dim humRegEx As New System.Text.RegularExpressions.Regex("Humidity: (?<Value>\d+)\w*\%")
Dim m = humRegEx.Match(s)
If m.Length = 0 Then Return Double.NaN
Return Double.Parse(m.Groups("Value").Value)
End If
End Function
Private Function ParseWind(ByVal s As String) As WeatherInfo_Wind
Dim rv As New WeatherInfo_Wind
If Not s Is Nothing Then
Dim humRegEx As New System.Text.RegularExpressions.Regex("Wind\:\s+(?<Direction>[NEWSnews]{1,2})\s+at\s+(?<speed>(?<value>\d+)\s(?<units>\w+)){1}")
Dim m = humRegEx.Match(s)
rv.speed = Double.NaN
If m.Length = 0 Then Return rv
With rv
.direction = m.Groups("Direction").Value
If Double.TryParse(m.Groups("value").Value, .speed) = False Then .speed = Double.NaN
.unit = m.Groups("units").Value
End With
End If
Return rv
End Function
<DebuggerHidden()>
Public Function Grab_Weather(ByVal Location As String) As WeatherInfo_Typed
Dim GrabWeather As New WeatherInfo_Typed
With GrabWeather
.Failed = True
Try
Dim xml As XDocument = XDocument.Load("http://www.google.com/ig/api?weather=" & Location)
Dim xp = xml.<problem_cause>
If xp.Any Then Return GrabWeather
.location = xml...<city>.#data
.forcast_date = xml...<forecast_date>.#data.TryParseAsDate
.checked_time_date = xml...<current_date_time>.#data.TryParseAsDate
.humidity = ParseHumidity(xml...<humidity>.#data)
.highf = xml...<high>.#data.TryParseAsDouble
.lowf = xml...<low>.#data.TryParseAsDouble
.highc = GrabWeather.highf.ToC
.lowc = GrabWeather.highc.ToC
.currenttempC = xml...<temp_c>.#data.TryParseAsDouble
.currenttempF = xml...<temp_f>.#data.TryParseAsDouble
'.current_icon = "http://www.google.com" & xml...<icon>.#data
'.predicted_icon = "http://www.google.com" & xml...<high>.#data
.current_condition = xml...<condition>.#data
.predicted_condition = From f In xml...<forecast_conditions> _
Select New WeatherInfo_Forecast With { _
.DayOfWeek = f.<day_of_week>.Value, _
.high = f.<high>.#data.TryParseAsDouble, _
.low = f.<low>.#data.TryParseAsDouble}
'.icon = "http://www.google.com" & f.<icon>.#data}
.wind_condition = ParseWind(xml...<wind_condition>.#data)
.day = xml...<day_of_week>.#data
.Failed = False
Return GrabWeather
Catch ex As Exception
.errormessage = ex
Return GrabWeather
End Try
End With
End Function
End Module
I finally found what I was looking for from Weather Underground. They have three APIs, and, starting with the middle one, gives hourly forecasts for 36 hours. You get English and Metric predicted statistics for temperature, "feels like" temperature, dew point, wind speed, and wind direction. There's also wind chill and heat index, but every result for both in English and Metric was -9998, so I'm pretty sure those results are a bit off! Also there are qpf, snow, pop, and mslp. Unfortunately qpf and snow have not results and I'm not sure what pop and mslp are. All results are available in JSON and XML. They have some image requests, too, but I haven't looked into them yet.
Update:
Link Updated

How do I access the data filters in this MVC3 VB application BEFORE loading the data?

I have a few filters for table data represented by dropdowns, but the table data is really huge and the process hangs for a few minutes until the complete table is rendered; only then is the table presented and I can use those filters.
I want to be able to access the filters before presenting the data; I don't want to wait for the table to load. This could be done by separating the filters into another view/controller, but I want to handle inside the index() method.
I tried to delete the part where the process checks if filters are set, but then than it will work if I set all filters only.
Relevant code:
Function Index(SelectedTimeType As System.Nullable(Of Integer), SelectedTimeStatus As System.Nullable(Of Integer), SelectedProject As System.Nullable(Of Integer), SelectedTask As System.Nullable(Of Integer)) As ActionResult
Dim tipovi = unitOfWork.TimeTypeRepository.Get(orderBy:=Function(q) q.OrderBy(Function(d) d.Opis))
ViewBag.SelectedTimeType = New SelectList(tipovi, "TimeTypeID", "Opis", SelectedTimeType)
Dim statusi = unitOfWork.TimeStatusRepository.Get(orderBy:=Function(q) q.OrderBy(Function(d) d.Opis))
ViewBag.SelectedTimeStatus = New SelectList(statusi, "TimeStatusID", "Opis", SelectedTimeStatus)
Dim projekti = unitOfWork.ProjectRepository.Get(orderBy:=Function(q) q.OrderBy(Function(d) d.Opis))
ViewBag.SelectedProject = New SelectList(projekti, "ProjekatID", "Opis", SelectedProject)
Dim taskovi = unitOfWork.TaskRepository.Get(orderBy:=Function(q) q.OrderBy(Function(d) d.Opis))
ViewBag.SelectedTask = New SelectList(taskovi, "TaskID", "Opis", SelectedTask)
Dim timeTypeID As Integer = SelectedTimeType.GetValueOrDefault()
Dim timeStatusID As Integer = SelectedTimeStatus.GetValueOrDefault()
Dim projekatID As Integer = SelectedProject.GetValueOrDefault()
Dim taskID As Integer = SelectedTask.GetValueOrDefault()
Return View(unitOfWork.TimeTrackingRepository.Get(
filter:=Function(d) Not (SelectedTimeType.HasValue And SelectedTimeStatus.HasValue And SelectedProject.HasValue And SelectedTask.HasValue) OrElse (d.TimeTypeID = timeTypeID And d.TimeStatusID = timeStatusID And d.ProjectID = projekatID And d.TaskID = taskID),
orderBy:=Function(q) q.OrderBy(Function(d) d.TimeTrackingID)))
End Function

How to retrieve just unread emails using pop3?

I'm using open source component to retrieve emails from my mail server using vb.net (pop3)
but because i have a lot of messages it gives me response Time out and i think if i just got the new messages it will make reading faster.
this is my code:
Dim popp As New Pop3Client("user#mail.com", "*******", "pop3.mail.com")
popp.AuthenticateMode = Pop3AuthenticateMode.Pop
popp.Port = 110
'popp.Ssl = True
popp.Authenticate()
Dim msglist As New List(Of String)
If popp.State = Pop3ConnectionState.Authenticated Then
Dim totalmsgs As Integer = popp.GetTotalMessageCount()
If totalmsgs > 0 Then
For index As Integer = 1 To totalmsgs
Dim msg As Pop3Message = popp.GetMessage(index)
msglist.Add(msg.Subject)
Next
popp.Close()
End If
End If
Return msglist
please i need some help if i'm using the component in a wrong way or if there is another component do what i'm looking for.
b.s. : my component name is "Higuchi.Mail.dll" or "OpenPOP.dll" and the two are same.
thanks
POP3 does not have the capibility to track whether messages are read or unread. I would suggest you set your limit to a finite number such as 50 or 100. Perhaps you could do some sort of pagination system.
This code needs to be within a function so that you can call it like so:
Sub Main
Dim start As Integer = Integer.parse(Request.QueryString("start"))
Dim count As Integer = Integer.parse(Request.QueryString("count"))
Dim subjects As New List(Of String)
subjects = getSubjects(start, count)
'Do whatever with the results...
'
End Sub
Function getSubjects(ByVal startItem As Integer, ByVal endItem as Integer) As List(Of String)
Dim popp As New Pop3Client("user#mail.com", "*******", "pop3.mail.com")
popp.AuthenticateMode = Pop3AuthenticateMode.Pop
popp.Port = 110
popp.Authenticate()
Dim msglist As New List(Of String)
If popp.State = Pop3ConnectionState.Authenticated Then
Dim totalmsgs As Integer = popp.GetTotalMessageCount()
Dim endItem As Integer = countItems + startItem
If endItem > totalmsgs Then
endItem = totalmsgs
End If
If totalmsgs > 0 Then
For index As Integer = startItem To endItem
Dim msg As Pop3Message = popp.GetMessage(index)
msglist.Add(msg.Subject)
Next
popp.Close()
End If
End If
Return msglist
End Function
Just have the program change the value for startItem to 50 get the next fifty (items 50-100)
POP3 protocol does not have the notion of seen/unseen messages.
Can't you use IMAP?
It would give you more features (like searching, flagging, folder management) than POP3.