VB: Problems with using variable from another class + what to do with not used interface`s functions - vb.net

I have a problem with getting variable from another class and cannot understand what to do with interface`s functions which have already existed in another class.
What I have:
Form where clicking on a button I should see reversed string:
(I want to call pooraja.StringReverse which is below)
Private Sub btnPoora1_Click(sender As System.Object, e As System.EventArgs) _
Handles btnPoora1.Click
'Dim text As PrjTekstiPooraja.ITeisendused = New PrjTekstiPooraja.CtekstiPooraja
Dim text As PrjTekstiPooraja.ITeisendused = New PrjTekstiPooraja.CtekstiPooraja
Dim pooraja As PrjTekstiPooraja.ITeisendused = New PrjTekstiPooraja.CAlgrotimilinePooraja
text.strText = txtSisendTekst.Text
txtValjundTekst1.Text = pooraja.stringReverse
text.intStart = 1
text.intEnd = Len(txtSisendTekst.Text)
ascFSymbol.Text = text.ascFirstSymbol
ascLSymbol.Text = text.ascLastSymbol()
End Sub
CtekstiPooraja:
(Thiss class will be used to store data.Under data I mean strPooratavText. Data will be used in CAlgoritmilinePooraja)
Public Class CtekstiPooraja
Implements ITeisendused
Public intStartSymbol As Integer
Public intEndSymbol As Integer
Public strPooratavText As String
Private Property intEnd As Integer Implements ITeisendused.intEnd
Get
Return intEndSymbol
End Get
Set(ByVal value As Integer)
intEndSymbol = value
End Set
End Property
Private Property intStart As Integer Implements ITeisendused.intStart
Get
Return intStartSymbol
End Get
Set(ByVal value As Integer)
intStartSymbol = value
End Set
End Property
Public Function pooraText() As String Implements ITeisendused.pooraText
Return StrReverse(strPooratavText)
End Function
Public Property strText As String Implements ITeisendused.strText
Get
Return strPooratavText
End Get
Set(ByVal value As String)
strPooratavText = value
MsgBox(strPooratavText)
End Set
End Property
Public Sub teisendaText(ByRef strSisendText As String) Implements ITeisendused.teisendaText
strPooratavText = StrReverse(strSisendText)
End Sub
Public Function ascFirstSymbol() As String Implements ITeisendused.ascFirstSymbol
Return Asc(GetChar(strPooratavText, intStartSymbol))
End Function
Public Function ascLastSymbol() As String Implements ITeisendused.ascLastSymbol
Return Asc(GetChar(strPooratavText, intEndSymbol))
End Function
Public Function stringReverse() As String Implements ITeisendused.stringReverse
Return Nothing
End Function
End Class
CAlgrotimilinePooraja:
(This class will be called by form button. There I need to use stringReverse function with data from CtekstiPooraja. The problem is that everywhere is used the same interface and there is some functions and procedures from this interface which isnt necessary. I dont know what value should return these unused functions/procedures. Just using "return Nothing or return 0/ "" is bad idea, may be there is possible somehow referenceto to CTekstiPooraja functions/procedures variables")
Public Class CAlgrotimilinePooraja
Implements ITeisendused
Private x As New PrjTekstiPooraja.CtekstiPooraja
Public Function stringReverse() As String Implements ITeisendused.stringReverse
MsgBox(x.strPooratavText)
Dim i As Integer = 0
Dim j As Integer
Dim characters(j) As Char
Dim newString(j) As Char
characters = x.strPooratavText.ToCharArray()
newString = x.strPooratavText.ToCharArray()
Do While i <= j - 1
newString(i) = characters(j - 1)
newString(j - 1) = characters(i)
i += 1
j -= 1
Loop
Return newString
End Function
Public Function ascFirstSymbol() As String Implements ITeisendused.ascFirstSymbol
Return x.ascFirstSymbol()
End Function
Public Function ascLastSymbol() As String Implements ITeisendused.ascLastSymbol
Return Nothing
End Function
Public Property intEnd As Integer Implements ITeisendused.intEnd
Get
Return x.intEndSymbol
End Get
Set(ByVal value As Integer)
End Set
End Property
Public Property intStart As Integer Implements ITeisendused.intStart
Get
Return x.intStartSymbol
End Get
Set(ByVal value As Integer)
End Set
End Property
Public Function pooraText() As String Implements ITeisendused.pooraText
Return x.pooraText()
End Function
Public Property strText As String Implements ITeisendused.strText
Get
Return x.strPooratavText
End Get
Set(ByVal value As String)
End Set
End Property
Public Sub teisendaText(ByRef strSisendText As String) Implements ITeisendused.teisendaText
x.strPooratavText = StrReverse(strSisendText)
End Sub
End Class
MyInterface:
Public Interface ITeisendused
Property intStart As Integer
Property intEnd As Integer
Property strText As String
Function pooraText() As String
Function ascFirstSymbol() As String
Function ascLastSymbol() As String
Function stringReverse() As String
Sub teisendaText(ByRef strSisendText As String)
End Interface
I cannot understand how to get variable strPooratavText from CTekstiPooraja to CAlgrotimilinePooraja. Usually that instancewhich I create worked but not now. And I cannot understand what to do with already existed function and procedures in CAlgoritmilinePooraja when the same function and procedures has in another class. Maybe, it is possible to reference them somehow to existed functions/procedures in CTekstiPooraja? Could you explain me how to id, already tired to surf Internet to find a solution for it, have already try a lot.

Well, I think you have a fundamental problem with understanding interfaces. They describe data and behavior, it should be extremely rare to want to implement part of an interface.
That said, if you do want to implement part of an interface, instead of returning bogus data, throw an exception for behavior you don't implement.
Your specific problem is that CAlgoritmilinePooraja works on an instance of CtekstiPooraja, but it creates a new instance instead of using an existing one. Add
Sub New(incomingX as CtekstiPooraja)
x = incomingX
End Sub
to CAlgoritmilinePooraja. And then in your event, use....
Dim text As PrjTekstiPooraja.CtekstiPooraja = New PrjTekstiPooraja.CtekstiPooraja
text.strText = txtSisendTekst.Text
Dim pooraja As PrjTekstiPooraja.ITeisendused = New PrjTekstiPooraja.CAlgrotimilinePooraja(text)
That is the minimum change to your design that gets what you want to happen to happen but it's problably not what you should do. Other than implementing strReverse, CtekstiPooraja seems to be what you want, CAlgrotimilinePooraja looks to do just one thing, the actual string reversal.
I would move the implementation of strReverse into CtekstiPooraja, and then eliminate CAlgrotimilinePooraja.
PS I would try to stick to English for class names as well as functions and variables.

Related

Adding member to list overides previous members

I need to read from an Excel file a list of dogs with their birth date, and store them in a list. The read works well, and every time I add a new dog to the list, the list count grows. So far so good.
The problem is that when I add the 2nd record, the first record is replaced by the first record content, so I have two identical records. And so on with every new record. In the end, I have many same records - all with the value of the last dog.
The dog class is:
Public Class DogClass
Public Name As String
Public Dob As Date
Public Age As Integer
Public Sex As String
Public Sub setDogName(ByVal _name As String)
Name = _name
End Sub
Public Sub setDogDOB(ByVal _dob As Date)
Dob = _dob
End Sub
Public Sub setDogAge(ByVal _age As String)
Age = _age
End Sub
Public Sub setDogSex(ByVal _sex As String)
Sex = _sex
End Sub
End Class
The class of the list is:
Public Class DogsListClass
Public dogsList As New List(Of DogClass)
Public Function DodgsCnt() As Integer
DodgsCnt = dogsList.Count()
End Function
Public Function DogExsists(_dogName As String) As Boolean
Dim res As Boolean = False
For Each item As DogClass In dogsList
If item.Name = _dogName Then
res = True
End If
Next
Return res
End Function
Public Sub AddDog(_dog As DogClass)
dogsList.Add(_dog)
End Sub
End Class
The calling:
Dim tdog As New DogClass
Dim DogsList As New DogsListClass
Do
tdog.setDogName(MyExcel.Cells(row_cnt, col_cnt).text)
tdog.setDogDOB(MyExcel.Cells(row_cnt, col_cnt + 1).value)
DogsList.AddDog(tdog)
Loop
Any idea why the records are being overridden?
DogsList variable must be declared outside the Do...Loop, otherwise you are creating a "New" DogsList at each iteration and, based on this code, you should end up having one single item in the collection, not many.
Also, declaring DogsList in the loop, prevents you from using it outside in the rest of your code.

Why is this returning Index out of bound exception

When I get to the Read loop I get an index out of bounds error. I think its on the reader ordinal value, but I am not sure why I am getting it.
Private Function Create(Reader As SqlDataReader) As IEnumerable(Of MyObject)
SetOrdinals(MyObjectReader)
Dim MyObjects = New List(Of MyObject)
While MyObjectReader.Read()
Dim Temp = New MyObject() With {
.FirstValue = MyObjectReader.GetValue(Of Integer)(MyObjectReader(FirstValue_Ord)),
.SecondValue = If(MyObjectReader.GetValue(Of String)(MyObjectReader(SecondValue_Ord)), String.Empty).Trim(),
.ThirdValue = If(MyObjectReader.GetValue(Of String)(MyObjectReader(ThirdValue_Ord)), String.Empty).Trim(),
MyObjects.Add(Temp)
End While
Return MyObjects
End Function
Private Sub SetOrdinals(MyObjectReader As SqlDataReader)
FirstValueOrd = MyObjectReader.GetOrdinal("FirstValue")
SecondValue_Ord = MyObjectReader.GetOrdinal("SecondValue")
ThirdValue_Ord = MyObjectReader.GetOrdinal("ThirdValue")
End Sub
End Class
Public Module Extensions
<Extension>
Function GetValue(Of T)(rdr As SqlDataReader, i As Integer) As T
If rdr.IsDBNull(i) Then
Return Nothing
End If
Return DirectCast(rdr.GetValue(i), T)
End Function
End Module
You should just be passing in the ordinal to the GetValue calls:
While MyObjectReader.Read()
Dim Temp = New MyObject() With {
.FirstValue = MyObjectReader.GetValue(Of Integer)(FirstValue_Ord),
.SecondValue = If(MyObjectReader.GetValue(Of String)(SecondValue_Ord), String.Empty).Trim(),
.ThirdValue = If(MyObjectReader.GetValue(Of String)(ThirdValue_Ord), String.Empty).Trim()
}
MyObjects.Add(Temp)
End While
Here my version :)
Private Function Create(reader As SqlDataReader) As IEnumerable(Of MyObject)
Dim objects As New List(Of MyObject)()
Dim ordinals As New Ordinals(reader)
While reader.Read()
Dim Temp As New MyObject With
{
.FirstValue = reader.GetValueOrDefault(Of Integer)(ordinals.FirstValue),
.SecondValue = reader.GetValueOrDefault(ordinals.SecondValue, "").Trim(),
.ThirdValue = reader.GetValueOrDefault(ordinals.ThirdValue, "").Trim()
}
objects.Add(Temp)
End While
Return MyObjects
End Function
Private Class Ordinals
Public Property FirstValue As Integer
Public Property SecondValue As Integer
Public Property ThirdValue As Integer
Public Sub New(reader As SqlDataReader)
FirstValue = reader.GetOrdinal(nameOf(FirstValue))
SecondValue = reader.GetOrdinal(nameOf(SecondValue))
ThirdValue = reader.GetOrdinal(nameOf(ThirdValue))
End Sub
End Class
Public Module Extensions
<Extension>
Function GetValueOrDefault(Of T)(reader As SqlDataReader, ordinal As Integer) As T
Return reader.GetValueOrDefault(Of T)(ordinal, Nothing)
End Function
<Extension>
Function GetValueOrDefault(Of T)(reader As SqlDataReader,
ordinal As Integer,
defaultValue As T) As T
Dim value = reader(ordinal)
If value = DbNull.Value Then
Return defaultValue
End If
Return DirectCast(value, T)
End Function
End Module
Because extension method execute checking for DbNull.Value against already extracted object, we get rid from reading same value twice from SqlDataReader.
SqlDataReader.IsDbNull(index) reads value before checking for DbNull.
Extension method have two overloads:
- One which return default value of given type, if value is DbNull.Value. Nothing in vb.net is default value of type.
- And one which takes parameter for default value you want return if value is DbNull.Value. Possibility pass default value makes lines where you create new object shorter and more readable. We get rid of inline if statement.
Your extension method with name GetValue have "side effects". By name consumer of this method expect to get value from SqlDataReader. So he can expect to get DbNull.Value if database query return NULL, but instead he get null for string or 0 for integer. Name GetValueOrDefault is little bid more informative, so you don't need to go inside method to check what is doing.

How I can proceed each member of lambda expression with a Function that return value using delegate?

I use Vb.net in my work. I find a difficulty when trying to delegate a Function that returns value into each member of lambda expression.
I can do if for each member of lambda is delegated into a Sub:
Public class TransactionX
Public Number1 as Integer
Public Number2 as Integer
end class
Public Class TestX
Public Sub DoTest()
Dim trans as New List(Of TransactionX)
trans.Add(New TransactionX with{.Number1=0, .Number2=0})
trans.Add(New TransacrtionX with{.Number1=1, .Number2=1})
dim changeNumber = New Action(Of TransactionX)(AddressOf DoChange)
dim transSearch = trans.Where(Function(t) t.Number1>0).ForEach(changeNumber)
end Sub
Private Sub DoChange(ByVal tranX as TransactionX)
with tranx
.Number1 = 10
.Number2 = 10
end with
end Sub
end Class
above code will update each member of lambda expression's result.
What if I want to do Number1 * Number2 for each member that I catch from Lambda with a private Function and then will return into a collection?
I think it can be done with C# but I could not solve it using Vb.net.
Change you method to return calculated value and use it with Select extension method
Private Function DoChange(ByVal tranX As TransactionX) As Integer
Return tranX.Number1 * tranX.Number2
End Function
Dim transSearch As IEnumerable(Of Integer) = trans.Select(AddressOf DoChange)
Use AddressOf keyword for passing existed method as parameter

Passing Enum Array or list to Function

I want to compare an enum array to single enum instance.
Introduction
I have a class with an enum type array\list
Public Enum InvalidEmailType
Multiple_Updates
Period_Before_At_Sign
Missing_Dot_Com
End Enum
Public Class CustomerClass
Public CustomerName As String
Public ErrorTypeList = [Enum].GetValues(GetType(InvalidEmailType))
Public ErrorDescription As String
End Class
Depending on what values are added to the list, I want to run specific code.
In order to do this I compare the entire list to a single instance:
If UpdateCustomer.MatchErrorType(customer.ErrorTypeList, InvalidEmailType.Trailing_Period) = True Then
'Run Code
End If
Inside the function I compare the entire list against the single instance.
In other words, I loop through the entire list inside the class and check if the value is there:
Public Shared Function MatchErrorType(CustomerErrortypeList As List(Of InvalidEmailType), EmailError As InvalidEmailType) As Boolean
MatchErrorType = False
Dim Found As InvalidEmailType = CustomerErrortypeList.Where(Function(match) match.ToString = EmailError.ToString).OrderByDescending(Function(match) match.ToString).FirstOrDefault()
If Found > 0 Then
MatchErrorType = True
End If
End Function
Here is the problem:
How do I declare the array\list in the function parameters?
List(Of InvalidEmailType) does not work, as I get a cast error
Unable to cast object of type 'EmailValidationReport.InvalidEmailType[]' to type 'System.Collections.Generic.List`1[EmailValidationReport.InvalidEmailType]'
Set ErrorTypeList to a List(of InvalidEmailType) instead of array.
Public ErrorTypeList = [Enum].GetValues(GetType(InvalidEmailType)) _
.Cast(of InvalidEmailType)().ToList()
or
Dim list = customer.ErrorTypeList.Cast(of InvalidEmailType)().ToList()
If UpdateCustomer.MatchErrorType(list, InvalidEmailType.Trailing_Period) Then
'Run Code
End If
Since you aren't doing anything that is specific to List or Array, you can make your method signature take in an IEnumerable instead of a List. This should be able to handle both List and Array (and a few more types as well).
Public Shared Function MatchErrorType(CustomerErrortypeList As IEnumerable(Of InvalidEmailType), EmailError As InvalidEmailType) As Boolean
Dim Found As InvalidEmailType = CustomerErrortypeList.Where(Function(match) match.ToString = EmailError.ToString).OrderByDescending(Function(match) match.ToString).FirstOrDefault()
MatchErrorType = (Found > 0)
End Function

Deserialize complex JSON (VB.NET)

I'm trying to deserialize json returned by some directions API similar to Google Maps API. My JSON is as follows (I'm using VB.NET 2008):
jsontext =
{
"version":0.3,
"status":0,
"route_summary":
{
"total_distance":300,
"total_time":14,
"start_point":"43",
"end_point":"42"
},
"route_geometry":[[51.025421,18.647631],[51.026131,18.6471],[51.027802,18.645639]],
"route_instructions": [["Head northwest on 43",88,0,4,"88 m","NW",334.8],["Continue on 42",212,1,10,"0.2 km","NW",331.1,"C",356.3]]
}
So far I came up with the following code:
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim lstTextAreas As Output_CloudMade() = js.Deserialize(Of Output_CloudMade())(jsontext)
I'm not sure how to define complex class, i.e. Output_CloudMade.
I'm trying something like:
Public Class RouteSummary
Private mTotalDist As Long
Private mTotalTime As Long
Private mStartPoint As String
Private mEndPoint As String
Public Property TotalDist() As Long
Get
Return mTotalDist
End Get
Set(ByVal value As Long)
mTotalDist = value
End Set
End Property
Public Property TotalTime() As Long
Get
Return mTotalTime
End Get
Set(ByVal value As Long)
mTotalTime = value
End Set
End Property
Public Property StartPoint() As String
Get
Return mStartPoint
End Get
Set(ByVal value As String)
mStartPoint = value
End Set
End Property
Public Property EndPoint() As String
Get
Return mEndPoint
End Get
Set(ByVal value As String)
mEndPoint = value
End Set
End Property
End Class
Public Class Output_CloudMade
Private mVersion As Double
Private mStatus As Long
Private mRSummary As RouteSummary
'Private mRGeometry As RouteGeometry
'Private mRInstructions As RouteInstructions
Public Property Version() As Double
Get
Return mVersion
End Get
Set(ByVal value As Double)
mVersion = value
End Set
End Property
Public Property Status() As Long
Get
Return mStatus
End Get
Set(ByVal value As Long)
mStatus = value
End Set
End Property
Public Property Summary() As RouteSummary
Get
Return mRSummary
End Get
Set(ByVal value As RouteSummary)
mRSummary = value
End Set
End Property
'Public Property Geometry() As String
' Get
' End Get
' Set(ByVal value As String)
' End Set
'End Property
'Public Property Instructions() As String
' Get
' End Get
' Set(ByVal value As String)
' End Set
'End Property
End Class
but it does not work. The problem is with complex properties, like route_summary. It is filled with "nothing". Other properties, like "status" or "version" are filled properly.
Any ideas, how to define class for the above JSON?
Can you share some working code for deserializing JSON in VB.NET?
Thanks,
Below is a sample Converter class that will take an incoming stream of JSON and convert to to an object you specify. I should note the below code is .Net 4.0. The JSON serializer in 4 is much easier to use. Let me know if you can't use 4 and I'll see if I can dig up a 3.5 version. Basically you need to create a class structure to map the JSON to a Class. I created the Route and RouteSummary classes for you. I left route_geometry and route_instructions as objects. You should create class definitions for each but this should get you started.
Imports System.IO
Imports System.Runtime.Serialization.Json
Imports System.Runtime.Serialization
<DataContract(Namespace:="")> _
Public Class Route
<DataMember(Name:="version")>
Public Property version As Double
<DataMember(Name:="status")>
Public Property status As Double
<DataMember(Name:="route_summary")>
Public Property route_summary As route_summary
<DataMember(Name:="route_geometry")>
Public Property route_geometry As Object()
<DataMember(Name:="route_instructions")>
Public Property route_instructions() As Object
End Class
<DataContract(Name:="route_summary", Namespace:="")> _
Public Class route_summary
<DataMember(Name:="total_distance")>
Public Property total_distance As Double
<DataMember(Name:="total_time")>
Public Property total_time As Double
<DataMember(Name:="start_point")>
Public Property start_point As Double
<DataMember(Name:="end_point")>
Public Property end_point As Double
End Class
Public Class Converter(Of t)
Public Function ReturnJSON(ByRef sreader As StreamReader) As t
If GetType(t).Equals(GetType(String)) Then
Dim result As Object = sreader.ReadToEnd.Replace("""", "")
Return result
Else
Dim ds As New DataContractJsonSerializer(GetType(t))
Dim result As t = DirectCast(ds.ReadObject(sreader.BaseStream), t)
ds = Nothing
Return result
End If
End Function
End Class
Sub Main()
Dim json As String = "{""version"":0.3, ""status"":0, ""route_summary"": { ""total_distance"":300, ""total_time"":14, ""start_point"":""43"", ""end_point"":""42"" }, ""route_geometry"":[[51.025421,18.647631],[51.026131,18.6471],[51.027802,18.645639]], ""route_instructions"": [[""Head northwest on 43"",88,0,4,""88 m"",""NW"",334.8],[""Continue on 42"",212,1,10,""0.2 km"",""NW"",331.1,""C"",356.3]]}"
Dim encoding As New System.Text.UTF8Encoding
Dim bytes() As Byte = encoding.GetBytes(json)
Using os As New MemoryStream
os.Write(bytes, 0, bytes.Length)
os.Position = 0
Using reader As New StreamReader(os)
Dim converter As New Converter(Of Route)
Dim output As Route
output = converter.ReturnJSON(reader)
'output contains data
End Using
End Using
End Sub
See this page for a detailed description of how to read the JSON data. http://www.json.org/