LINQ Query Causing Exit Sub or Swallowing Error - vb.net

My code is as follows:
Using _EntityModel As New AboveNemaSalesDatabaseEntities()
Dim _SelectActiveOptionCodes = (From _OptCodes In _EntityModel.tblOptionCodes
Where _OptCodes.fdStatus = "A"
Select _OptCodes.fdDescription, _OptCodes.fdOptionCode).ToList()
Dim _SelectActiveOptionCodes2 = (From _OptCodes In _EntityModel.tblOptionCodes
Where _OptCodes.fdStatus = "A"
Select New optionCodes With {.description = _OptCodes.fdDescription,
.optionCode = _OptCodes.fdOptionCode})
sortableOptionCodes = _SelectActiveOptionCodes2
sortedOptionCodes = _SelectActiveOptionCodes2
OptionCodeListBox.DataSource = sortedOptionCodes
OptionCodeListBox.DisplayMember = "fdDescription"
OptionCodeListBox.ValueMember = "fdOptionCode"
End Using
The first query works fine and returns a list in the format [index]{description = "descritption here", optionCode = "option code here"}
The second query creates but when it is called to save to my custom class the program exits the sub or swallows an error. Stepping through the code, the line starting with sortedOptionCodes and after never runs.

The main issue I was dealing with is that my query was producing a list of optionCodes and my variable was not prepared to store this.
Old variables:
Dim sortableOptionCodes As optionCodes
Dim sortedOptionCodes As optionCodes
New variables:
Dim sortableOptionCodes As List(Of optionCodes)
Dim sortedOptionCodes As List(Of optionCodes)
I also added a .ToList() function to the end of the second query.

Related

Conversion of type string " " to double not valid exception in vb.net code

I am trying to upload a csv file that has two records in it.
The below code executed for two times and third time I got this exception----Conversion of type string " " to double not valid
I put a debugger where I found the values of two colums of excel sheet but third time I am getting this exception. Your help is highly appreciated.
Below is the code.
Public Function GetLocationInformation(stream As Stream) As List(Of CsvPropLocation) _
Implements ICsvHandling.GetLocationInformation
If stream Is Nothing Then Return Nothing
Dim locations = New List(Of CsvPropLocation)
Using reader = New StreamReader(stream)
Dim config = New CsvConfiguration(CultureInfo.InvariantCulture) With {
.HasHeaderRecord = True,
.IgnoreBlankLines = False
}
Using csv = New CsvReader(reader, config)
Using dataReader As New CsvDataReader(csv)
Dim dt = New DataTable()
dt.Load(dataReader)
For Each row As DataRow In dt.Rows
Dim propLocation As CsvPropLocation
'find or create a propLocation
If locations.Any(Function(x) x.nLocationNumber = row("LocNum")) Then ######Got exception here ######
propLocation = locations.First(Function(x) x.nLocationNumber = row("LocNum"))
Else
propLocation = New CsvPropLocation(row("LocNum"))
locations.Add(propLocation)
End If
'do building stuff.
Dim building = ParseRowIntoBuilding(row)
propLocation.AddBuilding(building)
Next
End Using
End Using
End Using
Return locations
End Function
Change your line to
Dim number As Double
If Double.TryParse(row("LocNum"), number ) AndAlso locations.Any(Function(x) x.nLocationNumber = number )
This way you make sure number will be evaluated only if it gets a valid value from row("LocNum")
Also keep in mind the Else part must be controlled as New CsvPropLocation(row("LocNum")) probably is expecting a valid Double which isnt inside locations so, change to:
Else If Double.TryParse(row("LocNum"), number ) 'You can check against number = 0
'if zero isn't a valid value for number
'(or initialize number to a known invalid value and check against it)
'if yuo didn't want a double try parse
propLocation = New CsvPropLocation(number)
locations.Add(propLocation)
End If

Make pre-prepared sql command in libreoffice basic

I'm trying to make a prepared query based on the value in a field in my form in libreoffice basic.For this, I created a macro.
But it returns an error on the query line saying
BASIC syntax error.
Unexpected symbol: oInstruction_SQL
Sub concatMotherName
Dim oSourceDonnees As Object
Dim oConnexion As Object
Dim stSql As String
Dim oResultat As Object
oSourceDonnees = thisComponent.Parent.dataSource
oConnexion = oSourceDonnees.getConnection("","")
oInstruction_SQL = oConnexion.createStatement()
Dim valueData As String
Dim dateLabel As String
valueData = ThisComponent.Drawpage.Forms.getByName("Form").getByName("id_mother_label").getCurrentValue()
stSql = "SELECT NOM_MERE FROM ""T_MOTHER"" WHERE ""NUM_MOTHER"" = ?" _
oInstruction_SQL = = oConnection.prepareStatement(stSql)
oInstruction_SQL.setString(1, valueData)
oResultat = oInstruction_SQL.executeQuery(stSql)
If Not IsNull(oResultat) Then
oResultat.Next()
MsgBox oResultat.getString(1)
End If
End Sub
There are two syntax problems. The first is the _ after the query string, which indicates that the next line is a continuation of that one. It's not a continuation, so remove it.
The second error is on the next line: = =.
When these errors are fixed, the code compiles successfully.

Why does ThenBy raise an exception in the following case?

I am using .NET 4.5 and I would like to understand the following:
If I execute this everything works as expected:
Dim lst = Enumerable.Range(1, 10)
Dim lstOrdered = lst.OrderBy(Function(i) i Mod 2)
Dim lst2 = lstOrdered.ThenBy(Function(i) -i)
However, the following raises a System.MissingMemberException
Dim lst = Enumerable.Range(1, 10)
Dim lstOrdered
lstOrdered = lst.OrderBy(Function(i) i Mod 2)
Dim lst2 = lstOrdered.ThenBy(Function(i) -i)
In the real code, we have to dynamically apply sometimes OrderBy and sometimes OrderByDescending and then dymaically continue with ThenBy and ThenByDescending. That's why I would like to declare it first.
Also note that the production code contains anonymous objects instead of integers.
EDIT
The following code it's closer to production and I don't seem to manage adapting to the provided answer. It compiles but throws an execution error.
Dim lst = Enumerable.Range(1, 10).Select(Function(i) New With {.a = "foo", .b = i Mod 2, .c = -i})
Dim lstOrdered As IOrderedEnumerable(Of Object)
lstOrdered = lst.OrderBy(Function(i) i.b)
Dim lst2 = lstOrdered.ThenBy(Function(i) i.c)
The error sais the following
Unable to cast object of type 'System.Linq.OrderedEnumerable`2[VB$AnonymousType_3`3[System.String,System.Int32,System.Int32],System.Int32]' to type 'System.Linq.IOrderedEnumerable`1[System.Object]'
In your second example, you didn't declare a type for lstOrdered. It should work if you change the second line to
Dim lstOrdered As IOrderedEnumerable(Of Integer)
Set Option Strict On to catch these errors at compile time. You can make the statement Option Strict On the first one in your code file, set that option as the default in Test|Options|Environment|Projects and Solutions|VB Defaults.

Vb.net Code syntax error

I have following vb.net code and i am getting syntax error in it
Update
Protected Sub OpenLogin_Click(ByVal src As Object, ByVal e As CommandEventArgs)
Dim StrUri As String = e.CommandArgument.ToString()
Dim openid As New OpenIdRelyingParty()
Dim b = New UriBuilder(Request.Url)
With Key
.Query = ""
End With
'var b = new UriBuilder(Request.Url) { Query = "" };
Dim req = openid.CreateRequest(StrUri)
Dim fetchRequest = New FetchRequest()
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email)
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First)
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last)
req.AddExtension(fetchRequest)
req.RedirectToProvider()
End Sub
Now the error in code is "Key is Not declared" What should i do now for this
Two problems:
The Key reserved word is only to be used when identifying a multi-part key for grouping using Enumerable.GroupBy. It is not required for setting object properties inline with their constructor.
You are experiencing a problem whereby you have separated the With decorator onto a new line, which is syntactically incorrect because you are now treating it as a With block, which means that every dot access will target the variable immediately following the With statement. You need to use a line continuation character or put With on the same line as the object constructor:
Ex 1
Dim b = New UriBuilder(Request.Url) With {
.Query = ""
}
Ex 2
Dim b = New UriBuilder(Request.Url) _
With { .Query = "" }
EDIT:
You cannot use this syntax with a Visual Studio 2005/.NET 2.0 project. Just construct the object then initialize the property:
Dim b As New UriBuilder(Request.Url)
b.Query = ""
AFAIK, you don't need the curly braces.
With Something
.Property1 = True
.Property2 = "Inactive"
' And so on
End With
UPDATE
With Key
.Query = ""
End With
Why do you need a With clause here anyway ? The above is syntactically equivalent to
Key.Query = ""
Declare the Key variable or else remove it from your code.

VBNet Error: Collection was modified; enumeration operation may not execute

This is what happened: on the form load of my application i created a background worker to bind collection (records from database filled in the dataset) on my control. but the problem is when the i updated the records on the database it throws an error if i run this procedure again.
If xControl.InvokeRequired Then
Dim MyDelegate As New InitializeDataBinding_Delegate(AddressOf InitializeDataBinding)
Invoke(MyDelegate, New Object() {xControl, xQuery, xPrimaryKey}) ' ERROR HERE SAYING: Collection was modified; enumeration operation may not execute.
Else
Using ds As DataSet = New DataSet()
Using dbAdapter As MySqlDataAdapter = New MySqlDataAdapter(xQuery, ConnectionClass.ConnectionString)
dbAdapter.Fill(ds)
End Using
Dim dvm As DataViewManager = New DataViewManager(ds)
Dim iDataList As DataView = dvm.CreateDataView(ds.Tables(0))
For Each iBind As Binding In xControl.DataBindings
xControl.DataBindings.Remove(iBind)
Next
xControl.DataBindings.Add("EditValue", iDataList, xPrimaryKey)
xControl.Properties.DataSource = iDataList
xControl.EditValue = Nothing
txtStatus.Text = "Ready"
End Using
End If
You have to avoid updation in collection while iterating it using For Each. Use simple For loop instead of For Each.
You can't use a For Each loop to remove items from a diction or KeyValuePair, but you can use a regular for loop, get the key and use the key to remove the item from the list.
For i As Integer = 0 To oDictionary.Count - 1
Dim sKey = m_oDictionary.ElementAt(i).Key
m_oDictionary.Remove(sKey)
Next
Solved by adding:
xControl.DataBindings.Clear()
If xControl.InvokeRequired Then
Dim MyDelegate As New InitializeDataBinding_Delegate(AddressOf InitializeDataBinding)
Invoke(MyDelegate, New Object() {xControl, xQuery, xPrimaryKey}) ' ERROR HERE SAYING: Collection was modified; enumeration operation may not execute.
Else
Using ds As DataSet = New DataSet()
Using dbAdapter As MySqlDataAdapter = New MySqlDataAdapter(xQuery, ConnectionClass.ConnectionString)
dbAdapter.Fill(ds)
End Using
xControl.DataBindings.Clear() 'HERE
Dim dvm As DataViewManager = New DataViewManager(ds)
Dim iDataList As DataView = dvm.CreateDataView(ds.Tables(0))
For Each iBind As Binding In xControl.DataBindings
xControl.DataBindings.Remove(iBind)
Next
xControl.DataBindings.Add("EditValue", iDataList, xPrimaryKey)
xControl.Properties.DataSource = iDataList
xControl.EditValue = Nothing
txtStatus.Text = "Ready"
End Using
End If
Dim index As Integer = 0
opnieuw:
For Each F In openbestand.file
If F.Contains("~$") Then
openbestand.file.Remove(openbestand.file(index))
openbestand.path.Remove(openbestand.path(index))
GoTo opnieuw
Else
index = (index + 1)
End If
Next
If you are going to use a loop, you need to ensure that the index is less than the Count, since the count decreases every time a key element is removed:
Dim i As Integer
For i = 0 To dictionary1.Count - 1
If i <= dictionary1.Count - 1 Then
Dim sKey = dictionary1.ElementAt(i).Key
dictionary1.Remove(sKey)
End If
Next