checking datatype in an overload doesn't work for decimal - vb.net

I'm using vb.net. I am doing some checking and scrubbing of my data when i get it from the database. I'm using an overload but it doesn't seem to be working for decimal numbers. Decimal numbers get treated as integers.
Public Class CheckData
Public Shared Function Check(row As DataRow, columnName As String, pDefaultValue As Decimal) As Decimal
Dim x As Object = ReplaceDBNullAndColumnExists(row, columnName)
Dim y As Decimal = CDec(Dempsey.fnIsNull.IsNull(x, pDefaultValue))
Return y
End Function
Public Shared Function Check(row As DataRow, columnName As String, pDefaultValue As DateTime) As DateTime
Dim x As Object = ReplaceDBNullAndColumnExists(row, columnName)
Dim y As DateTime = Dempsey.fnIsNull.IsNull(x, pDefaultValue)
Return y
End Function
Public Shared Function Check(row As DataRow, columnName As String, pDefaultValue As Integer) As Integer
Dim x As Object = ReplaceDBNullAndColumnExists(row, columnName)
Dim y As Integer = Dempsey.fnIsNull.IsNull(x, pDefaultValue)
Return y
End Function
Public Shared Function Check(row As DataRow, columnName As String, pDefaultValue As String) As String
Dim x As Object = ReplaceDBNullAndColumnExists(row, columnName)
Dim y As String = Dempsey.fnIsNull.IsNull(x, pDefaultValue)
Return y
End Function
Public Shared Function Check(row As DataRow, columnName As String, pDefaultValue As Boolean) As Boolean
Dim x As Object = ReplaceDBNullAndColumnExists(row, columnName)
Dim y As Boolean = Dempsey.fnIsNull.IsNull(x, pDefaultValue)
Return y
End Function
So if i pass in some data and the type is a string, integer, boolean or datetime it goes to the propert function. if i pass in a decimal it goes to integer. If i set a breakpoint on the public shared function check that is a integer function and do a
row.Table.Columns(columnName).DataType.Name
I get back - "Decimal" (doing this in the immediate window)
So my question is what have i done wrong that it doesn't take it to the decimal overload and return a decimal value. By the way, the actual data value is 37.50.
Thanks
shannon
I use this to populate list.
Public Function populate(mDs As DataSet) As List(Of SR_SalaryRange_Current)
Dim rows As DataRowCollection
Dim drow As DataRow
Dim oSR_SalaryRange_Current As SR_SalaryRange_Current
Dim oSR_SalaryRange_Currents As List(Of SR_SalaryRange_Current) = New List(Of SR_SalaryRange_Current)
Dim dt As New DataTable
Try
dt = mDs.Tables("SR_SalaryRange_Currents")
rows = dt.Rows
For Each drow In rows
oSR_SalaryRange_Current = New SR_SalaryRange_Current
With oSR_SalaryRange_Current
.tblSR_SalaryRange_CurrentID = SitePlumbing.CheckData.Check(drow, "intTblSR_SalaryRange_CurrentID", 0)
.EffectiveDate = SitePlumbing.CheckData.Check(drow, "dtmEffectiveDate", CDate("1/1/1900"))
.WorkWeekHours = SitePlumbing.CheckData.Check(drow, "decWorkWeekHours", 0)
End With
oSR_SalaryRange_Currents.Add(oSR_SalaryRange_Current)
Next
Catch ex As Exception
ErrorMsg = "Populate Error:" & ex.InnerException.ToString
Return oSR_SalaryRange_Currents
End Try
Return oSR_SalaryRange_Currents
End Function
from there it goes into the checkdata that i mentioned before. In the code above it correctly goes to an integer and a datetime when hitting the overload, just isn't doing it for the decimal.

A decimal is implicitly covertable into an integer so the compiler is confused if you have OPTION STRICT set to off. You have two options:
1) Set OPTION STRICT to ON. Then the compiler will not convert implicitly.
2) Pass in a decimal literal like this: 10D (i.e. there is a D on the end telling the compiler it is a decimal).
For example:
'Sub Routine 1
public sub Test(ByVal d as decimal)
end sub
'Sub Routine 2
public sub Test(ByVal i as integer)
end sub
//Client
dim d1 as decimal={Number}D 'where {number} is replaced with a number
dim d2 as decimal={Number} 'where {number} is replaced with a number
Test(d1) 'this will always go to Sub Routine 1 regardless of whether OPTION strict is ON or OFF
Test(d2) 'this will go to Sub Routine 1 if option strict is ON. If it is OFF, then it may go to Sub Routine 2 depending on the size of the number.

I was given a way to work with this by Viorel on another forum. He suggested I do
Check(drow, "decWorkWeekHours", 0#)
and that did indeed work. When i asked what it does, this was his response.
With ‘#’, the constant ‘0#’ becomes a decimal one. Then VB.NET chooses the definition of Check that takes a Decimal parameter, since it is more suitable comparing with other candidates.
You can also write ‘0d’ [https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/data-types/type-characters].
hope that will help someone else down the road.
Thanks
shannon

Related

Return value gets assigned but always returns as 0

I'm trying to calculate the total count and value of orders for a customer, using the code below.
Dim iOrderCount As Integer
Dim iLineCount As Integer
Dim cTotalGoods As Decimal
Dim cTotalVat As Decimal
Dim cTotalDelivery As Decimal
Using manOrders As New CManOrders(m_dbSql)
manOrders.GetOrdersInProgress(sAccountCode, iOrderCount, iLineCount, cTotalGoods, cTotalVat, cTotalDelivery)
When I assign values to these variables in the GetOrdersInProgress subroutine, the values are being assigned correctly, which I can see when I step through the code.
Public Sub GetOrdersInProgress(sAccountCode As String, ByRef RET_orderCount As Integer, ByRef RET_lineCount As Integer,
ByRef RET_totalGoods As Decimal, ByRef RET_totalVat As Decimal, RET_totalDelivery As Decimal)
...
For Each dr As DataRow In m_dbSql.getDataTable(sql).Rows
RET_orderCount = dbToInt(dr(ORDER_COUNT))
RET_lineCount = dbToInt(dr(LINE_COUNT))
RET_totalGoods = dbToDecimal(dr(TOTAL_GOODS))
RET_totalVat = dbToDecimal(dr(TOTAL_VAT))
RET_totalDelivery = dbToDecimal(dr(2))
Return
Next
However, once I step through and move back into where the GetOrdersInProgress subroutine is called from, all of the values in the variables are returned correctly, except for RET_totalDelivery - the new one I've added to another developer's project.
The value in the RET_totalDelivery variable in the Public Sub GetOrdersInProgress... line is correct and it's correct after the assignment, but when it reaches Return and the variables are then used in the parent subroutine, for some reason they're all correct except for the new one I've added, RET_totalDelivery. I'd understand if the value wasn't being assigned correctly, however it is.
Why would it be returning 0 all the time?
By default, arguments passed to vb.net methods are passed by value, or ByVal. You did not specify ByRef in your RET_totalDelivery argument in GetOrdersInProgress.
Changes made to arguments passed by value are not retained when the method ends.
Your Sub should now be...
Public Sub GetOrdersInProgress(sAccountCode As String, ByRef RET_orderCount As Integer, ByRef RET_lineCount As Integer, ByRef RET_totalGoods As Decimal, ByRef RET_totalVat As Decimal, ByRef RET_totalDelivery As Decimal)
I prefer to write the method as a function. Write a class to hold all the return values. Then change the method into a function with just input parameters and return the values you fetch from sql.
Sub Main
Dim bl = New OrdersInProgressBusinessLogic()
Dim ordersInProgress = bl.GetOrdersInProgress("some account code")
End Sub
Public Class OrdersInProgress
Public Property OrderCount As Integer
Public Property LineCount As Integer
Public Property TotalGoods As Decimal
Public Property TotalVat As Decimal
Public Property TotalDelivery As Decimal
End Class
Public Class OrdersInProgressBusinessLogic
Public Function GetOrdersInProgress(sAccountCode As String) As OrdersInProgress
Dim ordersInProgress = New OrdersInProgress()
' some code here to fetch data from sql
For Each dr As DataRow In m_dbSql.getDataTable(sql).Rows
With ordersInProgress
.OrderCount = dbToInt(dr(ORDER_COUNT))
.LineCount = dbToInt(dr(LINE_COUNT))
.TotalGoods = dbToDecimal(dr(TOTAL_GOODS))
.TotalVat = dbToDecimal(dr(TOTAL_VAT))
.TotalDelivery = dbToDecimal(dr(2))
End With
Next
Return ordersInProgress
End Function
' some other functions/subs for OrdersInProgress class
End Class

Custom date sort

I have a list of date values
10/06/2017, 4/20/12, 7/13/12, 08.02.12, 04.05.13, 11.27.12
that needs to be sorted into correct chronological order.
The format from the original data entry was not controlled and therefore is variable. Date seperators, thus far, have shown to be '.' and '/'. The number of digits in each date segment are not consistent.
This list represents a single column of data in a table. The data is read from varying sources and can be put into any structure that will facilitate the sort. The date must sort the entire table.
The data must remain as originally entered so I cannot simply convert the data and be done with it.
Here's a function and overload which will work with either a string as you provided, or a list of strings:
Private Function getSortedDates(input As String) As IEnumerable(Of DateTime)
Return getSortedDates(input.Split({","c}, StringSplitOptions.RemoveEmptyEntries))
End Function
Private Function getSortedDates(input As IEnumerable(Of String)) As IEnumerable(Of DateTime)
Return input.
Select(Function(s As String) DateTime.Parse(s.Replace(".", "/"))).
OrderBy(Function(d) d)
End Function
Usage:
Sub Main()
' as a string
Dim input1 = "10/06/2017, 4/20/12, 7/13/12, 08.02.12, 04.05.13, 11.27.12"
Dim output1 = getSortedDates(input1)
' as an array
Dim input2 = {"10/06/2017", "4/20/12", "7/13/12", "08.02.12", "04.05.13", "11.27.12"}
Dim output2 = getSortedDates(input2)
' output1 and output2 have the same sorted dates.
End Sub
You can build a custom Comparer that can be used in sorting
Module Module1
Sub Main()
Dim dates() As String = {"10/06/2017", "4/20/12", "7/13/12", "08.02.12", "04.05.13", "11.27.12"}
Array.Sort(dates, New StringDateSorter)
For Each d In dates
Console.WriteLine(d)
Next
End Sub
End Module
Class StringDateSorter
Implements IComparer(Of String)
Public Function Compare(x As String, y As String) As Integer Implements IComparer(Of String).Compare
Dim d1 = Date.Parse(x)
Dim d2 = Date.Parse(y)
Return Date.Compare(d1, d2)
End Function
End Class

VB.NET Boxing weirdness

I can't understand what is happening with the following code in VB.NET. When I run this code:
Public Function test() As Boolean
Dim a As Integer = 1
Dim b As Object = a
Dim c As Object = b
Return Object.ReferenceEquals(b, c)
End Function
Then the function returns True. However, if I run this:
Structure TTest
Dim i As Integer
Dim tid As Integer
Sub New(ByVal _i As Integer, ByVal _tid As Integer)
i = _i
tid = _tid
End Sub
End Structure
Public Function test_2() As Boolean
Dim a As New TTest(1, 1)
Dim b As Object = a
Dim c As Object = b
Return Object.ReferenceEquals(b, c)
End Function
Then it returns False. In both functions, I declare two value type variables, an Integer on the first and a custom Structure on the second one. Both should be boxed upon object assignment, but in the second example, it seems to get boxed into two different objects, so Object.ReferenceEquals returns False.
Why does it work this way?
For primitive types, .Net is able to re-use the same "box" for the same values, and thus improve performance by reducing allocations.
Same with strings, it's .NET way to optimize thing. But as soon as you use it, the reference will change.
Sub Main()
Dim a As String = "abc"
Dim b As String = "abc"
Console.WriteLine(Object.ReferenceEquals(a, b)) ' True
b = "123"
Console.WriteLine(Object.ReferenceEquals(a, b)) ' False
Console.ReadLine()
End Sub

Vb.Net 2D Dictionary - very slow

I need to create a 2D dictionary/keyvalue pair.
I tried something like this.
Dim TwoDimData As New Dictionary(Of String, Dictionary(Of String, String))
'Create an empty table
For Each aid In AIDList '(contains 15000 elements)
TwoDimData.Add(aid, New Dictionary(Of String, String))
For Each bid In BIDList 'contains 30 elements
TwoDimData.Item(aid).Add(bid, "")
Next
Next
'Later populate values.
[some code here to populate the table]
'Now access the value
'The idea is to access the info as given below (access by row name & col name)
Msgbox TwoDimData.Item("A004").Item("B005") ' should give the value of 2
Msgbox TwoDimData.Item("A008").Item("B002") ' should return empty string. No error
Issue:
The issue is in Creating the empty table. It takes 70 seconds to create the TwoDimData table with empty values. Everything else seems to be fine. Is there any way to improve the performance - may be instead of using Dictionary?
I suggest you try Dictionary(Of Tuple(Of String, String), String) instead. That is, the keys are pairs of strings (Tuple(Of String, String)) and the values are strings. That would appear to correspond nicely to the diagram in your question.
Dim matrix As New Dictionary(Of Tuple(Of String, String), String)
' Add a value to the matrix:
matrix.Add(Tuple.Create("A003", "B004"), "3")
' Retrieve a value from the matrix:
Dim valueAtA003B004 = matrix(Tuple.Create("A003", "B004"))
Of course you can define your own key type (representing a combination of two strings) if Tuple(Of String, String) seems too generic for your taste.
Alternatively, you could also just use (possibly jagged) 2D arrays, but that would potentially waste a lot of space if your data is sparse (i.e. if there are many empty cells in that 2D matrix); and you'd be forced to use numeric indices instead of strings.
P.S.: Actually, consider changing the dictionary value type from String to Integer; your example matrix suggests that it contains only integer numbers, so it might not make sense to store them as strings.
P.P.S.: Do not add values for the "empty" cells to the dictionary. That would be very wasteful. Instead, instead of simply retrieving a value from the dictionary, you check whether the dictionary contains the key:
Dim valueA As String = "" ' the default value
If matrix.TryGetValue(Tuple.Create("A007", "B002"), valueA) Then
' the given key was present, and the associated value has been retrieved
…
End If
I would think that a simple structure would suffice for this?
Public Structure My2DItem
Public Row As Integer
Public Col As Integer
Public Value As String
End Structure
Public My2DArray As Generic.List(Of My2DItem) = Nothing
Public Size As Integer
Public MaxRows As Integer
Public MaxCols As Integer
'
Sub Initialise2DArray()
'
Dim CountX As Integer
Dim CountY As Integer
Dim Item As My2DItem
'
'initialise
MaxRows = 15000
MaxCols = 30
Size = MaxRows * MaxCols
My2DArray = New Generic.List(Of My2DItem)
'
'Create an empty table
For CountY = 1 To 15000
For CountX = 1 To 30
Item = New My2DItem
Item.Row = CountY
Item.Col = CountX
Item.Value = "0"
My2DArray.Add(Item)
Item = Nothing
Next
Next
'
End Sub
And to read the data out of the array,
Function GetValue(Y As Integer, X As Integer) As String
'
Dim counter As Integer
'
GetValue = "Error!"
If My2DArray.Count > 0 Then
For counter = 0 To My2DArray.Count - 1
If My2DArray(counter).Row = Y Then
If My2DArray(counter).Col = X Then
GetValue = My2DArray(counter).Value
Exit Function
End If
End If
Next
End If
'
End Function
And to read your sample cell A004 B005
MyStringValue = GetValue(4,5)
I would suggest creating a class that has properties for the AID and BID and use this as the basis for the values you want to store
Public Class AIdBId
Public Property AId As Integer
Public Property BId As Integer
Public Sub New(aId As Integer, bId As Integer)
Me.AId = aid
Me.BId = bid
End Sub
End Class
Note that I have used integers for everything because it seems that is all you need and it is more efficient that using a string
Then you can add values where they are non-zero:
'define your dictionary
Dim valueMatrix As New Dictionary(Of AIdBId, Integer)
'add your values
valueMatrix.Add(New AIdBId(1, 1), 1)
valueMatrix.Add(New AIdBId(2, 3), 1)
valueMatrix.Add(New AIdBId(4, 3), 3)
valueMatrix.Add(New AIdBId(5, 8), 8)
'check if a value exixts
Dim valueExixsts As Boolean = valueMatrix.ContainsKey(New AIdBId(9, 9))
'get a value
Dim i As Integer = valueMatrix(New AIdBId(4, 3))
So you can now combine these two to return the value if there is one or zero if not:
Private Function GetValue(valuematrix As Dictionary(Of AIdBId, Integer), aId As Integer, bId As Integer) As Integer
Dim xRef As New AIdBId(aId, bId)
If valuematrix.ContainsKey(xRef) Then
Return valuematrix(xRef)
Else
Return 0
End If
End Function

VB Assignment of member field programmatically

This question is a follow-on to VB ReDim of member field programmatically. After the arrays are dimensioned appropriately, I try to set the values of the elements, but I get an exception at run time when I try to assign the first value (MySB.AssignValues(0, "B", 0, 7.6))
System.InvalidCastException was unhandled
HResult=-2147467262
Message=Object cannot be stored in an array of this type.
Source=mscorlib
Module TestSetArray
Public Class BS
Public A As String
Public B() As Double
Public C() As Double
End Class
Public Class SB
Public MyBS() As BS
'ReadFieldString is a function that returns a string of the field name of Class BS,
'i.e., A, B or C. For test purpose, retun a constant
Public Function ReadFieldString() As String
Return "B"
End Function
'GetArrayDim is a function that returns an integer, which is the size of the array
'of that field name. For test purpose, retun a constant
Public Function GetArrayDim() As Integer
Return 2
End Function
Public Sub DimArrays()
ReDim MyBS(3)
Dim i As Integer
For i = 0 To MyBS.Length - 1
MyBS(i) = New BS()
Dim f = GetType(BS).GetField(ReadFieldString())
f.SetValue(MyBS(i), Array.CreateInstance(f.FieldType.GetElementType(), GetArrayDim()))
Next
End Sub
Public Sub AssignValues(MainIndex As Integer, TheName As String, TheIndex As Integer, TheValue As Double)
Dim f = MyBS(MainIndex).GetType.GetMember(TheName)
f.SetValue(TheValue, TheIndex)
End Sub
End Class
Sub Main()
Dim MySB As SB = New SB
MySB.DimArrays()
MySB.AssignValues(0, "B", 0, 7.6)
MySB.AssignValues(0, "B", 1, 8.2)
End Sub
End Module
Thanks in advance.
The problem is that the GetMember method returns an array of type MemberInfo, not the double array of the class. You'd probably have an easier time if you used GetField instead. You have to call GetValue and cast its result to an Array in order to use SetValue to set the value.
Public Sub AssignValues(MainIndex As Integer, TheName As String, TheIndex As Integer, TheValue As Double)
Dim f = MyBS(MainIndex).GetType().GetField(TheName)
Dim doubleArray = DirectCast(f.GetValue(MyBS(MainIndex)), Array)
doubleArray.SetValue(TheValue, TheIndex)
End Sub
or if you know that the array will always be an array of Double, you can cast it directly to that:
Public Sub AssignValues(MainIndex As Integer, TheName As String, TheIndex As Integer, TheValue As Double)
Dim f = MyBS(MainIndex).GetType().GetField(TheName)
Dim doubleArray = DirectCast(f.GetValue(MyBS(MainIndex)), Double())
doubleArray(TheIndex) = TheValue
End Sub