Adding a list (T) property to a inherited panel class - vb.net

I am vey new to programming with classes. I am setting up a new program and want to give it a new, good structure and want to work with classes. But, I am stuck now for two days....I have an object class inherited from a panel. I want to add a list with info to it. IT almost seems to work but the property window in my main form also shows the info collection editor but I get a error which I can not seem to get rid of.. What am I doing wrong.
The error mesage:
Severity Code Description Project File Line Suppression State
Error Invalid Resx file. Could not load type System.Collections.Generic.List`1[[KRE_Interface.Info, KRE Interface, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 which is used in the .RESX file. Ensure that the necessary references have been added to your project. Line 915, position 5. KRE Interface D:\Dropbox\Dropbox\kre\KRESoftware\Alma 1 Interface\20200820 KRE Interface V6\KRE Interface\frmMain.resx 915
My code of the class:
Public Class RbGroep
Inherits Panel
Private m_ItemsInfo As List(Of Info)
Public Sub New()
ItemsInfo() = New List(Of Info)
End Sub
Property ItemsInfo() As List(Of Info)
Get
Return m_ItemsInfo
End Get
Set(ByVal value As List(Of Info))
m_ItemsInfo = value
End Set
End Property
End Class
<Serializable()>
Public Class Info
Public Property Order As Integer
Public Property RbName As String
End Class

I have it working with the info of Sean Kelly. Thanks a lot. Only: in the class I try to access the list with information, to make some radio bullets.
For i = 0 To amount_of_rb
Dim newrb As New KRERadiobutton
newrb.Name = "rb" & i
newrb.Text = ItemsInfo(i).RbName
newrb.Tag = itemsinfo(i).Order
newrb.Tag = i
newrb.Location = New System.Drawing.Point(40, 20 * i)
AddHandler newrb.CheckedChanged, AddressOf RadioButton1_CheckedChanged
Me.Controls.Add(newrb)
Next
The line with the itemsinfo(i) give me errors. Anybody an idea how to adress these bvariables?

Add this line to the top of the .vb file containing your class:
Imports System.Collections.Generic

Related

VS2019 class constructor with different signatures requires all signatures types be included as references by calling program

This has been reported via VS2019 feedback mechanism, but I need a solution quicker. Code snippets are below. Apologies for not knowing how to format this better.
Library class has three constructors, the calling test program in same solution which is .NET V4, is required to have a reference to System.Web when it is not needed. When System.Web is referenced and imported, problem occurs that VS2019 V16.6 thinks Newtonsoft.Json V9.0.1 is being referenced. This is on the critical path for a WS2008R2 (VS2010) to WS2019 (VS2019) migration. Problem not seen on WS2012 or WS2016, both with VS2010.
Severity Code Description Project File Line Suppression State
Warning The primary reference “C:\Users\grollman\Documents\Visual Studio 2019\Projects\WriteToQB\WriteToQB\bin\Debug\WriteToQB.dll” could not be resolved because it has an indirect dependency on the assembly “Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed” which was built against the “.NETFramework,Version=v4.5” framework. This is a higher version than the currently targeted framework “.NETFramework,Version=v4.0”. TestWriteToQB C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets 2081
Library class
Public Sub New()
m_Page = Nothing
dicWinFormsCache = New Dictionary(Of String, String)(StringComparer.OrdinalIgnoreCase)
InitCRCTable()
End Sub
Public Sub New(objPage As System.Web.UI.Page)
m_Page = objPage
InitCRCTable()
End Sub
Public Sub New(dicIn As Dictionary(Of String, String))
dicWinFormsCache = dicIn
InitCRCTable()
End Sub
calling test program error statement:
Severity Code Description Project File Line Suppression State
Error BC30652 Reference required to assembly ‘System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ containing the type ‘Page’. Add one to your project. WriteToQB C:\Users\grollman\Documents\Visual Studio 2019\Projects\WriteToQB\WriteToQB\clsWriteToQB.vb 25 Active
calling test program
Dim m_objclsDataFunctions As clsDataFunctions.clsDataFunctions
Public dicSettings As New Dictionary(Of String, String)
Private ReadOnly Property objclsDataFunctions As clsDataFunctions.clsDataFunctions
Get
If IsNothing(m_objclsDataFunctions) Then
'Dim applicationCache As System.Web.Caching.Cache = System.Web.HttpRuntime.Cache
m_objclsDataFunctions = New clsDataFunctions.clsDataFunctions(dicSettings)
End If
Return m_objclsDataFunctions
End Get
End Property

set and get properties on Shared Libraries

i created a comp.dll for my project and then add the dll to my projects.sln (multiple projects), for every project on projects.sln i added comp.dll, and created 1 mdlmain.vb
Module mdlMain
Public master_FA As New master_FixAsset
Public objComp As New component.clsFunction
End Module
and 1 clsmain.vb to call main form on that project.
in comp.dll i made a property :
Private pubUserName as String
Public Property userName As String
Get
Return pubUserName
End Get
Set(value As String)
pubUserName = value
End Set
End Property
i changed the properties through my login.vbproj (inside projects.sln), but when i tried to get the value of that properties (from fixasset.vbproj) it returns nothing. Is it because i declare New component.clsFunctionin fixasset.vbproj so the compilers (?) create another new object in my .sln ? How can i fix this ?

Remove Properties and Events from UserControl vb.net

I´m devoloment my own userControl with vb.net. I´m new with this task.
I want to remove default properties.
After google, I found several topics, like this:
Removing certain properties in a user control, i.e. forcing one value and not editable in Design mode
So, I´m trying to use it, but doesn´t works for me. I don´t know what I missing or doing wrong.
Public Class MyControlDesigner
Inherits System.Windows.Forms.Design.ControlDesigner
Protected Overrides Sub PreFilterProperties(ByVal properties As System.Collections.IDictionary)
MyBase.PreFilterProperties(properties)
properties.Remove("BackColor")
properties.Remove("ForeColor")
properties.Remove("Font")
End Sub
End Class
<DesignerAttribute(GetType(MyControlDesigner))> _
Public Class MyUserControl
' ...
End Class
To hide overwrite properties I follow this topic Hiding inherited properties and this works fine, for some of them.
<Browsable(False), EditorBrowsable(EditorBrowsableState.Never)> _
Public Shadows Property AutoScroll() As Boolean
Get
Return m_AutoScroll
End Get
Set(ByVal value As Boolean)
m_AutoScroll = value
End Set
End Property
But still, I have other properties that I don´t know how to hide or remove. Like Font, ForeColor, Margin etc...
Thanks advanced
Edit: Once I finish my control, I don´t want to see, all the properties like the picture, Only I want to show mine´s.
Edit: Add code from #Plutonix
I do not have access to that control/tool/property editor, but you can try to use a TypeConverter. This works with a control that inherits from UserControl to hide properties from a Property Grid, but it wont hide them from the VS IDE property editor.
The VS IDE uses reflection to get the property list and apparently ignores the TypeConverter. If your tool does something similar, this wont work - again, I dont have the tool to test it, but it is simple and worth a try.
I created an actual UserControl with a few controls on it. Then:
Imports System.ComponentModel
Public Class YControlConverter
Inherits TypeConverter
Public Overrides Function GetPropertiesSupported(context As ITypeDescriptorContext) As Boolean
Return True
End Function
Public Overrides Function GetProperties(context As ITypeDescriptorContext,
value As Object,
attributes() As Attribute) As PropertyDescriptorCollection
Dim propNames() As String = {"backcolor", "forecolor",
"autoscroll", "autoscrollminsize",
"autoscrollmargin", "autoscrolloffset",
"autoscrollposition"}
Dim pdc As PropertyDescriptorCollection = TypeDescriptor.GetProperties(context.Instance)
' collection to store the ones we want:
Dim myPDCList As New List(Of PropertyDescriptor)
For Each pd As PropertyDescriptor In pdc
If propNames.Contains(pd.Name.ToLowerInvariant) = False Then
myPDCList.Add(pd)
End If
Next
Return New PropertyDescriptorCollection(myPDCList.ToArray())
End Function
End Class
Then decorate your usercontrol with the TypeConverter:
<TypeConverter(GetType(YControlConverter))>
Public Class YControl
This basically runs thru the PropertyDescriptorCollection for the control and filters out the unwanted properties before returning the new collection. If it works, just add the names to the propNames array that you want to hide. View in a PropertyGrid:
As you can see, all the AutoScroll... properties are removed as well as BackColor. The others are gone as well. If the editor will use your TypeConverter instead of reflection, it should work.
--
How to test your TypeConverter using a PropertyGrid. Using a form with a property grid and a button, in the button click:
Dim yp As New YControl
PropertyGrid1.SelectedObject = yp
If the AutoScroll... properties are missing from the prop grid, your TypeConverter works! If they still show in the other tool, it is using reflection like VS.

Serializing and Searching Object Collections

I would appreciate if somebody could answer some questions regarding storing and searching object collections please. If you could give a basic example of any suggestions I would be very grateful.
Storing:
I'm writing an application which needs to search Active Directory for computer objects, and I'm storing them in a collection of objects. I want to save the computer objects collection along with additional information which is not stored in Active Directory (e.g. the computer's MAC address) for the next time the application is run. I also want to save a list of OU's.
Here is my object collection so far (It will have more properties). What is the best method of saving the collection? Preferably not using a database or will saving to a file have a drastic performance impact?
Or is there a better way to do what I have below?
Public Class Computer
Public Property Name As String
Public Property FQDN As String
Public Property Path As String
End Class
Public Class ComputerCollection
Inherits Collections.CollectionBase
Public Sub Add(ByVal computer As Computer) 'Adds a new computer object to the collection
List.Add(computer)
End Sub
End Class
Searching:
I have a layout similar to ADUC with a tree view of OU's and a list view displaying computer objects in the selected OU. The following code loops through the computer object collection checking if the path of the computer object matches the selected OU path and then displays them in the list view.
Is this the best method in terms of performance? or is there a faster way?
Private Sub tvOU_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles tvOU.AfterSelect
lvComputers.Items.Clear()
If tvOU.SelectedNode.Name > "" Then
For Each computerObj In computers
If computerObj.Path.ToString.Replace("CN=" + computerObj.Name + ",", "") = tvOU.SelectedNode.Name Then
Dim lvItem As New ListViewItem
lvItem.Text = computerObj.Name
lvComputers.Items.Add(lvItem)
End If
Next
Else
Exit Sub
End If
End Sub
A simple List(Of Computer) is indeed all you need unless there is some other unknown requirement. Saving is very simple using serialization for this type of thing, and would work the same for a List or Collection<T>.
Imports System.Collections.ObjectModel
Public Class ComputersCollection
Inherits Collection(Of Computer)
' NOT the crude thing in the VB NameSpace
' there is almost nothing to add: item, add and remove
' are in the base class
' ... perhaps saving and retrieving them by a key (name)
' which may do away with the search procedure in the posted code
End Class
Private Computers As New Collection(Of Computer)
' or
Private Computers As New List(Of Computer)
The other part, saving your collection, can be simple with serialization. First, you will have to add the Serializable attribute to your Computer class:
<Serializable>
Public Class Computer
If you forget, you get the error Class foobar is not marked as serializable. Save to disk:
Imports System.Runtime.Serialization
Private myComputerFile As String = ...
Dim bf As New BinaryFormatter
Using fs As New FileStream(myComputerFile , FileMode.OpenOrCreate)
bf.Serialize(fs, Computers)
End Using
Then you can recreate the List or Collection just as easily; this time the List:
' ToDo: add a check to skip if file is not there
' as in the first time run
Dim bf As New BinaryFormatter
Using fs As New FileStream(myComputerFile , FileMode.Open)
Computers = CType(bf.Deserialize(fs), List(Of Computers))
End Using
Alternatively you can use the XML serializer to create an XML File or use the faster, smarter binary serializer is ProtoBuf-Net

vb.net - custom templates issue with databinding expressions in repeater control

I'm new here but I've been browsing stackoverflow for a while when looking for answers.
Here's the problem : I'm trying to implement a custom repeater with multiple conditional templates to avoid as much tests in the templates as possible
As for now my ascx code looks like that :
<custom:Repeater runat="server">
<headerTemplate>...</headerTemplate>
<templates>
<custom:template match="[filter1]"><contents>[filter1] is true for <%# Container.DataItem.ID%></contents></custom:template>
<custom:template match="[filter2]"><contents>[filter2] is true for <%# Container.DataItem.ID%></contents></custom:template>
</templates>
</custom:Repeater>
Besides that this syntax is too verbose, the following code works
<custom:template match="[filter1]"><contents><%# TypeOf Container is IDataItemContainer%></contents></custom:template>
But this code fails
<custom:template match="[filter1]"><contents>[filter1] is true for <%# Container.DataItem.ID%></contents></custom:template>
and I get the error message: : 'DataItem' is not a member of 'System.Web.UI.Control'.
It seems like vb tries to parse the template content at compile time instead of on databinding
Here are my vb classes
<ParseChildren(True, "contents")>
Public Class Template : Inherits WebControl : Implements ITemplate
Private _match As String
<PersistenceMode(PersistenceMode.Attribute)>
Public Property match() As String
Get
Return _match
End Get
Set(ByVal value As String)
'TODO compile filter as an expression
_match = value
End Set
End Property
Private _source As ITemplate
<PersistenceMode(PersistenceMode.Attribute)>
Public Property contents() As ITemplate
Get
Return Nothing
End Get
Set(ByVal value As ITemplate)
_source = value
End Set
End Property
Public Sub InstantiateIn(container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
_source.InstantiateIn(container)
End Sub
End Class
<ParseChildren(True)>
Public Class ApplyTemplate : Inherits Repeater
_template as List(Of Template)
<PersistenceMode(PersistenceMode.InnerProperty), TemplateContainerAttribute(GetType(Template))>
Public Overloads Property templates() As List(Of Template)
Get
Return Nothing
End Get
Set(value As List(Of Template))
_templates = value
End Set
End Property
End Class
How can I add databinding expressions in my templates' content ?
Thanks in advance.
Max.
PS: Would it be possible (and how ;)) to compact the ascx code so it would look like this :
<custom:Repeater runat="server">
<headerTemplate>...</headerTemplate>
<custom:template match="[filter1]">[filter1] is true for <%# Container.DataItem.ID%></custom:template>
<custom:template match="[filter2]">[filter2] is true for <%# Container.DataItem.ID%></custom:template>
...
</custom:Repeater>
At last I had time to work on this again and thanks to this link (http://www.codeproject.com/Articles/21521/Creating-a-Templated-User-Control) I was able to implement my own custom repeater as I wanted to.
So now the aspx code looks like this
<custom:Repeater runat="server" >
<headerTemplate>...</headerTemplate>
<separatorTemplate on="1,9">some advertisement snippet</separatorTemplate>
<separatorTemplate every="2"><hr/></separatorTemplate>
<itemTemplate match="[filter1]"><source>[filter1] is true for <%# Container.DataItem.ID%></source></itemTemplate>
<itemTemplate match="[filter2]"><source>[filter2] is true for <%# Container.DataItem.ID%></source></itemTemplate>
...
</custom:Repeater>
The inner source tag is still necessary to allow code blocks in the template if needed.
If anybody knows how to remove it and still keep the feature with Metadata attributes, please comment.
So for the vb code here are the classes skeleton
Public Class Repeater
Inherits System.Web.UI.UserControl ' I use a UserControl so i can add support any html-bound attributes like class, style, data-*... without hardcoding them in the class
Private templates As New List(Of TemplateItem)
<PersistenceMode(PersistenceMode.InnerProperty)>
Public WriteOnly Property itemTemplate() As TemplateItem
Set(value As TemplateItem)
value.Container = Me 'to bind the container to the template instead of passing the reference on instanciation
templates.Add(value)
End Set
End Property
Public Overrides Sub DataBind()
If Not IsNothing(datasource) Then 'this to avoid nested controls Databind method to be called twice
[... iterate on dataitems]
[... template selection on best matching filters]
templates.instantiateFor(dataitem) ' to instanciate the template for the current item
[... iteration done]
MyBase.DataBind() ' to bind the newly created controls
End If
End Sub
...
End Class
'
<ParseChildren(True, "source")>
Public Class TemplateItem
Inherits Control
Friend Container As Repeater
'handle as many attributes as you want here
Private _matchExpression As String
<PersistenceMode(PersistenceMode.Attribute)>
Public Property match() As String
Get
Return _matchExpression
End Get
Set(value As String)
_matchExpression = value
End Set
End Property
'Now the simple part for parsing the inner code has a template
'I use the standard RepeaterItem class as the template container because i don't need more features for now
Private _source As ITemplate
<PersistenceMode(PersistenceMode.InnerDefaultProperty)>
<TemplateContainer(GetType(RepeaterItem))>
Public Property source() As ITemplate
Get
Return _source
End Get
Set(value As ITemplate)
_source = value
End Set
End Property
'now the part to instantiate as template for a given item
Public Sub instantiateFor(Item As Object, Optional itemIndex As Integer = -1)
Dim instantiator = New RepeaterItem(itemIndex, ListItemType.Item)
instantiator.DataItem = Item
_source.InstantiateIn(instantiator)
Container.Controls.Add(instantiator)
End Sub
End Class
Et voilà... at last !!
Hope this will help some