How to get a value back out from a property in a class - vb.net

I have the following code in my Form1 wherein I will set Value to a property:
Dim login As New logInSession
Dim k As String
login.saveLogInfo = unameTB.Text
and this is my code from my logInSession class where I will store the value:
Private logInfo As String
Public Property saveLogInfo() As String
Get
Return logInfo
End Get
Set(ByVal value As String)
logInfo = value
End Set
End Property
Now, I want to get back out the value to my Form2. The problem is it doesn't return any value. The following is my code:
Dim login As New logInSession
Dim k As String
k = login.saveLogInfo
MsgBox(k)
Can you tell me what's the problem with my codes?

Dim login As New logInSession // HERE
Dim k As String
k = login.saveLogInfo
MsgBox(k)
This code creates a new instance of the logInSession class. Therefore, each time you are trying to access the login.saveLogInfo property, it is at it's default value (empty string). You need to use the original object you created here:
Dim login As New logInSession
Dim k As String
login.saveLogInfo = unameTB.Text

That's because you have two different instances of logInSession class. One in Form1 and another in Form2. Here is an illustration :
Dim login As New logInSession
'you have 1 logInSession instance here, and set it's property
login.saveLogInfo = "Some Text"
Dim anotherLogin As New logInSession
'but later you check property of another instance of logInSession
Dim k = anotherLogin.saveLogInfo
'here you get empty string
Console.WriteLine(k)
'you need to, in some way, pass the first instance instead of creating new instance
Dim referenceToFirstInstance As logInSession = login
k = anotherLogin.saveLogInfo
'here you get "Some Text"
Console.WriteLine(k)
Check this reference on how to pass data between forms

Related

Setting a User Group with an Array using Active Directory Domain Services VB.net

I am trying to figure out how to set Users to an array of groups with Data I pulled from another user. I am in the process of creating a User Creation GUI and I am stuck because I am not sure if the data I have is an acceptable to pass through?
Currently I have the getGroups class which grabs the groups from a user that already exsists in AD. Which is represented in the code below:
Public Function getUserGroups(ByVal Username) As Array
Dim root As DirectoryEntry = New DirectoryEntry("L....")
Dim _objDirSearcher As DirectorySearcher = New DirectorySearcher(root)
_objDirSearcher.Filter = "(&(objectCategory=user)(name=" + Username.ToString() + "))"
_objDirSearcher.PropertiesToLoad.Add("memberOf")
Dim arr As Object = Nothing
Dim arrcol As Object() = Nothing
Try
'get all the user objects matching with the search pattern given
Dim _objResults As SearchResultCollection = _objDirSearcher.FindAll()
'loop with in each object
Dim _objResult As SearchResult
For Each _objResult In _objResults
'Check for properties available
If (Not _objResult Is Nothing) And _objResult.GetDirectoryEntry().Properties.Count > 0 Then
'verify for the mobile property not null
If Not _objResult.GetDirectoryEntry().Properties("memberOf").Value Is Nothing Then
If TypeOf _objResult.GetDirectoryEntry().Properties("memberOf").Value Is Object() Then
arr = CType(_objResult.GetDirectoryEntry().Properties("memberOf").Value, Object())
ElseIf TypeOf _objResult.GetDirectoryEntry().Properties("memberOf").Value Is Object Then
arr = CType(_objResult.GetDirectoryEntry().Properties("memberOf").Value, Object)
End If
Exit For
End If
End If
Next
Catch e As Exception
Return Nothing
End Try
Return arr
End Function
Then I have some code below to add ad user to group this is the part I am unclear if I did right. The Username variable will hold the newly created username and then pass the array of groups from the other user that is currently in format like "CN=group name, ou="test",DC=""...."
Private Sub adUserToGroup(ByVal user As String, ByVal listGroup As Array)
' sDomainName represents the location of your LDAP server
Dim sDomainName As String = "LDAP://ads.yourdomain.edu"
Dim adUserFolder As DirectoryEntry = New DirectoryEntry("LDAP://ads.yourdommain.edu/DC=ads,DC=yourdomain,DC=edu")
' This user is an active directory user and it will need access to write to the group you're trying to add to
adUserFolder.Username = "<insert user to authenticate as>"
adUserFolder.Password = "<insert password>"
Dim adSearch As New System.DirectoryServices.DirectorySearcher(adUserFolder)
For i = 0 To UBound(listGroup)
' bpell being the name of the user that you want to add.
listGroup(i).Properties("member").Add("CN=" + user + ",OU=Accounts,DC=ads,DC=mydomain,DC=edu")
listGroup(i).CommitChanges()
Next
End Sub
Does the code above look correct for what I need it to do. Should I revise it?
I figured it out, I had to break it apart and add the "Children" class to be able to find and access the group. I also made a for loop that strips the "DC" attributes from every string in the array because DC is already established in the LDAP path.
This is the final product. However I may initilize currentgroup out side the for loop as I feel like opening multiple sessions to add value to a group may cause issues.
Private Sub adUserToGroup(ByVal user As String, ByVal listGroup As Array)
Dim de As DirectoryEntry = New DirectoryEntry()
de.Path = "LDAP://domain.com/DC=Test,DC=COM"
de.AuthenticationType = AuthenticationTypes.Secure
de.Username = AuthUser
de.Password = AuthPass
Dim root As DirectoryEntries = de.Children
'1. Create user account
For i = 0 To UBound(listGroup)
Dim currentGroup As DirectoryEntry = de.Children.Find(listGroup(i), "group")
'Dim currentGroup As DirectoryEntry = de.find(listGroup(i))
currentGroup.Properties("member").Add("CN=" + user + ",OU=Employees,OU=Users,DC=test,DC=com")
currentGroup.CommitChanges()
Next
de.Close()
End Sub

About Casting in a Class property in VB.Net

Is it possible to cast a sting in a class property?
what i want to do is that from 'My' class i can fetch the Form's Text properties. but for every form i have to provide the form name statically. I want to do it dyanamically. What i tried is here
Dim frmName As New Object
frmName = Name.ToString()
Dim frmProperty As String
frmProperty = "My.Forms." & frmName & ".Text"
frmNameLabelControl.Text = frmProperty
but at the Front-End it displays 'My.Forms.Form1.Text'
I think that all you need is the following code. But you need to create the equivalent of frmNameLabelControl in the same order in every form. For example to be the last label you created in every form
Dim FormsCount As Integer = My.Application.OpenForms.Count
Dim frmProperty As String
Dim lblContrIndex As Integer = 0 ' Number of label creation in descending order
For i As Integer = 0 To FormsCount - 1
frmProperty = My.Application.OpenForms.Item(i).Text
My.Application.OpenForms.Item(i).Controls.OfType(Of Label).ElementAt(lblContrIndex).Text = frmProperty
Next

VBA class instances

I'm having an issue in VBA where every item in the array is being replaced every time i add something to that array.
I am attempting to go through the rows in a given range and cast every row of that into a custom class (named 'CustomRow' in below example). there is also a manager class (called 'CustomRow_Manager' below) which contains an array of rows and has a function to add new rows.
When the first row is added it works fine:
https://drive.google.com/file/d/0B6b_N7sDgjmvTmx4NDN3cmtYeGs/view?usp=sharing
however when it loops around to the second row it replaces the contents of the first row as well as add a second entry:
https://drive.google.com/file/d/0B6b_N7sDgjmvNXNLM3FCNUR0VHc/view?usp=sharing
Any ideas on how this can be solved?
I've created a bit of code which shows the issue, watch the 'rowArray' variable in the 'CustomRow_Manager' class
Macro file
https://drive.google.com/file/d/0B6b_N7sDgjmvUXYwNG5YdkoySHc/view?usp=sharing
otherwise code is below:
Data
A B C
1 X1 X2 X3
2 xx11 xx12 xx13
3 xx21 xx22 xx23
4 xx31 xx32 xx33
Module "Module1"
Public Sub Start()
Dim cusRng As Range, row As Range
Set cusRng = Range("A1:C4")
Dim manager As New CustomRow_Manager
Dim index As Integer
index = 0
For Each row In cusRng.Rows
Dim cusR As New CustomRow
Call cusR.SetData(row, index)
Call manager.AddRow(cusR)
index = index + 1
Next row
End Sub
Class module "CustomRow"
Dim iOne As String
Dim itwo As String
Dim ithree As String
Dim irowNum As Integer
Public Property Get One() As String
One = iOne
End Property
Public Property Let One(Value As String)
iOne = Value
End Property
Public Property Get Two() As String
Two = itwo
End Property
Public Property Let Two(Value As String)
itwo = Value
End Property
Public Property Get Three() As String
Three = ithree
End Property
Public Property Let Three(Value As String)
ithree = Value
End Property
Public Property Get RowNum() As Integer
RowNum = irowNum
End Property
Public Property Let RowNum(Value As Integer)
irowNum = Value
End Property
Public Function SetData(row As Range, i As Integer)
One = row.Cells(1, 1).Text
Two = row.Cells(1, 2).Text
Three = row.Cells(1, 3).Text
RowNum = i
End Function
Class module "CustomRow_Manager"
Dim rowArray(4) As New CustomRow
Dim totalRow As Integer
Public Function AddRow(r As CustomRow)
Set rowArray(totalRow) = r
If totalRow > 1 Then
MsgBox rowArray(totalRow).One & rowArray(totalRow - 1).One
End If
totalRow = totalRow + 1
End Function
Your issue is using
Dim cusR As New CustomRow
inside the For loop. This line is actually only executed once (note that when you single F8 step through the code it does not stop on that line)
Each itteration of the For loop uses the same instance of cusR. Therefore all instances of manager added to the class point to the same cusR
Replace this
For Each row In cusRng.Rows
Dim cusR As New CustomRow
with this
Dim cusR As CustomRow
For Each row In cusRng.Rows
Set cusR = New CustomRow
This explicitly instantiates a new instance of the class

Get ValueMember of Selected item in ListBox

I've seen a couple of posts asking a similar question but I have not been able to duplicate the answers in my code successfully.
The following code adds items and their value member to a list box.
Public Shared Sub ListFiles(hTab As Hashtable)
Debug.Print("create file and key" & Now)
Dim Enumerator As IDictionaryEnumerator
Enumerator = hTab.GetEnumerator()
Dim MyKeys As ICollection
Dim Key As Object
MyKeys = hTab.Keys()
If (hTab.Count > 0) Then
For Each Key In MyKeys
Dim sfileName As String = hTab(Key)
Dim first As Integer = sfileName.IndexOf("_")
Dim last As Integer = sfileName.LastIndexOfAny("_")
Dim first2 = (first + 1)
Dim splitFile = sfileName.Substring(first2)
frmViewFiles.ListBox1.Items.Add(splitFile)
frmViewFiles.ListBox1.ValueMember = Key
frmViewFiles.ListBox1.SelectedValue = Key
Next
End If
End Sub
When I run my code to get the selected items value member
Dim file = ListBox1.ValueMember.ToString()
I can acess the first item I choose but subsequent selections dont change the value member to that of the selected item.
Please direct me.
Thank you for your answers. this is my new code:
Public Shared Sub runListFiles(CustomerId As String)
Dim cfp As New CloudFilesProvider(cloudId)
Dim containerObjectList As IEnumerable(Of ContainerObject) = cfp.ListObjects(container:="EstherTest", identity:=cloudId, prefix:=CustomerId & "_")
For Each file As ContainerObject In containerObjectList
Dim sFullFileName As String = file.Name
Dim first As Integer = sFullFileName.IndexOf("_")
Dim first2 = (first + 1)
Dim splitFile = sFullFileName.Substring(first2)
'frmViewFiles.ListBox1.Items.Add(splitFile)
'frmViewFiles.ListBox1.ValueMember = sFullFileName
Dim fb = New myFile
fb.FileName = splitFile
fb.FullPath = sFullFileName
frmViewFiles.ListBox1.Items.Add(fb)
frmViewFiles.ListBox1.DisplayMember = fb.FileName
frmViewFiles.ListBox1.ValueMember = fb.FullPath
This is my class:
Public Class myFile
Public Property FileName As String
Public Property FullPath As String
Public Sub New(f As String, b As String)
FileName = f
FullPath = b
End Sub
End Class
Please see my comment below and assist
ValueMember is supposed to indicate the property name of an object added to the Items collection: the property to use as the actual value for the items in the ListControl.
You are not adding objects to the control, so Key from the hashtable is meaningless as the ValueMember. Your post references a file variable in passing, so I will assume this revolves around showing the filename while wanting to get the full pathname when selected/clicked. WebForms/Winforms/WPF was not indicated, I am assuming WinForms:
Public Class myFile
Public Property FileName As String
Public Property FullPath As String
Public Property FileSize As Int64 ' just so there is something else
Public Sub New(f as String, p as String, s as Int64)
FileName = f
FullPath = b
FileSize = s
End Sub
End Class
Lets say we want to add some of these to a ListBox, for each item added we want FileName to display as the text, but want to get them back by FullPath:
Dim f As myFile
' assume these come from a fileinfo
For Each fi as FileInfo in DirectoryInfo.GetFiles(searchFor)
f = New myFile
f.FileName = fi.Name
f.FullPath = fi.FullPath
f.FileSize = fi.Length
' myFile accepts all the prop values in the constructor
' so creating a new one could also be written as:
' f = New myFile(fi.Name, fi.FullPath, fi.Length)
myListBox.Items.Add(f)
Next n
If the myFile objects were stored to a List(of myFile) rather than adding them to the control, we can bind the List as the DataSource and not have to iterate or copy:
mylistBox.DataSource = myFileList
Either way, Display- and ValueMember refer to the property names we wish to use:
myListBox.DisplayMember = "FileName" ' indicate property name of obj to SHOW
myListBox.ValueMember = "FullPath" ' prop name of object to return
When you select a listbox item, myListBox.SelectedValue would refer to the FullPath of the myFile object clicked on. The SelectedIndex would still refer to the index of the item in the list.
tl;dr
ValueMember and DisplayMember refers to the Property Names of Objects represented in the list.
Note:
I know this is many years later, but still relevant information.
It took me a while to parse what was said above, until I grokked it fully, so I thought it might help if I restated it slightly.
When you select a listbox item,
myListBox.SelectedValue is the contents of the field, myListBox.ValueMember. ValueMember contains the Field Name, SelectedValue contains the contents of the field.
myListBox.SelectedItem is the contents of the field myListBox.DisplayMember. DisplayMember contains the field name and SelectedItem contains the value of the field.
The SelectedIndex refers to the index of the item in the list. To see which item is selected, reference myListBox.SelectedIndex. You can, for example, change the selection to the last item in the list by using myListBox.SelectedIndex = myListBox.Items.Count - 1
If you want to display the values, then
Console.WriteLine("The value of {0} is {1}",myListBoxDisplayMember,myListBox.SelectedItem)
Console.WriteLine("The Value of {0} is {1}",myListBox.ValueMember,myListBox.SelectedValue)

accessing variable from within a different sub

I have this,
Public Class posData
Public Property strLabel As String
Public Property strX As String
Public Property strY As String
Public Property blnAvail As Boolean
Public Sub New(ByVal strLabelID As String, ByVal X As Integer, ByVal Y As Integer)
Me.strLabel = strLabelID
' Format = "<PinX F='53mm'></PinX>", "<PinY F='204mm'></PinY>"
Me.strX = "<PinX F='" & X.ToString & "mm'></PinX>"
Me.strY = "<PinY F='" & Y.ToString & "mm'></PinY>"
Me.blnAvail = True
End Sub
End Class
Im utilzing this within another sub to build a list called PosList..
Public Sub SetUpCoords(ByRef PosList As HashSet(Of posData))
Dim a1 As New posData("a1", X_coords(0), Y_coords(0))
Dim a2 As New posData("a2", X_coords(1), Y_coords(0))
Dim a3 As New posData("a3", X_coords(2), Y_coords(0))
and so on and so on, however i want to call this method and populate the list in my button click sub so i have added this in my button click event.
Dim MyPosList As New HashSet(Of posData)
SetUpCoords(MyPosList)
then i want to loop through all the objects within my list so i have a for each position in posList, inside this is where the problem occurs, i want to be able to write something like this, a1.blnavail, this is not happening however, i know i can use position.blnavail but i need to hardcode the position for my logic to work correctly, what am i doing wrong?
thanks :)
Couldn't you use another data structure, like a Dictionary, that uses a key? You could then key each item with a1 etc. and access the items in a for loop using the key.