PIGroup Add / Remove PIUser Example

picture

 

This example, during the Form_Load, connects to the default server, displays the server name, and fills list boxes with the server's users and the server's groups. When a group is selected from the server's groups (List1) the users in that group are displayed in the Group's Users list box (List3). To remove a user from a group, select the group from the Server Groups list box (List1), and select a user from the Group's Users list box (List3), then hit Command 1 (Remove User from Group). The list of users in the group (List3)is refreshed if the removal is successful. To add a user to a group, select the group from the Server Groups list box (List1), and select a user from the Server Users list box (List2), then hit Command2 (Add User to Group). The list of users in the group is refreshed if the add is successful.

 

Build the PIGroup Add/Remove PIUser example as follows:

1. Create a new project and add a reference to the PISDK library.

2. Add the visual elements as shown in the picture. Make sure the numbered element names (label1, list1, &ldots;) match those shown.

3. Cut and paste the code below into the project.

Option Explicit
Dim srv As Server

Private Sub Command1_Click()
'Remove a user from a group
On Error GoTo ErrorHandler
  If List3.Text = "" Then
    MsgBox "Please select a user from the Group's Users list to remove from the group " & List1.Text
    Exit Sub
  End If
  Dim grp As PIGroup
  Set grp = srv.PIGroups(List1.Text)
  grp.RemoveUser List2.Text
  List1_Click
Exit Sub
ErrorHandler:
  MsgBox Err.Description & vbCrLf & Hex(Err.Number)
End Sub

Private Sub Command2_Click()

On Error GoTo ErrorHandler

  'Add a user to the group
  If List2.Text = "" Then
    MsgBox "Please select a user to add to group " & List1.Text
    Exit Sub
  End If
  Dim grp As PIGroup
  Set grp = srv.PIGroups(List1.Text)
  Dim usr As PIUser
  Set usr = srv.PIUsers(List2.Text)
  grp.AddUser usr
  List1_Click
Exit Sub
ErrorHandler:
  MsgBox Err.Description & vbCrLf & Hex(Err.Number)
  
End Sub

Private Sub Form_Load()
On Error GoTo ErrorHandler
  Set srv = Servers.DefaultServer

  ' Open connection with enough permissions to change groups
  srv.Open "UID=piadmin"
  Label1.Caption = srv.Name
  'Load the server's groups and users into list boxes
  Dim grp As PIGroup
  For Each grp In srv.PIGroups
    List1.AddItem grp.Name
  Next
  List1.ListIndex = 0
  Dim usr As PIUser
  For Each usr In srv.PIUsers
    List2.AddItem usr.Name
  Next
Exit Sub
ErrorHandler:
  MsgBox Err.Description & vbCrLf & Hex(Err.Number)
End Sub

Private Sub List1_Click()

On Error GoTo ErrorHandler
  'Show the selected group's users
  Dim grp As PIGroup
  Set grp = srv.PIGroups.Item(List1.Text)
  List3.Clear
  Dim usr As PIUser
  For Each usr In grp.PIUsers
    List3.AddItem usr.Name
  Next
Exit Sub
ErrorHandler:
  MsgBox Err.Description & vbCrLf & Hex(Err.Number)
End Sub
Enabling Operational Intelligence