How to enumerate My.Setting.Connectionstring in custom control Combobox - vb.net

I am creating a custom control of type Textbox, and I want to create a combobox property that enumerates all the connections available in the project setting "Connection String".
I am using this code. As you can see, I commented non-working code while I was trying.
Private _formatString As String = Nothing
<Category("Display")>
<DisplayName("Connection")>
<Description("Connection string.")>
<DefaultValue("")>
<TypeConverter(GetType(FormatStringConverter))>
Public Property Connection As String
Get
Return _formatString
End Get
Set(ByVal value As String)
_formatString = value
End Set
End Property
Public Class FormatStringConverter
Inherits StringConverter
Public Overrides Function GetStandardValuesSupported(ByVal context As ITypeDescriptorContext) As Boolean
Return True
End Function
Public Overrides Function GetStandardValuesExclusive(ByVal context As ITypeDescriptorContext) As Boolean
Return True
End Function
Public Overrides Function GetStandardValues(ByVal context As ITypeDescriptorContext) As TypeConverter.StandardValuesCollection
Dim list As List(Of String) = New List(Of String)()
'For Each current In Configuration.ConfigurationManager.ConnectionStrings
' list.Add(current.Name)
'Next
'For Each value As Configuration.SettingsPropertyValue In My.Settings.PropertyValues
' 'MessageBox.Show(value.Name & " - " & value.PropertyValue.ToString)
' 'list.Add(value.Name & " - " & value.PropertyValue.ToString)
'Next
list.Add("")
list.Add("Currency")
list.Add("Scientific Notation")
list.Add("General Number")
list.Add("Number")
list.Add("Percent")
list.Add("Time")
list.Add("Date")
Return New StandardValuesCollection(list)
End Function
End Class
I want to enumerate the connection strings in the project I placed the control in.
The custom control is in a separate project, not the same project of the form I am using.
[edit]
I cannot see the expected results at design-time. I want to choose the connection from a combobox same as tableadapter in dataset table adapter connection selection from combobox at design time. So I want to read and set the connection list available in a form belong to the project I placed the custom textbox in at design time.

Related

For a combobox with item = a datarow, how to point ValueMember to one of it's columns

I add items to a combobox like this:
For each R as DataRow in MyDataTable.Rows
If R("ID") > 10 then MyCombo.Items.Add(R)
Next
And now I need to set the DisplayMember and ValueMember to a column of the datarow:
MyCombo.ValueMember = R("ID")
MyCombo.DisplayMember = R("Name")
I know it doesn't make sence to to use "R" as it doesn't reference to anything at this point but it's just to make an indication of what I mean ;-)
The documentation for ValueMember says:
"A String representing a single property name of the DataSource property value, or a hierarchy of period-delimited property names that resolves to a property name of the final data-bound object"
I know I can add the rows to a new datatable and set it to the DataSource, but as you can add any object to the combobox items, it would be nice to use the rows directly, just can't figures out how to make a reference the particular column as a string.?
Maybe you cannot use a row object directly. I guess to use Valuemember you need your item objects to be wrapped in a collection which implement an ilist interface.
In the old MS-Access days combobox items had natively Display- and ValueMember properties, I've always missed that in the .Net combobox control.
My work-around is to use this class, which then can be used for all your ComboBoxes:
Class oComboItems
Public items As New List(Of oDVpairs)
Class oDVpairs
Implements IComparable(Of oDVpairs)
Private myDM As String
Private myVM As Object
Sub New(DM As String, VM As Object)
myDM = DM
myVM = VM
End Sub
Public ReadOnly Property DM() As String
Get
Return myDM
End Get
End Property
Public ReadOnly Property VM() As Object
Get
Return myVM
End Get
End Property
Public Function CompareTo(other As oDVpairs) As Integer Implements IComparable(Of oDVpairs).CompareTo
Return Me.myDM.CompareTo(other.myDM)
End Function
End Class
Public Sub AddItems(DisplayMember As String, ValueMemeber As Object)
items.Add(New oDVpairs(DisplayMember, ValueMemeber))
End Sub
Public ReadOnly Property DisplayMember() As String
Get
Return "DM"
End Get
End Property
Public ReadOnly Property ValueMember() As Object
Get
Return "VM"
End Get
End Property
End Class
And now add my datarows(or any other objects) to the ComboBox:
Dim CI As New oComboItems
For Each R As DataRow In DT_U.Rows
If R("medlnr") > 10 Then
CI.AddItems(R("name"), R("ID"))
end if
Next
CI.items.Sort()
MyCombo.DataSource = CI.Items
MyCombo.DisplayMember = CI.DisplayMember
MyCombo.ValueMember = CI.ValueMember

Why does ListBox not display objects correctly?

I have a listbox and a class.
The class is called CTS_Warnings_List
And the listbox is called lbpropWarningFacList
Here is the class:
Public Class CTS_Warnings_List
Public _Warning As String
Public _WarnID As Integer
Public Property Warning() As String
Get
Return _Warning
End Get
Set(ByVal value As String)
_Warning = value
End Set
End Property
Public Property WarnID() As Integer
Get
Return _WarnID
End Get
Set(ByVal value As Integer)
_WarnID = value
End Set
End Property
Sub New(ByVal Warning As String, ByVal WarnID As Integer)
Me.Warning = Warning
Me.WarnID = WarnID
End Sub
End Class
So now I want to add a new item to the listbox. So I tried this:
Dim llist As New CTS_Warnings_List("K", 8)
lbpropWarningFacList.Items.Add(llist)
I also tried this:
lbpropWarningFacList.Items.Add(New CTS_Warnings_List("K", 8))
When I run the app and add these to the listbox, in each case I get this displayed in the listbox:
NameOfApplication.NameOfClass
as the display in the listbox.
What am I doing wrong?
Thank you
Listboxes only knows how to display strings.
Therefor, when you add an item of any type to the listbox, it displays the value it gets by calling the items ToString() method.
You should override the ToString() method or simply enter items as strings in the first place.
In your case, add this to your class:
Public overrides function ToString() as string
return Me.Warning & " " & Me.WarnID.ToString()
End Function
You are sending a CTS_Warnings_List object to a listbox. How does the listbox know what to do with that object? It doesn't know what to do with that object. If you want to send the properties of the object to the listbox, then you have to do something like:
lbpropWarningFacList.Items.Add(llist._WarnID & ": " & llist.Warning)
Thanks for the responses. But I found that if I add
NameOfListBox.DisplayMemeber = "PropertyOfClass"
NameOfListBox.ValueMember = "PropertyOfClass"
By just adding this it now shows the correct data in the listbox.

How Do I loop through this class once I have added items

How do i loop through this class once I add items via this method. Just I am quite new to generic lists so was wonding if someone could point me in right direction in datatables im used to doing the following:
For Each thisentry In dt.rows
Next
What do I use in collections
Calling Code
Calling this in my delciarations of main class
Dim infoNoProductAvail As List(Of infoProductsNotFound) = New List(Of infoProductsNotFound)()
this is how i am adding the files but I have checked in the routine and the count for the list is at 2 products
If medProductInfo.SKU.SKUID = 0 Then
infoNoProductAvail.Add(New infoProductsNotFound(thisenty2.Item("EAN13").ToString(), True))
End If
this is the class itselfs
Public Class infoProductsNotFound
Public Sub New(tbcode As String, notfound As Boolean)
Me.tagbarcode = tbcode
Me.notfound = notfound
End Sub
Private tagbarcode As String = String.Empty
Private notfound As Boolean
Public Property tbcode() As String
Get
Return tagbarcode
End Get
Set(ByVal value As String)
tagbarcode = value
End Set
End Property
Public Property isNotFound() As Boolean
Get
Return notfound
End Get
Set(ByVal value As Boolean)
notfound = value
End Set
End Property
End Class
Tried
I tried using the following
Function BuildExceptionsForEmail()
Dim retval As String = ""
Dim cnt As Int32 = 0
retval = "The following products are not avialable" & vbCrLf
For Each info As infoProductsNotFound In infoNoProductAvail
retval &= info.tbcode
cnt &= 1
Next
Return retval
but for some reason at this point my info noproductAvail is blank even though in the routine above its sitting at count of 2 what gives?
First I'd shrink that declaration a bit:
Dim infoNoProductAvail As New List(Of infoProductsNotFound)
Next, to iterate there are several options. First (and what you're likely most used to):
For Each info as infoProductsNotFound in infoNoProductAvail
If info.tbCode = "xyz" Then
DoSomething(info)
End If
Next
Or you might want to use lambda expressions (if you're using .Net 3.5 and above I think - might be .Net 4):
infoNoProductAvail.ForEach (Function(item) DoSomething(item))
Remember that generics are strongly typed (unlike the old VB collections) so no need to cast whatever comes out: you can access properties and methods directly.
If infoNoProductAvail(3).isNotFound Then
'Do something
End If
(Not that that is a great example, but you get the idea).
The For Each syntax is the same. It works the same way for all IEnumerable objects. The only "trick" to it is to make sure that your iterator variable is of the correct type, and also to make sure that you are iterating through the correct object.
In the case of the DataTable, you are iterating over it's Rows property. That property is an IEnumerable object containing a list of DataRow objects. Therefore, to iterate through it with For Each, you must use an iterator variable of type DataRow (or one of its base classes, such as Object).
To iterate through a generic List(Of T), the IEnumerable object is the List object itself. You don't need to go to one of it's properties. The type of the iterator needs to match the type of the items in the list:
For Each i As infoProductsNotFound In infoNoProductAvail
' ...
Next
Or:
Dim i As infoProductsNotFound
For Each i In infoNoProductAvail
' ...
Next
Or:
For Each i As Object In infoNoProductAvail
' ...
Next
Etc.

How do I get VBCodeProvider to return an object

I have a program that allows users to setup a client/server to control/run commands from a remote location. Now i'm trying to implement server plugins, and I'm doing that by loading every .vb file in a folder contained inside the current running directory. Everything is great, and the code from the external files compiles just fine... Only problem is, Its returning nothing when I try to compile the script and use one of the methods inside it.
Here's some code for you to check out. My error is in the 2nd. Any idea on how to fix this?
The Interaction Interface:
Public Interface LinkingInterface
Property name As String
Property statetag As String
Sub selected(ByVal Sock As Integer)
Sub deselected(ByVal Sock As Integer)
Sub load()
Function generateOutput(ByVal input As String, ByVal Sock As Integer) As String
End Interface
Detection/Loading of the "Modes" (add-ins):
For Each file In My.Computer.FileSystem.GetFiles("modes\")
Dim thisMode As LinkingInterface = LoadMode(My.Computer.FileSystem.ReadAllText(file))
thisMode.load() '<---------------------------My error is here, saying its a null ref.
modes_InterfaceCollection.Add(thisMode) 'Public modes_InterfaceCollection As New Microsoft.VisualBasic.Collection()
modes_nameIndex.Add(thisMode.name) 'Public modes_nameIndex As New Specialized.StringCollection()
Next
'LoadMode' Function
Public Function LoadMode(ByVal code As String) As LinkingInterface
Using provider As New VBCodeProvider()
Dim parameters As New CompilerParameters()
parameters.GenerateInMemory = True
parameters.ReferencedAssemblies.Add(Reflection.Assembly.GetExecutingAssembly().Location)
parameters.MainClass = "Remote_Command_Line.MainModule"
Dim interfaceNamespace As String = GetType(LinkingInterface).Namespace
Dim codeBuilder As New Text.StringBuilder
Dim namespaces() As String = New String() {"Microsoft.VisualBasic", "System", "System.Console", "System.Collections", "System.Collections.Generic", _
"System.Data", "System.Diagnostics", "Remote_Command_Line.MainModule"}
Dim codeString As New StringBuilder
For Each namespacestring As String In namespaces
codeString.AppendLine("Imports " & namespacestring)
Next
codeString.AppendLine(code)
Dim results As CompilerResults = provider.CompileAssemblyFromSource(parameters, codeString.ToString)
'I commented out this just for debugging purposes
'If results.Errors.HasErrors Then
'For Each scriptError As CompilerError In results.Errors
'WriteLine(scriptError.ToString)
'Next
'Else
Return CType(results.CompiledAssembly.CreateInstance(results.CompiledAssembly.GetType.Name), LinkingInterface)
'End If
End Using
End Function
The Testing file 'test.vb':
Public Class test_mode
'Designed for RCL mode 1.0b
'Matthew 2013
'used for managing the local filesystem.
'####################################
#Region "Properties"
'all of these properties listed are required --------------------
Implements LinkingInterface
Property name As String Implements LinkingInterface.name 'the name the client refers to you in the 'modeswitch' command
Property statetag As String Implements LinkingInterface.statetag 'short tag displayed on the client when active before the input signal '>'
'----------------------------------------------------------------
Public curDirDatabank As New Specialized.StringCollection()
#End Region
'####################################
'####################################
#Region "Subs"
'Its required to have, but not required to do anything. This load sub is here for any modes that may require an initialization
Private Sub load() Implements LinkingInterface.load 'REQUIRED
name = "file" : statetag = "file"
MsgBox("Testing: It's loaded")
End Sub
Private Sub selected(ByVal Sock As Integer) Implements LinkingInterface.selected
MsgBox("Testing: '" & Sock & "' selected the File mode")
End Sub
Private Sub deselected(ByVal Sock As Integer) Implements LinkingInterface.deselected
MsgBox("Testing: '" & Sock & "' deselected the File mode")
End Sub
Private Function generateOutput(ByVal input As String, ByVal Sock As Integer) As String Implements LinkingInterface.generateOutput 'REQUIRED
Return ("Testing: '" & Sock & "' said '" & input & "'")
End Function
#End Region
'####################################
End Class
the following line is wrong.
Return CType(results.CompiledAssembly.CreateInstance(results.CompiledAssembly.GetType.Name), LinkingInterface)
You need to search through the loaded classes for one implementing your interface (it being VB you automatically get classes generated for the My namespace objects such as My.Computer)
Try this instead
For Each t As Type In results.CompiledAssembly.GetTypes()
If t.GetInterface(GetType(LinkingInterface).Name) IsNot Nothing Then
Return CType(results.CompiledAssembly.CreateInstance(t.Name), LinkingInterface)
End If
Next
Return Nothing

VB.net creating new AD user account using UserPrincipalEx?

I'm having a heck of a time trying to add fields like department and title.
I'm using this to create a user account:
Dim ctx As New PrincipalContext(ContextType.Domain, "domain.name.pvt", "OU=Users,DC=global,DC=pvt")
Dim usr As UserPrincipal = New UserPrincipal(ctx)
I have no problem creating the account but can't add simple things like Department and Title. I read about using extensions but its in C++ and have no clue on how to do it.
Any help would be great!!! Thanks!
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
To extend the UserPrincipal class, you don't need much - something like this will suffice (I wrote this in C# originally and just converted it to VB.NET on the 'net - I hope there's no issues with the VB.NET code!)
Imports System.DirectoryServices.AccountManagement
Namespace ADExtended
<DirectoryRdnPrefix("CN")> _
<DirectoryObjectClass("Person")> _
Public Class UserPrincipalEx
Inherits UserPrincipal
' Inplement the constructor using the base class constructor.
Public Sub New(context As PrincipalContext)
MyBase.New(context)
End Sub
' Implement the constructor with initialization parameters.
Public Sub New(context As PrincipalContext, samAccountName As String, password As String, enabled As Boolean)
MyBase.New(context, samAccountName, password, enabled)
End Sub
' Create the "Department" property.
<DirectoryProperty("department")> _
Public Property Department() As String
Get
If ExtensionGet("department").Length <> 1 Then
Return String.Empty
End If
Return DirectCast(ExtensionGet("department")(0), String)
End Get
Set
ExtensionSet("department", value)
End Set
End Property
' Create the "Title" property.
<DirectoryProperty("title")> _
Public Property Title() As String
Get
If ExtensionGet("title").Length <> 1 Then
Return String.Empty
End If
Return DirectCast(ExtensionGet("title")(0), String)
End Get
Set
ExtensionSet("title", value)
End Set
End Property
' Implement the overloaded search method FindByIdentity.
Public Shared Shadows Function FindByIdentity(context As PrincipalContext, identityValue As String) As UserPrincipalEx
Return DirectCast(FindByIdentityWithType(context, GetType(UserPrincipalEx), identityValue), UserPrincipalEx)
End Function
' Implement the overloaded search method FindByIdentity.
Public Shared Shadows Function FindByIdentity(context As PrincipalContext, identityType As IdentityType, identityValue As String) As UserPrincipalEx
Return DirectCast(FindByIdentityWithType(context, GetType(UserPrincipalEx), identityType, identityValue), UserPrincipalEx)
End Function
End Class
End Namespace
Now, you just use the UserPrincipalEx class:
Dim ctx As New PrincipalContext(ContextType.Domain, "domain.name.pvt", "OU=Users,DC=global,DC=pvt")
Dim usr As UserPrincipalEx = New UserPrincipalEx(ctx)
usr.Title = "......."
usr.Department = "......."
The new S.DS.AM makes it really easy to play around with users and groups in AD!