Its not going to CollectionBase, Enumerator,Enumerable objects - vb.net

I have a class in the code below, where besides equals and hash methods from IEqualityComparer which I use, I also want to implement add, remove, item, count from list and GetEnumerator (current,movenext,position). So I decided to use Inherits CollectionBase, IEnumerator and IEnumerable.
Anyway for instance when I use Add its not going to Add method in Part class, or when I do for each its not going to GetEnumerator move next. What is the problem?
This is the class:
Imports System.Collections.Generic
Public Class Part
Inherits CollectionBase
Implements IEqualityComparer(Of Part), IEnumerator(Of Part), IEnumerable(Of Part)
Private _values As List(Of Part)
Private _currentIndex As Integer
Public Property _comparisonType As EqualsComparmission
Public Sub New(ComparisonType As EqualsComparmission)
Me._comparisonType = ComparisonType
End Sub
Public Sub New(values As List(Of Part))
_values = New List(Of Part)(values)
Reset()
End Sub
Public Sub New()
End Sub
Public Property PartName() As String
Public Property PartId() As Integer
Public Overrides Function ToString() As String
Return "ID: " & PartId & " Name: " & PartName
End Function
Public Sub Add(ByVal value As Part)
Me.List.Add(value)
End Sub
Public Sub Remove(ByVal Index As Integer)
If Index >= 0 And Index < Count Then
List.Remove(Index)
End If
End Sub
Public ReadOnly Property Item(ByVal Index As Integer) As Part
Get
Return CType(List.Item(Index), Part)
End Get
End Property
Public ReadOnly Property Current() As Part
Get
Return _values(_currentIndex)
End Get
End Property
Public ReadOnly Property Current1 As Object Implements IEnumerator.Current
Get
Return Current
End Get
End Property
Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext
_currentIndex += 1
Return _currentIndex < _values.Count
End Function
Public Sub Reset() Implements IEnumerator.Reset
_currentIndex = -1
End Sub
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
' TODO: set large fields to null.
End If
Me.disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
'Protected Overrides Sub Finalize()
' ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
' Dispose(False)
' MyBase.Finalize()
'End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
Public Function GetEnumerator1() As IEnumerator(Of Part) Implements IEnumerable(Of Part).GetEnumerator
Return CType(Me, IEnumerator)
End Function
Public ReadOnly Property Current2 As Part Implements IEnumerator(Of Part).Current
Get
Return Current
End Get
End Property
Public Function Equals1(x As Part, y As Part) As Boolean Implements System.Collections.Generic.IEqualityComparer(Of Part).Equals
If x Is Nothing AndAlso y Is Nothing Then Return True
If x Is Nothing OrElse y Is Nothing Then Return False
Select Case _comparisonType
Case EqualsComparmission.PartId
Return x.PartId = y.PartId
Case EqualsComparmission.PartName
Return String.Equals(x.PartName, y.PartName)
Case EqualsComparmission.PartId_and_PartName
Return x.PartId = y.PartId AndAlso String.Equals(x.PartName, y.PartName)
Case Else
Throw New NotSupportedException("Unknown comparison type for parts: " & _comparisonType.ToString())
End Select
End Function
Public Function GetHashCode1(obj As Part) As Integer Implements System.Collections.Generic.IEqualityComparer(Of Part).GetHashCode
Select Case _comparisonType
Case EqualsComparmission.PartId
Return obj.PartId
Case EqualsComparmission.PartName
Return If(obj.PartName Is Nothing, 0, obj.PartName.GetHashCode())
Case EqualsComparmission.PartId_and_PartName
Dim hash = 17
hash = hash * 23 + obj.PartId
hash = hash * 23 + If(obj.PartName Is Nothing, 0, obj.PartName.GetHashCode())
Return hash
Case Else
Throw New NotSupportedException("Unknown comparison type for parts: " & _comparisonType.ToString())
End Select
End Function
End Class
and this is test code:
Dim parts As New List(Of Part)()
parts.Add(New Part() With { _
.PartName = "ala", _
.PartId = 11 _
})
parts.Add(New Part() With { _
.PartName = "shift lever", _
.PartId = 1634 _
})
For Each aPart As Part In parts
Console.WriteLine(aPart)
Next
Edited:
PartsCollection which implements ICollection for list operations:
Public Class PartsCollection
Implements ICollection(Of Part)
' Enumerators are positioned before the first element
' until the first MoveNext() call.
Dim position As Integer = -1
Private myList As List(Of Part)
Public Sub New()
If myList Is Nothing Then
myList = New List(Of Part)
End If
End Sub
Public Sub Add(item As Part) Implements ICollection(Of Part).Add
myList.Add(item)
End Sub
Public Sub Clear() Implements ICollection(Of Part).Clear
End Sub
Public Function Contains1(item As Part) As Boolean Implements ICollection(Of Part).Contains
Return myList.Contains(item)
End Function
Public Sub CopyTo(array() As Part, arrayIndex As Integer) Implements ICollection(Of Part).CopyTo
End Sub
Public Function GetEnumerator() As IEnumerator(Of Part) Implements IEnumerable(Of Part).GetEnumerator
Return New PartsEnumeration(myList)
End Function
Public ReadOnly Property Count As Integer Implements ICollection(Of Part).Count
Get
End Get
End Property
Public ReadOnly Property IsReadOnly As Boolean Implements ICollection(Of Part).IsReadOnly
Get
End Get
End Property
Public Function Remove(item As Part) As Boolean Implements ICollection(Of Part).Remove
End Function
Public Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
End Function
End Class
PartsEnumeration for for each loop:
Public Class PartsEnumeration
Implements IEnumerator(Of Part)
Private mmyList As List(Of Part)
Dim position As Integer = -1
Public Sub New(ByVal myList As List(Of Part))
mmyList = myList
End Sub
Public ReadOnly Property Current As Part Implements IEnumerator(Of Part).Current
Get
Try
Return mmyList(position)
Catch ex As IndexOutOfRangeException
Throw New InvalidOperationException()
End Try
End Get
End Property
Public ReadOnly Property Current1 As Object Implements IEnumerator.Current
Get
Try
Return mmyList(position)
Catch ex As IndexOutOfRangeException
Throw New InvalidOperationException()
End Try
End Get
End Property
Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext
If position < mmyList.Count - 1 Then
position += 1
Return True
End If
Return False
End Function
Public Sub Reset() Implements IEnumerator.Reset
position = -1
End Sub
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
' TODO: set large fields to null.
End If
Me.disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
'Protected Overrides Sub Finalize()
' ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
' Dispose(False)
' MyBase.Finalize()
'End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
Test code:
Dim cos As New Part With { _
.PartName = "crank arm", _
.PartId = 1234 _
}
Dim cos3 As New Part With { _
.PartName = "cranddk arm", _
.PartId = 123334 _
}
myParts.Add(something1)
myParts.Add(something2)
Dim p As Boolean = myParts.Contains1(something1)
Console.WriteLine(p)
For Each ii In myParts
Console.WriteLine(ii.ToString)
Next

You are gluing 2 things together that are related but not the same thing and making a list of collections.
Dim parts As New List(Of Part)()
Since Part inherits from CollectionBase, you are making a List of Collections. A Collection class should be used to implement methods to manage the list/collection such as the Extension functionality in the other question. It would manage the List for you.
Class Part
Property Name As String
Property ID As Integer
End Class
Class Parts
Private myList As New List(Of Part)
Public Sub Add(item As Part)
Public Function IndexOfPartName...
etc
Public Sub Remove(item As Part)
' some might just be wrappers:
Public Function Contains(p As Part) As Boolean
Return myList.Contains(Part)
End Function
End Class
The code that consumes these:
Friend myParts As New Parts
myParts.Add(New Part(...))
Dim p As Part = myParts.IndexOfPartName("screws")
Once you work out the functionality you need and how it will be used, you might change it to Inherit Collection<T> so you can do For Each p As Part in Parts. But work on getting a viable collection class before tackling interfaces and such. Some of those may not be needed since Collection<T> implements all that for you.
You might be interested in: Guidelines for Collections
--
For your parts collection class to BE a collection rather then be a wrapper for an internal one:
Imports System.ComponentModel
Class Parts
Inherits Collection(Of Part)
' ALREADY implemeted for you are:
' Contains, Count, Add, Clear, IndexOf, Insert, EQUALS
' Item, Items, Remove, RemoveAt and RemoveItem
As such, all you need to do is override those methods which do something differently than you would like, or to extend functionality such as a IndexOfPartName.
ICollection requires you to write a collection from scratch, but the wheel has already been built.

Related

Implement same logic for diffrent objects as T

I suppose to use T but i am not sure how do it in proper way.
Let's consider following example.
Base class:
Public Class HtmlBase
Implements IGetInformation
Public Overridable Function IsExist() As Boolean Implements IGetInformation.IsExist
Throw New NotImplementedException()
End Function
Public Overridable Function GetIdByName(pName As String) As Integer Implements IGetInformation.GetIdByName
Throw New NotImplementedException()
End Function
End Class
Example classes which inherit from base class:
Public Class HtmlSubSection
Inherits HtmlBase
'--sometimes i have to overload to add additioinal parameter
Public Overloads Function isExist(subsection As String) As Boolean
Dim dlsubkategorie As New DataLayer.DALSubSection
Return dlsubkategorie.CheckIfSubSectionExist(subsection)
End Function
Public Overrides Function GetIdByName(subsectionName As String) As Integer
Dim dlget As New DataLayer.DALSubSection
Return dlget.GetSubSectionIdByName(subsectionName)
End Function
End Class
Public Class HtmlSection
Inherits HtmlBase
'sometime i have to overload to add additioinal parameter
Public Overloads Function IsExist(section As String) As Boolean
Dim dlsubkategorie As New DataLayer.DALSection
Return dlsubkategorie.CheckIfSectionExist(section)
End Function
Public Overrides Function GetIdByName(Name As String) As Integer
Dim dlsubkategorie As New DataLayer.DALSection
Return dlsubkategorie.GetSectionIdByName(Name)
End Function
End Class
As could be seen above two classes which inherits from base within their methods has same logic (sometimes i have to use additional parameter therefore overloads there, but are using diffrent DAL class to call. I would like to implement this logic in base class and for each just point to specific DAL. How to do that to not everytime in those classes write e.g:
Dim dlsubkategorie As New DataLayer.<DALSection>
Return dlsubkategorie.GetSectionIdByName(Name)
EDIT:
Htmlbase constructor's:
Sub New()
End Sub
Sub New(pId As Integer)
_Id = pId
End Sub
HtmlSubSection's constructors:
Sub New()
MyBase.New()
AvailableSentences = New List(Of HtmlSubSection_Sentence)
SelectedSentences = New List(Of HtmlSubSection_Sentence)
End Sub
Sub New(pId As Integer)
MyBase.New(pId)
End Sub
Sub New(pName As String)
_Name = pName
End Sub
Sub New(pId As Integer, pName As String)
MyBase.New(pId)
_Name = pName
End Sub
HtmlSection's constructors:
Sub New()
MyBase.New()
End Sub
Sub New(pId As Integer)
MyBase.New(pId)
End Sub
Sub New(pId As Integer, pName As String, pPosition As Integer)
MyBase.New(pId)
_Name = pName
_Position = pPosition
End Sub
Sub New(pName As String)
_Name = pName
End Sub
Sub New(pName As String, pPosition As Integer)
_Name = pName
_Position = pPosition
End Sub
You donĀ“t need generic types here. Just use Interfaces, Sub Classing and Polymorphism correctly.
New Interface IDAL which is implemented by DAL classes to get rid of different method names which take same parameters and do the same:
Public Interface IDAL
Function CheckIfSectionExist(section As string) As Boolean
Function GetSectionIdByName(section As string) As Integer
End Interface
Public Class DALSection
Implements IDAL
Public Function CheckIfSectionExist(section As string) As Boolean Implements IDAL.CheckIfSectionExist
...
End Function
Public Function GetSectionIdByName(section As String) As Integer Implements IDAL.GetSectionIdByName
...
End Function
End Class
Public Class DALSubSection
Implements IDAL
Public Function CheckIfSubSectionExist(subSection As string) As Boolean Implements IDAL.CheckIfSectionExist
...
End Function
Public Function GetSubSectionIdByName(subSection As String) As Integer Implements IDAL.GetSectionIdByName
...
End Function
End Class
Base class changed to abstract and the constructor now takes IDAL parameter. Function can now be executed polymorphic. Added a isExists(string) function to avoid overloading:
Public MustInherit Class HtmlBase
Implements IGetInformation
Public Property DAL as DataLayer.IDAL
Protected Sub New(dal as DataLayer.IDAL)
Me.DAL = dal
End Sub
Public Overridable Function isExist() As Boolean Implements IGetInformation.isExist
Return True
End Function
Public Overridable Function isExist(section As String) As Boolean
Return DAL.CheckIfSectionExist(Section)
End Function
Public Overridable Function GetIdByName(pName As String) As Integer Implements IGetInformation.GetIdByName
Return DAL.GetSectionIdByName(pName)
End Function
End Class
Client classes only need to give correct DAL to base class:
Public Class HtmlSubSection
Inherits HtmlBase
Public Sub New()
MyBase.New(New DataLayer.DALSubSection)
End Sub
End Class
Public Class HtmlSection
Inherits HtmlBase
Public Sub New()
MyBase.New(New DataLayer.DALSection)
End Sub
End Class
Basically it would be ideal if IGetInformation had a isExist method with an optional string parameter. This would save one unneccessary method in HtmlBase.

CodeAccessSecurityAttribute derived class throwing System.TypeLoadException (Failure has occurred while loading a type)

I have custom attribute applied to CRUD repository methods to control access:
Public Class SecureDbContextGenericRepository(Of TEntity As Class, TContext As DbContext)
Inherits DbContextGenericRepository(Of TEntity, TContext)
Public Sub New(connectionService As IConnectionService)
MyBase.New(connectionService)
End Sub
<EmployeeRoleRequirement(SecurityAction.Demand, EmployeeRoles:=EmployeeRoles.DataWriter)>
Public Overrides Sub Delete(ParamArray entities() As TEntity)
MyBase.Delete(entities)
End Sub
<EmployeeRoleRequirement(SecurityAction.Demand, EmployeeRoles:=EmployeeRoles.DataWriter)>
Public Overrides Sub Insert(ParamArray entities() As TEntity)
MyBase.Insert(entities)
End Sub
<EmployeeRoleRequirement(SecurityAction.Demand, EmployeeRoles:=EmployeeRoles.DataReader)>
Public Overrides Function [Select](Optional predicate As Func(Of TEntity, Boolean) = Nothing) As IList(Of TEntity)
Return MyBase.Select(predicate)
End Function
<EmployeeRoleRequirement(SecurityAction.Demand, EmployeeRoles:=EmployeeRoles.DataWriter)>
Public Overrides Sub Update(ParamArray entities() As TEntity)
MyBase.Update(entities)
End Sub
End Class
This is implementation of attribute:
Public Class EmployeeRoleRequirementAttribute
Inherits CodeAccessSecurityAttribute
Public Sub New(action As SecurityAction)
MyBase.New(action)
End Sub
Public Overrides Function CreatePermission() As IPermission
Return New EmployeeRolePermission(_EmployeeRoles)
End Function
Public Property EmployeeRoles As EmployeeRoles
End Class
<Flags>
Public Enum EmployeeRoles As Integer
DataReader = 0
DataWriter = 1
End Enum
And permission:
Public Class EmployeeRolePermission
Implements IPermission
Public Sub New(employeeRoles As EmployeeRoles)
_EmployeeRoles = employeeRoles
End Sub
Public Function Copy() As IPermission Implements IPermission.Copy
Return New EmployeeRolePermission(_EmployeeRoles)
End Function
Public Sub Demand() Implements IPermission.Demand
Dim principal = DirectCast(Thread.CurrentPrincipal, ProductionAssistantPrincipal)
If Not principal.IsInRole(_EmployeeRoles) Then
Throw New SecurityException(String.Format(My.Resources.EmployeeRoleNotFound,
principal.Identity.Name,
_EmployeeRoles.ToString()))
End If
End Sub
Public Sub FromXml(e As SecurityElement) Implements ISecurityEncodable.FromXml
Throw New NotImplementedException()
End Sub
Public Function Intersect(target As IPermission) As IPermission Implements IPermission.Intersect
Return New EmployeeRolePermission(_EmployeeRoles And DirectCast(target, EmployeeRolePermission).EmployeeRoles)
End Function
Public Function IsSubsetOf(target As IPermission) As Boolean Implements IPermission.IsSubsetOf
Return _EmployeeRoles.HasFlag(DirectCast(target, EmployeeRolePermission).EmployeeRoles)
End Function
Public Function ToXml() As SecurityElement Implements ISecurityEncodable.ToXml
Throw New NotImplementedException()
End Function
Public Function Union(target As IPermission) As IPermission Implements IPermission.Union
Return New EmployeeRolePermission(_EmployeeRoles Or DirectCast(target, EmployeeRolePermission).EmployeeRoles)
End Function
Public ReadOnly Property EmployeeRoles As EmployeeRoles
End Class
Every time one of the CRUD methods are reached, TypeLoadException is thrown. I really dont know cause of this, but if I remove attributes from CRUD methods, everything works fine.
This seems to be due to the enum-valued property on the attribute (see https://connect.microsoft.com/VisualStudio/feedback/details/596251/custom-cas-attributes-with-an-enum-property-set-cause-a-typeloadexception for details). To work around this issue, you could use a string-valued property on the attribute and cast to an enum either in the property setter or just before creating the permission. (Personally, I'd probably opt for the former in the interests of enabling early validation, but ymmv...)
Another workaround is making attribute property of type, which is used in Enum, in this case Integer.
Public Class EmployeeRoleRequirementAttribute
Inherits CodeAccessSecurityAttribute
Public Sub New(action As SecurityAction)
MyBase.New(action)
End Sub
Public Overrides Function CreatePermission() As IPermission
Return New EmployeeRolePermission(CType(_RequiredEmployeeRoles, EmployeeRoles))
End Function
Public Property RequiredEmployeeRoles As Integer
End Class
<Flags>
Public Enum EmployeeRoles As Integer
DataReader = 0
DataWriter = 1
End Enum
Then you dont need to use String, which does not allow easy combining of flags when attribute is used:
<EmployeeRoleRequirement(SecurityAction.Demand, RequiredEmployeeRoles:=EmployeeRoles.DataReader Or EmployeeRoles.DataWriter)>
Sub SecuredMethod()
End Sub

Create a List property which cannot be changed externally

I have a public class in my VB.NET project which has a List(Of String) property. This list needs to be modified by other classes within the project, but since the class may (at some time in the future) be exposed outside the project, I want it to be unmodifiable at that level. The modification of the existing property within the project will only be done by calling the list's methods (notably .Add, occasionally .Clear), not by a wholesale replacement of the property value with a new List (which is why I have it as a ReadOnly property).
I have come up with a way of doing it, but I'm not sure that it's exactly what you would call "elegant".
It's this:
Friend mlst_ParameterNames As List(Of String) = New List(Of String)
Public ReadOnly Property ParameterNames() As List(Of String)
Get
Return New List(Of String)(mlst_ParameterNames)
End Get
End Property
Now this just works fine and dandy. Any class in the project which accesses the mlst_ParameterNames field directly can modify it as needed, but any procedures which access it through the public property can bang away at modifying it to their heart's content, but will get nowhere since the property procedure is always returning a copy of the list, not the list itself.
But, of course, that carries overhead which is why I feel that it's just... well, viscerally "wrong" at some level, even though it works.
The parameters list will never be huge. At most it will only contain 50 items, but more commonly less than ten items, so I can't see this ever being a performance killer. However it has of course set me to thinking that someone, with far more VB.NET hours under their belt, may have a much neater and cleaner idea.
Anyone?
Instead of creating a new copy of the original list, you should use the AsReadOnly method to get a read-only version of the list, like this:
Friend mlst_ParameterNames As List(Of String) = New List(Of String)
Public ReadOnly Property ParameterNames() As ReadOnlyCollection(Of String)
Get
Return mlst_ParameterNames.AsReadOnly()
End Get
End Property
According to the MSDN:
This method is an O(1) operation.
Which means that the speed of the AsReadOnly method is the same, regardless of the size of the list.
In addition to the potential performance benefits, the read-only version of the list is automatically kept in sync with the original list, so if consuming code keeps a reference to it, its referenced list will still be up-to-date, even if items are later added to or removed from the list.
Also, the list is truly read-only. It does not have an Add or Clear method, so there will be less confusion for others using the object.
Alternatively, if all you need is for consumers to be able to iterate through the list, then you could just expose the property as IEnumerable(Of String) which is, inherently, a read-only interface:
Public ReadOnly Property ParameterNames() As IEnumerable(Of String)
Get
Return mlst_ParameterNames
End Get
End Property
However, that makes it only useful to access the list in a For Each loop. You couldn't, for instance, get the Count or access the items in the list by index.
As a side note, I would recommend adding a second Friend property rather than simply exposing the field, itself, as a Friend. For instance:
Private _parameterNames As New List(Of String)()
Public ReadOnly Property ParameterNames() As ReadOnlyCollection(Of String)
Get
Return _parameterNames.AsReadOnly()
End Get
End Property
Friend ReadOnly Property WritableParameterNames() As List(Of String)
Get
Return _parameterNames
End Get
End Property
What about providing a Locked property that you can set, each other property then checks this to see if it's been locked...
Private m_Locked As Boolean = False
Private mlst_ParameterNames As List(Of String) = New List(Of String)
Public Property ParameterNames() As List(Of String)
Get
Return New List(Of String)(mlst_ParameterNames)
End Get
Set(value As List(Of String))
If Not Locked Then
mlst_ParameterNames = value
Else
'Whatever action you like here...
End If
End Set
End Property
Public Property Locked() As Boolean
Get
Return m_Locked
End Get
Set(value As Boolean)
m_Locked = value
End Set
End Property
-- EDIT --
Just to add to this, then, here's a basic collection...
''' <summary>
''' Provides a convenient collection base for search fields.
''' </summary>
''' <remarks></remarks>
Public Class SearchFieldList
Implements ICollection(Of String)
#Region "Fields..."
Private _Items() As String
Private _Chunk As Int32 = 16
Private _Locked As Boolean = False
'I've added this in so you can decide if you want to fail on an attempted set or not...
Private _ExceptionOnSet As Boolean = False
Private ptr As Int32 = -1
Private cur As Int32 = -1
#End Region
#Region "Properties..."
Public Property Items(ByVal index As Int32) As String
Get
'Make sure we're within the index bounds...
If index < 0 OrElse index > ptr Then
Throw New IndexOutOfRangeException("Values between 0 and " & ptr & ".")
Else
Return _Items(index)
End If
End Get
Set(ByVal value As String)
'Make sure we're within the index bounds...
If index >= 0 AndAlso Not _Locked AndAlso index <= ptr Then
_Items(index) = value
ElseIf _ExceptionOnSet Then
Throw New IndexOutOfRangeException("Values between 0 and " & ptr & ". Use Add() or AddRange() method to append fields to the collection.")
End If
End Set
End Property
Friend Property ChunkSize() As Int32
Get
Return _Chunk
End Get
Set(ByVal value As Int32)
_Chunk = value
End Set
End Property
Public ReadOnly Property Count() As Integer Implements System.Collections.Generic.ICollection(Of String).Count
Get
Return ptr + 1
End Get
End Property
''' <summary>
''' Technically unnecessary, just kept to provide coverage for ICollection interface.
''' </summary>
''' <returns>Always returns false</returns>
''' <remarks></remarks>
Public ReadOnly Property IsReadOnly() As Boolean Implements System.Collections.Generic.ICollection(Of String).IsReadOnly
Get
Return False
End Get
End Property
#End Region
#Region "Methods..."
Public Shadows Sub Add(ByVal pItem As String) Implements System.Collections.Generic.ICollection(Of String).Add
If Not _Items Is Nothing AndAlso _Items.Contains(pItem) Then Throw New InvalidOperationException("Field already exists.")
ptr += 1
If Not _Items Is Nothing AndAlso ptr > _Items.GetUpperBound(0) Then SetSize()
_Items(ptr) = pItem
End Sub
Public Shadows Sub AddRange(ByVal collection As IEnumerable(Of String))
Dim cc As Int32 = collection.Count - 1
For sf As Int32 = 0 To cc
If _Items.Contains(collection.ElementAt(sf)) Then
Throw New InvalidOperationException("Field already exists [" & collection.ElementAt(sf) & "]")
Else
Add(collection.ElementAt(sf))
End If
Next
End Sub
Public Function Remove(ByVal item As String) As Boolean Implements System.Collections.Generic.ICollection(Of String).Remove
Dim ic As Int32 = Array.IndexOf(_Items, item)
For lc As Int32 = ic To ptr - 1
_Items(lc) = _Items(lc + 1)
Next lc
ptr -= 1
End Function
Public Sub Clear() Implements System.Collections.Generic.ICollection(Of String).Clear
ptr = -1
End Sub
Public Function Contains(ByVal item As String) As Boolean Implements System.Collections.Generic.ICollection(Of String).Contains
Return _Items.Contains(item)
End Function
Public Sub CopyTo(ByVal array() As String, ByVal arrayIndex As Integer) Implements System.Collections.Generic.ICollection(Of String).CopyTo
_Items.CopyTo(array, arrayIndex)
End Sub
#End Region
#Region "Private..."
Private Sub SetSize()
If ptr = -1 Then
ReDim _Items(_Chunk)
Else
ReDim Preserve _Items(_Items.GetUpperBound(0) + _Chunk)
End If
End Sub
Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of String) Implements System.Collections.Generic.IEnumerable(Of String).GetEnumerator
Return New GenericEnumerator(Of String)(_Items, ptr)
End Function
Private Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Return GetEnumerator()
End Function
#End Region
End Class
Friend Class GenericEnumerator(Of T)
Implements IEnumerator(Of T)
#Region "fields..."
Dim flist() As T
Dim ptr As Int32 = -1
Dim size As Int32 = -1
#End Region
#Region "Properties..."
Public ReadOnly Property Current() As T Implements System.Collections.Generic.IEnumerator(Of T).Current
Get
If ptr > -1 AndAlso ptr < size Then
Return flist(ptr)
Else
Throw New IndexOutOfRangeException("=" & ptr.ToString())
End If
End Get
End Property
Public ReadOnly Property Current1() As Object Implements System.Collections.IEnumerator.Current
Get
Return Current
End Get
End Property
#End Region
#Region "Constructors..."
Public Sub New(ByVal fieldList() As T, Optional ByVal top As Int32 = -1)
flist = fieldList
If top = -1 Then
size = fieldList.GetUpperBound(0)
ElseIf top > -1 Then
size = top
Else
Throw New ArgumentOutOfRangeException("Expected integer 0 or above.")
End If
End Sub
#End Region
#Region "Methods..."
Public Function MoveNext() As Boolean Implements System.Collections.IEnumerator.MoveNext
ptr += 1
Return ptr <= size
End Function
Public Sub Reset() Implements System.Collections.IEnumerator.Reset
ptr = -1
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class

Can't sort BindingSource from the first time on SelectedIndexChange

I have a sub which on SelectedIndexChange - of Customer returns the TransactionBindingSource.
What I want is to show on the databound controls the latest transaction of each selected customer instead of the first one. The weird thing is that when the tab loads (on the 'enter' event I call the selectedIndexChange method and the latest record is selected. However, when I manually select another customer, the first record of each transaction is displayed! This is what I have
Private Sub cboCustomerName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCustomerName.SelectedIndexChanged
resetstats()
'Try
Dim iTotalbuyin, iCountBuyins, iSumBuyins, iSumCashouts, iBiggestWin, iBiggestLoss As Integer
Dim oTotalbuyin, oCountBuyIns, oSumCashouts, oBiggestWin, oBiggestLoss As Object
' If Me.cboCustomerName.SelectedIndex <> -1 Then
Dim drv As DataRowView = CType(Me.cboCustomerName.SelectedItem, DataRowView)
Dim SelCustId As Integer = drv.Item("CustomerID")
Me.TransactionTableAdapter.Fill(Me.DbPBDataSet.Transaction, SelCustId)
Me.TransactionBindingSource.Sort = "TransactionID"
Me.TransactionBindingSource.MoveLast()
Any ideas?
You can make your own SortableBindingList class, like so:
Imports System.ComponentModel
Imports System.Reflection
Public Class SortableBindingList(Of T)
Inherits BindingList(Of T)
Private Property IsSorted As Boolean
Private Property SortDirection As ListSortDirection
Private Property SortProperty As PropertyDescriptor
Protected Overrides ReadOnly Property SupportsSortingCore() As Boolean
Get
Return True
End Get
End Property
Protected Overrides ReadOnly Property SortDirectionCore() As ListSortDirection
Get
Return _SortDirection
End Get
End Property
Protected Overloads Overrides ReadOnly Property SortPropertyCore() As PropertyDescriptor
Get
Return _SortProperty
End Get
End Property
Protected Overloads Overrides Sub ApplySortCore(ByVal PDsc As PropertyDescriptor, ByVal Direction As ListSortDirection)
Dim items As List(Of T) = TryCast(Me.Items, List(Of T))
If items Is Nothing Then
IsSorted = False
Else
Dim PCom As New PCompare(Of T)(PDsc.Name, Direction)
items.Sort(PCom)
IsSorted = True
SortDirection = Direction
SortProperty = PDsc
End If
OnListChanged(New ListChangedEventArgs(ListChangedType.Reset, -1))
End Sub
Protected Overloads Overrides ReadOnly Property IsSortedCore() As Boolean
Get
Return _IsSorted
End Get
End Property
Protected Overrides Sub RemoveSortCore()
_IsSorted = False
End Sub
#Region " Constructors "
Sub New(ByVal list As ICollection(Of T))
MyBase.New(CType(list, Global.System.Collections.Generic.IList(Of T)))
End Sub
Sub New()
MyBase.New()
End Sub
#End Region
#Region " Property comparer "
Private Class PCompare(Of T)
Implements IComparer(Of T)
Private Property PropInfo As PropertyInfo
Private Property SortDir As ListSortDirection
Friend Sub New(ByVal SortProperty As String, ByVal SortDirection As ListSortDirection)
SortProperty = CheckPropertyName(SortProperty)
PropInfo = GetType(T).GetProperty(SortProperty)
SortDir = SortDirection
End Sub
''' <summary>
''' Used to change the name of the sorted property for certain classes.
''' </summary>
''' <param name="SortProperty"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function CheckPropertyName(ByVal SortProperty As String) As String
If SortProperty = "BinNumber" AndAlso GetType(T).Name = "BinReportDisplay" Then
Return "BinNumberSort"
End If
Return SortProperty
End Function
Friend Function Compare(ByVal x As T, ByVal y As T) As Integer Implements IComparer(Of T).Compare
Return If(SortDir = ListSortDirection.Ascending, Comparer.[Default].Compare(PropInfo.GetValue(x, Nothing),
PropInfo.GetValue(y, Nothing)), Comparer.[Default].Compare(PropInfo.GetValue(y, Nothing),
PropInfo.GetValue(x, Nothing)))
End Function
End Class
#End Region
End Class
Then sort the list according to how you want it sorted.

Trying to understand IDisposable

I read some articles and blogs on Implementation if IDisposable and GC working set. However, I could not understand the core areas of differentiation like:
Following is code of my test class:
Imports System.ComponentModel
Namespace Classes
Public Class BaseClass
Implements INotifyPropertyChanged
Implements IDisposable
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Protected Friend Sub NotifyPropertyChanged(ByVal info As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
End If
End If
Me.disposedValue = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
Public Class GenreClass
Inherits BaseClass
#Region "Private Variables"
Private _GenreValue As String
Private _IconValue As String
Private _IsSelectedValue As Boolean
Private _IsExpandedValue As Boolean
#End Region
#Region "Property Variables"
Property Genre As String
Get
Return _GenreValue
End Get
Set(Value As String)
If Not _GenreValue = Value Then
_GenreValue = Value
NotifyPropertyChanged("Genre")
End If
End Set
End Property
Property Icon As String
Get
Return _IconValue
End Get
Set(Value As String)
If Not _IconValue = Value Then
_IconValue = Value
NotifyPropertyChanged("Icon")
End If
End Set
End Property
Property IsSelected As Boolean
Get
Return _IsSelectedValue
End Get
Set(Value As Boolean)
If Not _IsSelectedValue = Value Then
_IsSelectedValue = Value
NotifyPropertyChanged("IsSelected")
End If
End Set
End Property
Property IsExpanded As Boolean
Get
Return _IsExpandedValue
End Get
Set(Value As Boolean)
If Not _IsExpandedValue = Value Then
_IsExpandedValue = Value
NotifyPropertyChanged("IsExpanded")
End If
End Set
End Property
#End Region
Protected Overrides Sub Dispose(disposing As Boolean)
Genre = Nothing
MyBase.Dispose(disposing)
End Sub
Public Overrides Function ToString() As String
Return Genre
End Function
End Class
End Namespace
My Test scenarios are as follows:
Test1:
Dim list1 As New List(Of HODLib.Classes.GenreClass)
For i = 0 To 4
Using z As New HODLib.Classes.GenreClass
With z
.Genre = "asdasd"
.Icon = "asdasdasdasdasd"
.IsExpanded = True
.IsSelected = True
End With
list1.Add(z)
End Using
Next
For Each z In list1
MessageBox.Show(z.ToString)
Next
result of test1 is that GC is called immediately and I loose access to resources, I get null message.
Test2:
Dim list1 As New List(Of HODLib.Classes.GenreClass)
For i = 0 To 4
Dim z As New HODLib.Classes.GenreClass
With z
.Genre = "asdasd"
.Icon = "asdasdasdasdasd"
.IsExpanded = True
.IsSelected = True
End With
list1.Add(z)
Next
For Each z In list1
MessageBox.Show(z.ToString)
Next
Result is Dispose is never called, even for z in forloop, I dont understand this, why is z not disposed, is it waiting because the list has reference to its values?
Test3:
Dim list1 As New List(Of HODLib.Classes.GenreClass)
For i = 0 To 4
Dim z As New HODLib.Classes.GenreClass
With z
.Genre = "asdasd"
.Icon = "asdasdasdasdasd"
.IsExpanded = True
.IsSelected = True
End With
list1.Add(z)
z.Dispose()
Next
For Each z In list1
MessageBox.Show(z.ToString)
Next
Result: Test2 vs test3 is calling the dispose manually after adding to the list. Result is that I lost access to resource, I get null message. Why did this happen although I added the object to list before calling the dispose method.
Thank you.
Unfortunately, the Dispose implementation that the Visual Basic IDE auto-generates is wrong in 99.9% of all cases. You should only use it if your class has a Finalize() method or the base class has a protected Dispose(Boolean) method. Which is extremely rare, finalizers are implemented by .NET Framework classes. It is their job to wrap unmanaged resources that should be released early.
It becomes 100% wrong when you find out that you can't write any meaningful code in the Dispose() method. Like this case, your class has no fields of a type that is disposable. Setting a field to Nothing has no effect.
You are adding a reference to the instance z which you create. When that instance is destroyed, the reference is no longer pointing to anything. The Using construct automatically calls Dispose for you. You can make a new copy of the object z by adding a method to the class:
Public Function Clone() As GenreClass
Return DirectCast(Me.MemberwiseClone(), GenreClass)
End Function
and use list1.Add(z.Clone).
See Object.MemberwiseClone Method for more information and if you need to create a deep copy.