passing by reference in VB.Net - vb.net

I posted a similar question before, which worked in C# (thanks to the community), but the actual problem was in VB.Net ( with option strict on). Problem is that tests are not passing.
Public Interface IEntity
Property Id() As Integer
End Interface
Public Class Container
Implements IEntity
Private _name As String
Private _id As Integer
Public Property Id() As Integer Implements IEntity.Id
Get
Return _id
End Get
Set(ByVal value As Integer)
_id = value
End Set
End Property
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
End Class
Public Class Command
Public Sub ApplyCommand(ByRef entity As IEntity)
Dim innerEntity As New Container With {.Name = "CommandContainer", .Id = 20}
entity = innerEntity
End Sub
End Class
<TestFixture()> _
Public Class DirectCastTest
<Test()> _
Public Sub Loosing_Value_On_DirectCast()
Dim entity As New Container With {.Name = "Container", .Id = 0}
Dim cmd As New Command
cmd.ApplyCommand(DirectCast(entity, IEntity))
Assert.AreEqual(entity.Id, 20)
Assert.AreEqual(entity.Name, "CommandContainer")
End Sub
End Class

The same is true in VB as in C#. By using the DirectCast, you're effectively creating a temporary local variable, which is then being passed by reference. That's an entirely separate local variable from the entity local variable.
This should work:
Public Sub Losing_Value_On_DirectCast()
Dim entity As New Container With {.Name = "Container", .Id = 0}
Dim cmd As New Command
Dim tmp As IEntity = entity
cmd.ApplyCommand(tmp)
entity = DirectCast(tmp, Container)
Assert.AreEqual(entity.Id, 20)
Assert.AreEqual(entity.Name, "CommandContainer")
End Sub
Of course it would be simpler just to make the function return the new entity as its return value...

Related

How to Deserialize JSON Array

there I am having difficulty deserializing a json array. The array is derived from the following classes
Public Class PIValues
Inherits List(Of PIValue)
Public Sub New()
End Sub
End Class
Public Class PIValue
Private _PointName As String
Private _value As Double
Private _timeStamp As String
Public Property PointName() As String
Get
PointName = _PointName
End Get
Set(value As String)
_PointName = value
End Set
End Property
Public Property TimeStamp() As String
Get
TimeStamp = _timeStamp
End Get
Set(value As String)
_timeStamp = value
End Set
End Property
Public Property Value() As Double
Get
Value = _value
End Get
Set(value As Double)
_value = value
End Set
End Property
End Class
The above is held as AssemblyName.PIValue and AssemblyName.PIValues which are part of the same solution
Implementation of this code within my unit tests results in the following json array held in the string result:
[{\"PointName\":\"MW Tag
1\",\"TimeStamp\":\"20200128073000\",\"Value\":-0.0015},{\"PointName\":\"MW Tag
2\",\"TimeStamp\":\"20200128073000\",\"Value\":-0.0031},{\"PointName\":\"MW Tag
3\",\"TimeStamp\":\"20200128073000\",\"Value\":-2.1485},{\"PointName\":\"MW Tag
4\",\"TimeStamp\":\"20200128073000\",\"Value\":0.0}]
I had expected to be able to use the newtonsoft library in the following way for deserialization:
Dim Items = Newtonsoft.Json.JsonConvert.DeserializeObject(Of PIValue())(result)
However this does not work. I am new to using the newtonsoft library, would appreciate any assistance
Kind Regards
Paul.
We can't know what you mean by "doesn't work," but this code runs without error and emits a JSON string identical to the one you've provided:
Public Module Main
Public Sub Main()
Dim oPIValues1 As PIValues
Dim oPIValues2 As PIValues
Dim sResult As String
oPIValues1 = New PIValues From {
New PIValue With {.PointName = "MW Tag 1", .TimeStamp = "20200128073000", .Value = -0.0015},
New PIValue With {.PointName = "MW Tag 2", .TimeStamp = "20200128073000", .Value = -0.0031},
New PIValue With {.PointName = "MW Tag 3", .TimeStamp = "20200128073000", .Value = -2.1485},
New PIValue With {.PointName = "MW Tag 4", .TimeStamp = "20200128073000", .Value = -0.0000}
}
sResult = JsonConvert.SerializeObject(oPIValues1)
oPIValues2 = JsonConvert.DeserializeObject(Of PIValues)(sResult)
Console.WriteLine(sResult)
Console.ReadKey()
End Sub
End Module
Public Class PIValues
Inherits List(Of PIValue)
End Class
Public Class PIValue
Public Property PointName As String
Public Property TimeStamp As String
Public Property Value As Double
End Class
Ok... So I sussed it, the answer is:
Dim dser As List(Of PIValue) = JsonConvert.DeserializeObject(Of List(Of PIValue))(result)

Filter List of Class by Property Value and List Of Value

I have a Devexpress Gridcontrol bound to a custom class.
The class looks like this:
Public Class AuditList
Public CasualtyList As List(Of CasualtyRecords)
Public MedsList As List(Of CasualtyRecords.Medications)
Public Property FilterString As CriteriaOperator
Public Sub New()
CasualtyList = New List(Of CasualtyRecords)
MedsList = New List(Of CasualtyRecords.Medications)
End Sub
Public Class CasualtyRecords
Private _primary As New PS
Public Property PrimarySurvey As PS
Get
Return _primary
End Get
Set(value As PS)
_primary = value
End Set
End Property
Public Sub New()
Vitals = New List(Of VitalRecords)
End Sub
Public Property Vitals As List(Of VitalRecords)
Public Property Meds As List(Of Medications)
ReadOnly Property MedCount As Integer
Get
Return Meds.Count
End Get
End Property
Property Id As Integer
Property ClinicalImpression As String
Property Disposal As String
Property Age As Integer
Property Gender As String
Class PS
Public Property Airway As Integer
Public Property Breathing As Integer
Public Property Circulation As Integer
Public Property Rate As Integer
End Class
Class Medications
Public Property MedName As String
End Class
End Class
End Class
This is an example of a filter type I am trying to create:
"[Gender] ='Male' AND [Medications].[MedName] = 'Paracetamol' AND [Age] >100"
Is this possible with the class constructed as shown, or perhaps do I need to implement some other interface?
I imagine that it would look something like this with LINQ
Dim b As New CasualtyRecords
b = a.CasualtyList.Where(Function(x) x.Meds.Any(Medications.Med = "Paracetamol") And x.Gender = "Male" And x.Age > 20)
Thanks
I was able to achieve the required results using this LINQ query
Dim newrecords = a.CasualtyList.Where(
Function(x) x.Meds.Any(
Function(b) b.MedName = "Paracetamol") _
And x.Gender = "Male" And x.Age > 20).ToList()

VB.NET Object with custom name to store property?

I'm not familiar with the type of structure or whatever I need to use to achieve this, but I know that there is one.
I'm trying to make it so that I can reference things something like this:
racerlist(x).compatibilityArr.john.CleatScore
instead of what I have to do now:
racerlist(x).compatibilityArr.CleatScoreArr(y).name/.score
So essentially, I want to add items to the compatibilityarr (will probably have to change to a list which is fine) and be able to reference the racer as their own name, instead of by using an index.
This is one way to build a solution that fits your needs as described above. It requires an embedded class that is built as a List(Of T) where we overload the property to accept a string rather than the integer.
Public Class Foo
Public Property compatibilityArr As New Members
End Class
Public Class Members : Inherits List(Of Member)
Public Overloads ReadOnly Property Item(name As String) As Member
Get
Return Me.Where(Function(i) i.Name = name).FirstOrDefault
End Get
End Property
End Class
Public Class Member
Public Property Name As String
Public Property CleatScore As Integer
End Class
Then to use it:
Public Class Form1
Dim f As New Foo
Private Sub loads() Handles Me.Load
Dim member As New Member With {.Name = "John", .CleatScore = 10}
f.compatibilityArr.Add(member)
MessageBox.Show(f.compatibilityArr.Item("John").CleatScore)
End Sub
End Class
There are other ways to do this, but the simplest is to write a function to search the array by name:
Sub Main1()
Dim racerlist(2) As Racer
racerlist(0) = New Racer With {.Name = "Adam", .CleatScore = "1"}
racerlist(1) = New Racer With {.Name = "Bill", .CleatScore = "2"}
racerlist(2) = New Racer With {.Name = "Charlie", .CleatScore = "3"}
For i As Integer = 0 To racerlist.GetUpperBound(0)
For j As Integer = 0 To racerlist.GetUpperBound(0)
If racerlist(j).Name <> racerlist(i).Name Then
ReDim Preserve racerlist(i).CompatibilityArr(racerlist(i).CompatibilityArr.GetUpperBound(0) + 1)
racerlist(i).CompatibilityArr(racerlist(i).CompatibilityArr.GetUpperBound(0)) = racerlist(j)
End If
Next j
Next i
Dim racerBill As Racer = Racer.FindRacer(racerlist, "Bill")
MsgBox(racerBill.FindCompatibility("Charlie").CleatScore)
End Sub
Class Racer
Property Name As String
Property CleatScore As String
Property CompatibilityArr As Racer()
Sub New()
ReDim CompatibilityArr(-1) 'initialise the array
End Sub
Function FindCompatibility(name As String) As Racer
Return FindRacer(CompatibilityArr, name)
End Function
Shared Function FindRacer(racerlist() As Racer, name As String) As Racer
For i As Integer = 0 To racerlist.GetUpperBound(0)
If racerlist(i).Name = name Then
Return racerlist(i)
End If
Next i
Return Nothing
End Function
End Class
As #Codexer mentioned, I used a dictionary to achieve this.
In my list of Racers (RacerList), I have RacerCompatibility, which I created similar to below:
Public RacerCompatibility As New Dictionary(Of String, Compatibility)
Compatibility is created like:
Public Class Compatibility
Public Cleat As Boolean
Public Skill As Integer
Public Height As Integer
End Class
So now I can access the compatibility of a racer inside the list like:
RacerList(x).RacerCompatibility.Item("John")

Combine two tables into one entity framework? (SQLite)

I am using the EntityFramework.SQLite library and for the life of me can not figure out how to combine two tables together into a temporary table for display purposes in xaml code.
Here's the code for my two tables I want to combine which is about all I am using right now besides a class for my temp table called CategoryList (this is part of the business/data logic dll library):
Partial Public Class CategoryList
Public Sub New()
Me.CategoryInfo = New CategoryReference
'Me.CategoryCode = New HashSet(Of CategoryCodes)
Me.CategoryCodes = New CategoryCodes
End Sub
Public Property MyId As Integer
<Key, ForeignKey("CodeID")>
<Required>
Public Property CodeID As Integer
<Key, ForeignKey("CategoryID")>
Public CategoryID As Integer
'Public Property CategoryCode As ICollection(Of CategoryCodes)
Public Property CategoryInfo As CategoryReference
' Public Property CategoryInfo As ICollection(Of CategoryReference)
Public Property CategoryCodes As CategoryCodes
End Class
<Table("CategoryCodes")>
Public Class CategoryCodes 'category shortnames/codes
<MaxLength(100)>
<Required>
Public Property CategoryCode As String
Get
Return _CategoryCode
End Get
Set(value As String)
_CategoryCode = value
End Set
End Property
Private _CategoryCode As String
'<NotNull>
' <PrimaryKey>
'<Unique(Name:="UQ__CategoryCodes__0000000000000081_CategoryCodes", Order:=0)>
<Key>
<Required>
Public Property CodeID As Integer
Get
Return CategoryCode
End Get
Set(value As Integer)
_CodeID = value
End Set
End Property
Private _CodeID As Integer
End Class
<Table("CategoryReference")>
Partial Public Class CategoryReference 'table design for category data
<MaxLength(100)>
Public Property CategoryName As String
Get
Return _CategoryName
End Get
Set(value As String)
_CategoryName = value
End Set
End Property
Private _CategoryName As String
<MaxLength(100)>
Public Property CategoryDescription As String
Get
Return _CategoryDescription
End Get
Set(value As String)
_CategoryDescription = value
End Set
End Property
Private _CategoryDescription As String
'<Unique(Name:="UQ__CatagoryReference__000000000000005F_CatagoryReference", Order:=0)>
<ForeignKey("CodeID")>
<Required>
Public Property CodeID As Integer
Get
Return _CodeID
End Get
Set(value As Integer)
_CodeID = value
End Set
End Property
Private _CodeID As Integer
'<Unique(Name:="UQ__CatagoryReference__000000000000005A_CatagoryReference", Order:=0)>
<Key>
<Required>
Public Property CategoryID As Integer
Get
Return _CategoryID
End Get
Set(value As Integer)
_CategoryID = value
End Set
End Property
Private _CategoryID As Integer
End Class
It may seem long but the tables are very simple and the get/set blocks make it look long (A vb.net editor can turn them into simple property's if she/he wishes). I may be using the CategoryList class wrong but here's where I use it in my xaml datasource in my main application code (I have business logic/data processing in a dll library):
Private Property ViewModel As List(Of UIELLUWP.DataAccess.CategoryList)
Dim categories As New UIELLUWP.DataAccess.SQLiteDb
ViewModel = categories.Categories.ToList
Errors received with current code:
I receive an error that Table "CategoryList" does not exist when I run the above code.
my solution I found out to this question was to add asnotracking because tracking was taking place.

how to loop inside every tables/columns in a dbml file to create new partial class with more information about every columns

I have a class that add extra information about a column for linq2sql (see code below)
right now, I have to explicitly tell what column I want that info on, how would you put that code with a loop on every column in every table from a dbml file?
I was doing my test on a very very small DB, now I have to implement it on a much more bigger database and I really don't want to do it manually for every tables/columns
it will take hours.
how it's being used:
Partial Class Contact ''contact is a table inside a dbml file.
Private _ContactIDColumn As ExtraColumnInfo
Private _ContactNameColumn As ExtraColumnInfo
Private _ContactEmailColumn As ExtraColumnInfo
Private _ContactTypeIDColumn As ExtraColumnInfo
Private Sub OnCreated()
initColumnInfo()
End Sub
Private Sub initColumnInfo()
Dim prop As PropertyInfo
prop = Me.GetType.GetProperty("ContactID")
_ContactIDColumn = New ExtraColumnInfo(DirectCast(prop.GetCustomAttributes(GetType(ColumnAttribute), False)(0), ColumnAttribute))
prop = Me.GetType.GetProperty("ContactName")
_ContactNameColumn = New ExtraColumnInfo(DirectCast(prop.GetCustomAttributes(GetType(ColumnAttribute), False)(0), ColumnAttribute))
prop = Me.GetType.GetProperty("ContactEmail")
_ContactEmailColumn = New ExtraColumnInfo(DirectCast(prop.GetCustomAttributes(GetType(ColumnAttribute), False)(0), ColumnAttribute))
prop = Me.GetType.GetProperty("ContactTypeID")
_ContactTypeIDColumn = New ExtraColumnInfo(DirectCast(prop.GetCustomAttributes(GetType(ColumnAttribute), False)(0), ColumnAttribute))
prop = Nothing
End Sub
Public ReadOnly Property ContactIDColumn() As ExtraColumnInfo
Get
Return _ContactIDColumn
End Get
End Property
Public ReadOnly Property ContactNameColumn() As ExtraColumnInfo
Get
Return _ContactNameColumn
End Get
End Property
Public ReadOnly Property ContactEmailColumn() As ExtraColumnInfo
Get
Return _ContactEmailColumn
End Get
End Property
Public ReadOnly Property ContactTypeIDColumn() As ExtraColumnInfo
Get
Return _ContactTypeIDColumn
End Get
End Property
End Class
what is ExtraColumnInfo:
Public Class ExtraColumnInfo
Private _column As ColumnAttribute
Private _MaxLength As Nullable(Of Integer)
Private _Precision As Nullable(Of Integer)
Private _Scale As Nullable(Of Integer)
Private _IsIdentity As Boolean
Private _IsUniqueIdentifier As Boolean
Sub New(ByVal column As ColumnAttribute)
Dim match As Match
_column = column
Match = Regex.Match(DBType, "^.*\((\d+)\).*$", RegexOptions.Compiled Or RegexOptions.IgnoreCase)
_MaxLength = If(match.Success, Convert.ToInt32(match.Groups(1).Value), Nothing)
match = Regex.Match(DBType, "^.*\((\d+),(\d+)\).*$", RegexOptions.Compiled Or RegexOptions.IgnoreCase)
_Precision = If(Match.Success, Convert.ToInt32(Match.Groups(1).Value), Nothing)
match = Regex.Match(DBType, "^.*\((\d+),(\d+)\).*$", RegexOptions.Compiled Or RegexOptions.IgnoreCase)
_Scale = If(match.Success, Convert.ToInt32(match.Groups(2).Value), Nothing)
match = Regex.Match(DBType, "^.*\bIDENTITY\b.*$", RegexOptions.Compiled Or RegexOptions.IgnoreCase)
_IsIdentity = match.Success
match = Regex.Match(DBType, "^.*\bUniqueIdentifier\b.*$", RegexOptions.Compiled Or RegexOptions.IgnoreCase)
_IsUniqueIdentifier = match.Success
End Sub
'others available information
'AutoSync
'Expression
'IsVersion
'Name
'Storage
'TypeId
'UpdateCheck
'maybe more
Public ReadOnly Property CanBeNull() As Boolean
Get
Return _column.CanBeNull
End Get
End Property
Public ReadOnly Property IsDbGenerated() As Boolean
Get
Return _column.IsDbGenerated
End Get
End Property
Public ReadOnly Property IsPrimaryKey() As Boolean
Get
Return _column.IsPrimaryKey
End Get
End Property
Public ReadOnly Property DBType() As String
Get
Return _column.DbType
End Get
End Property
Public ReadOnly Property MaxLength() As System.Nullable(Of Integer)
Get
Return _MaxLength
End Get
End Property
Public ReadOnly Property Precision() As System.Nullable(Of Integer)
Get
Return _Precision
End Get
End Property
Public ReadOnly Property Scale() As System.Nullable(Of Integer)
Get
Return _Scale
End Get
End Property
Public ReadOnly Property IsIdentity() As Boolean
Get
Return _IsIdentity
End Get
End Property
Public ReadOnly Property IsUniqueIdentifier() As Boolean
Get
Return _IsUniqueIdentifier
End Get
End Property
End Class
The only thing that comes to mind, and it's a far from optimal solution, would be to include this functionality into a base class and declare partials for all of the generated classes so that they inherit from your base class.
I'm sure there are also other ways to do this, but none that I know of that are native to the designer.
I took the T4 template and modified it a little to automatically put inside the generated class the column information,
in the import I added
Imports System.Reflection
Imports System.Text.RegularExpressions
at line 228, added these line:
<# foreach(Column column in class1.Columns) {#>
Private _<#=column.Member#>Column As ExtraColumnInfo
Public ReadOnly Property <#=column.Member#>Column() As ExtraColumnInfo
Get
Return _<#=column.Member#>Column
End Get
End Property
<# }#>
at line 298 I added
Dim prop As PropertyInfo
<# foreach(Column column in class1.Columns) {#>
prop = Me.GetType.GetProperty("<#=column.Member#>")
_<#=column.Member#>Column = New ExtraColumnInfo(DirectCast(prop.GetCustomAttributes(GetType(ColumnAttribute), False)(0), ColumnAttribute))
<# }#>
at the end of the file, I added my own class