Linq Filter - After Filter Expecting Result Should be Nothing - vb.net

Please check below code, as my question related to following example.
Dim objPOSMaxDiscountTemplateDetailList As POSMaxDiscountTemplateDetailList
objPOSMaxDiscountTemplateDetailList = _
POSMaxDiscountTemplateDetailList.GetPOSMaxDiscountTemplateDetailList(UserDiscountPolicyTemplateCode)
'Filtering Above List
Dim Data = (From p In objPOSMaxDiscountTemplateDetailList _
Where p.ItemTypeCode = ItemTypeCode)
If Data IsNot Nothing Then
'' Do Something
End If
In above example objPOSMaxDiscountTemplateDetailList object am getting 14 records. After that am filtering those record with ItemTypeCode condition and there is no matched record with ItemTypeCode. So I am expecting Data object will be nothing. But while debugging i found Data object is not nothing and data.count am getting 0.
I don't understand this behavior, as same type of coding i made some other class which running perfectly as per my expectation.
Thanks.

It won't be Nothing. It will be an empty collection. LINQ to Objects query almost never returns Nothing.
Try
If Not Data.Any() Then
'' Do Something
End If

Related

LINQ Count problems while trying to access to subList from a List of Objects (VB.NET)

I'm having a pretty tough time figuring it out why it doesn't work properly but I'm asking for it.
Dim goodCount As Integer = (From item In equipmentTagList
Where item.Importance = "Critique"
Where item.Status <> TargetRange.OutOfRange
Select item).Count()
Dim badCount As Integer = (From item In equipmentTagList
Where item.Importance = "Critique"
Where item.Status.Contains(TargetRange.OutOfRange)
Select item).Count()
EquipmentTagList is a List(Of MachineTag) (custom object) so I want to get how many MachineTag from the EquipmentTagList matches the criteria. I'm still confused about why the first one works but not the other one. I know by debugging that the first one returns at least one result while the other returns nothing... I've searched a lot to get help for this error but unfortunately found nothing...
Thanks for helping me out.
EDIT:
The error I get is :
System.InvalidOperationException with Object reference not set to an instance of an object
Assuming for the moment that item.Status is an Integer data type (inferred from your use of TargetRange.OutOfRange as though it's an Enum), the syntax in your second snippet would be expected to fault.
The .Contains() method is reserved for use with IEnumerable objects, not Integer values.
If you modify your code slightly, to this:
Dim badCount = (From item In equipmentTagList
Where item.Importance = "Critique"
Where item.Status.Contains(TargetRange.OutOfRange)
Select item)
...and then set a breakpoint at some point after this call, you'll note that badCount is Nothing. Since Nothing can't have a .Count, the call fails.
Your first snippet is correct—as you've already pointed out.
EDIT
Something's not right here. Your code shouldn't even compile.
Here's what I'm getting:
So item.Status certainly can't be an Integer.
Maybe this will make it a bit easier. You can group by Status after filtering by Importance:
Dim items = From i In equipmentTagList Where i.Importance = "Critique"
Dim counts = items.ToLookup(Function(i) i.Status <> TargetRange.OutOfRange)
Dim goodCount = counts(True).Count()
Dim badCount = counts(False).Count()

VB.net application using reader HasRows

I am running an SQL Query with data readers in vb.net
reader3 = myCommand3.ExecuteReader
reader3.Read()
If reader3.HasRows Then
FromToDates = reader3.GetString(3)
End If
There are no rows being returned in this particular query, however even though the if reader3.HasRows is being used its still showing an error saying:
Additional information: Data is Null. This method or property cannot be called on Null values.
this is when trying to set the FromToDates variable but there are no rows being returned so it should not even reach this part
I doubt that there are no rows, i assume that there is at least one row where the value is NULL. You could check it with the IsDBNull-method:
If reader3.HasRows AndAlso Not reader3.IsDbNull(3) Then
FromToDates = reader3.GetString(3)
End If
However, the variable name suggests that it's a date, but you are storing it as string. Use the correct type which is date or datetime. If it's actually a datetime use:
Dim FromToDates As Date
If reader3.HasRows AndAlso Not reader3.IsDbNull(3) Then
FromToDates = reader3.GetDateTime(3)
End If
if you are using Reader.read() then i don't think so you need reader,hasrow(). you can do somthing like this
reader3 = myCommand3.ExecuteReader
If reader3.Read()Then
FromToDates = reader3.GetString(3)
End If
and related to your error its look like you are getting NULL value from database and in vb you can not read NULL, i will suggest to use ISNULL(Column_NAME,'') function in your SQL Script.
It seems that even though the row is empty (all DBNull, perhaps), there IS a row object returning from the query. There are several different solutions presented in this thread that all take differing approaches to catching the empty row before it errors!
http://www.vbforums.com/showthread.php?555183-datareader-and-empty-records

String assignment to dataview unexpectedly removes data row

I'm stumped on a problem where VB is removing a row of data upon a simple string assignment. The processing loop is below. If the dvData dataview has 3 rows (i.e., dvData.Count is 3) then the string assignment below is causing the dataview to lose a row (i.e,. after executing the string assignment the dvData.Count is 2). What more odd is that this same string assignment call is used many other times in the same script without causing the loss of a data row.
For Each oneShipment As Shipment In DelShipmentsList
For intRow = 0 To (dvData.Count - 1)
' Example: if dvData.Count is 3 at this point, then....
dvData(intRow)("Result") = " Receipt Transaction Accepted."
' ... now dvData.Count will be 2!
Next
Next
Try examining your RowFilter property for that DataView object. If it's something like this, it would explain the issue:
dvData.RowFilter = "Result NOT LIKE '*Accepted*'"
It looks like we found the answer, albeit completely unforeseen and worthy of much head scratching. Just to be super sure about passing integers and strings explicitly, I had him us CStr() and CInt() where appropriate. Here's what we found:
' This string causes the dataview to change error
dvData(CInt(intRow))(CStr("Result")) = CStr("Receipt Transaction Accepted")
'This string does not.
dvData(CInt(intRow))(CStr("Result")) = CStr("Receipt Transaction Successful")
Apparently there’s something about the word "accepted". We spent quite a while trying different strings to figure out why the Specified string causes the odd behavior that remains otherwise unexplained.

Query results don't match NumFound when using SolrNet with VB.NET

I have implemented SolrNet in a VB.NET web site and it's working perfectly with one exception. My results object may tell me that 10 matching "documents" have been found but the collection only contains 9.
My collection always contains 1 less than the NumFound property states. I have run the queries directly through my Solr instance and I know that the NumFound property is reflecting the correct value. Having reviewed the returned documents I can see that the first document in each result set is missing from my collection i.e. the one at position 0.
This seems like a problem connected to a zero indexed collection.
I can't see that I'm doing anything wrong and suspect that this is a bug. Has anyone else experienced this or can you suggest where I may have gone wrong?
Source code is as follows
Private Prods As New SolrQueryResults(Of BLL.solrProduct)
Dim solr As ISolrOperations(Of BLL.solrProduct) = ServiceLocator.Current.GetInstance(Of ISolrOperations(Of BLL.solrProduct))()
Dim SolrQueryOptions As New SolrNet.Commands.Parameters.QueryOptions() With {.Stats = New StatsParameters(), .Start = PagingCurrent, .Rows = PagingSize, .Facet = New FacetParameters() With { _
.MinCount = 1, .Queries = New SolrNet.ISolrFacetQuery() {New SolrFacetFieldQuery("brand")}}}
SolrQueryOptions.Stats.AddField("selling_price")
SolrQueryOptions.FilterQueries.Add(New SolrQueryByField("brand", "puma"))
Prods = solr.Query("shirt", SolrQueryOptions)
PagingTotal = Prods.NumFound 'This returns 10
lv_prods.DataSource = Prods
lv_prods.DataBind() 'This renders 9 items
Solr pagination is zero-based, i.e. the first item corresponds to Start=0

ComboBox DataBinding DisplayMember and LINQ queries

Update
I decided to iterate through the Data.DataTable and trimmed the values there.
Utilizing SirDemon's post, I have updated the code a little bit:
Sub test(ByVal path As String)
Dim oData As GSDataObject = GetDataObj(path)
EmptyComboBoxes()
Dim oDT As New Data.DataTable
Try
Dim t = From r In oData.GetTable(String.Format("SELECT * FROM {0}gsobj\paths ORDER BY keyid", AddBS(path))) Select r
If t.Count > 0 Then
oDT = t.CopyToDataTable
For Each dr As Data.DataRow In oDT.Rows
dr.Item("key_code") = dr.Item("key_code").ToString.Trim
dr.Item("descript") = dr.Item("descript").ToString.Trim
Next
dataPathComboBox.DataSource = oDT
dataPathComboBox.DisplayMember = "descript"
dataPathComboBox.ValueMember = "key_code"
dataPathComboBox.SelectedIndex = 0
dataPathComboBox.Enabled = True
End If
Catch ex As Exception
End Try
End Sub
This works almost as I need it to, the data is originally from a foxpro table, so the strings it returns are <value> plus (<Field>.maxlength-<value>.length) of trailing whitespace characters. For example, a field with a 12 character length has a value of bob. When I query the database, I get "bob_________", where _ is a space.
I have tried a couple of different things to get rid of the whitespace such as:
dataPathComboBox.DisplayMember.Trim()
dataPathComboBox.DisplayMember = "descript".Trim.
But nothing has worked yet. Other than iterating through the Data.DataTable or creating a custom CopyToDataTable method, is there any way I can trim the values? Perhaps it can be done in-line with the LINQ query?
Here is the code I have so far, I have no problem querying the database and getting the information, but I cannot figure out how to display the proper text in the ComboBox list. I always get System.Data.DataRow :
Try
Dim t = From r In oData.GetTable("SELECT * FROM ../gsobj/paths ORDER BY keyid") _
Select r
dataPathComboBox.DataSource = t.ToList
dataPathComboBox.SelectedIndex = 0
'dataPathComboBox.DisplayMember = t.ToList.First.Item("descript")
dataPathComboBox.Enabled = True
Catch ex As Exception
Stop
End Try
I know that on the DisplayMember line the .First.Item() part is wrong, I just wanted to show what row I am trying to designate as the DisplayMember.
I'm pretty sure your code tries to set an entire DataRow to a property that is simply the name of the Field (in a strongly type class) or a Column (in a DataTable).
dataPathComboBox.DisplayMember = "descript"
Should work if the DataTable contains a retrieved column of that name.
Also, I'd suggest setting your SelectedIndex only AFTER you've done the DataBinding and you know you actually have items, otherwise SelectedIndex = 0 may throw an exception.
EDIT: Trimming the name of the bound column will trim just that, not the actual bound value string. You either have to go through all the items after they've been bound and do something like:
dataPathComboBox.Item[i].Text = dataPathComboBox.Item[i].Text.Trim()
For each one of the items. Not sure what ComboBox control you're using, so the item collection name might be something else.
Another solution is doing that for each item when it is bound if the ComboBox control exposes an onItemDataBound event of some kind.
There are plenty of other ways to do this, depending on what the control itself offers and what you choose to do.
DisplayMember is intended to indicate the name of the property holding the value to be displayed.
In your case, I'm not sure what the syntax will by since you seem to be using a DataSet, but that should be
... DisplayMember="Item['descript']" ...
in Xaml, unless you need to switch that at runtime in which case you can do it in code with
dataPathComboBox.DisplayMember = "Item['descript']"
Again, not 100% sure on the syntax. If you are using a strongly typed DataSet it's even easier since you should have a "descript" property on your row, but given hat your error indicates "System.DataRow" and not a custom type, I guess you are not.
Because I can't figure out the underlying type of the datasource you are using I suggest you to change commented string to
dataPathComboBox.DisplayMember = t.ElementType.GetProperties.GetValue(0).Name
and try to determine correct index (initially it is zero) in practice.