Part 8. Defining Functions for Custom Connections

To define the DeleteUser member function, you need to instruct the Visual Builder to include user files for the MyGui class in the project configuration, so that you can declare and define the function. These files have the extensions .hpv and .cpv. Then, within the IDE, you can create these files and add the declaration and definition to them.

Follow these steps to define the DeleteUser function:

  1. Switch from the Composition Editor view of the MyGui part to the Class Interface Editor view. You can do this in two ways:
  2. Select the Generated options section of the Class Editor notebook.
  3. The lower left portion of this notebook section shows a group box entitled User files included in generation. In this group box, turn on the first two check boxes, for C++ header file (.hpv) and C++ code file (.cpv).
  4. Press Ctrl+G to generate part source again.

When you do this, #include directives for MyGui.hpv and MyGui.cpv being added to the corresponding MyGui.hpp and MyGui.cpp files generated by the Visual Builder. You can then declare and define your own member functions of the MyGui class in these files from within the IDE, by following these steps:

  1. Switch to the VisualAge C++ IDE window for the project.
  2. Press Ctrl+O or select Open or Create File from the Project Workbook menu.
  3. Enter a new file name, MyGui.hpv. Check the Open as a Workbook Section radio button. Make sure you have not checked the Add to Project option, because the generated MyGui.hpp file already includes this file with an #include directive. Click Open to open the file.
  4. Add the declaration void DeleteUser(); to MyGui.hpv. Notice that you do not need to scope the declaration with its class name, because the generated source includes this file from within the body of the class declaration in MyGui.hpp.
  5. Press Ctrl+S, or select Save File from the Source pull-down menu, to save this file. Because it is not part of the configuration for this project, it will not be automatically saved when you rebuild.
  6. Open another new file, MyGui.cpv, as you did for MyGui.hpv. For now, define the DeleteUser function with an empty body:
    void MyGui::DeleteUser() {
       ;
    }
  7. Save this file also (Ctrl+S).

Rebuild the project. The build should complete successfully, and you can run the executable file, however, if you try the Remove action you will not see any change, because:

Change the MyGui Constructor

In order to have something to remove from the list, you first need to populate the list. The sensible place to do this is during construction of the MyGui object. From the Class Editor you can add code to the start or end of the class constructor; when you generate source code, this code gets inserted at the appropriate location.

You can either enter the complete code within the Class Editor, or you can code a call to a separate user-defined function so that you can then edit your custom code from within the IDE. Since you have already set up your environment to use the .hpv and .cpv files, it makes sense to add the code as a separate member function in these files. It also makes sense to add the code as a separate member function because you may want to populate the list at other times than when the user interface is first loaded. Here are the steps to add a call to the new function:

  1. In the Class Editor view, select the User Code tab.
  2. Select Ending constructor code from the upper left pane.
  3. In the bottom pane, enter PopulateList();. This is a simple function call to the member function, which you will code in the next section.
  4. Press Ctrl+G to generate part source.
  5. Switch to the IDE.
  6. If you already have workbook sections for MyGui.hpv and MyGui.cpv, select the MyGui.hpv section. Otherwise, obtain a source view of this file in the Source Files page of the project section by selecting the source file name in the Source Files view.
  7. Enter the declaration for the constructor add-on code in the source view:
    void PopulateList();

Define the PopulateList Function

  1. Change to a source view of MyGui.cpv as was described for MyGui.hpv in Step 6 above, and add a new class definition for a UserInfo class. You will use this class in the PopulateList function, as well as in other functions you define in MyGui.cpv. Add the following class declaration, which includes inline constructors and member functions:
    class UserInfo {
       public:
          IString Name, Key;
          int Authority;
          UserInfo() : Name(""),Key(""),Authority(0) {}
          UserInfo(IString Line) {
             Key=Line.word(1);
             Authority=Line.word(2).asInt();
             Name=Line.word(3).change("_"," ");
             }
          IString Out() {
             if (Name+Key!="")
                return Key+" "
                       +IString(Authority)+" "
                       +IString::change(Name," ","_")
                       +"\n";
             return "";
          }
       };
  2. Next, add some static variables used by several of the functions you will define. Add these at the top of the MyGui.cpv file:
    UserInfo* UserData=0;
    int UserCount=0;
    int UserMax=32;
  3. Next, define the PopulateList function. This function reads lines from the file containing a list of users, populates an array of user records with the users in the file, and adds the name of each user record as the last line in the list box. Type or paste the following into MyGui.cpv:
    void MyGui::PopulateList() {
       // 1. Define array for holding user information
       if (UserCount==0) UserData=new UserInfo[UserMax];
       // 2. Read in user file information. UserFilepath
       // will be picked up from the macros.hpp file defined
       // for the CGI part of the tutorial. As each valid
       // user is read, add their name to the UserList object.
       ifstream UserFile(UserFilepath);
       while (UserFile) {
          IString UserLine=IString::lineFrom(UserFile);
          if (UserLine.numWords()>=3) {
             // If the array size is reached, double its size
             if (UserCount==UserMax) {
                UserMax*=2;
                UserInfo* tUserData=new UserInfo[UserMax];
                for (int i=0;i<UserCount;i++)
                   tUserData[i]=UserData[i];
                delete[] UserData;
                }
             UserData[UserCount]=UserInfo(UserLine);
             fImpl->iUserList()->addAsLast(UserData[UserCount].Name);
             UserCount++;
          } // end if
       } // end while
       UserFile.close();
    } // end function
  4. The function makes use of the fstream class, and of a preprocessor macro that was defined in the CGI portion of the tutorial in the file macros.hpp. You need to include the fstream.h header file at the top of MyGui.cpv. If you completed the CGI portion of the tutorial, you can include macros.hpp there as well. Otherwise, add a macro definition for UserFilepath. Add parts of the following excerpt to the top of MyGui.cpv depending on your setup. The comments indicate which parts to include:
    #include <fstream.h>
    // If you did not complete the CGI portion of the tutorial,
    // or if it is stored in a different directory than this project,
    // add a macro definition like the following:
    #define UserFilepath IString("f:\\vatutor\\users.dat")
    // Otherwise, include the macros.hpp file:
    #include "macros.hpp"

    Do not add a trailing semicolon to the UserFilepath macro definition.

You can now build your project again, and try out the user interface. Before you run the program, however, try creating the file pointed to by the UserFilepath macro, if that file does not already exist; create it with the following contents:

reader 1 John_Borge
author 3 Ralph_Heinho
reviewer 2 Rachel_Kruger
abcdef 2 Jennifer_Sceeles

If you create it within a Source view in the IDE, remember to save the file.

Run your program; you should see the names of these users displayed in the user list. When you select a name and click Delete, the name is deleted from the list. However, if you exit the program and start it again, all names are still there, because your DeleteUser function does not yet do anything.

Define the DeleteUser Function

Replace the empty DeleteUser() body in MyGui.cpv with the following:

void MyGui::DeleteUser() {
   // Determine what item in list is selected
   unsigned long Index=
    fImpl->iUserList()->selection();
   // If an item was selected...
   if (Index!=IBaseListBox::notFound) {
      // Overwrite existing user file
      ofstream UserFile(UserFilepath);
      // Write out information for all users except this one
      for (int i=0;i<UserCount;i++)
         if (i!=Index) UserFile << UserData[i].Out();
      UserFile.close();
      // Remove all items from list
      fImpl->iUserList()->removeAll();
      // Set UserCount to 0 to force reloading of users
      UserCount=0;
      // Repopulate list
      PopulateList();
   }
}

This function determines which item in the UserList object is selected with the call:

fImpl->iUserList()->selection();

The three parts of this call are:

fImpl
A member of the MyGui class that points to an object of the MyGuiImpl class. MyGuiImpl is an implementation class generated by the Visual Builder, which you use to access the member functions of the user interface controls for the visual part.
iUserList()
A member function of the MyGuiImpl class to access the pointer to the UserList object. The Visual Builder creates member functions of the implementation class to access each user interface part. Each function name consists of a lowercase "i", followed by the name of the part.
selection()
A member of the IBaseListBox class, from which IListBox inherits. This funciton returns the index value (0 to n) of the first selected entry in the list. The IBaseListBox::notFound static value is returned if no entry is selected.

If an item is selected, DeleteUser opens the user data file for output, overwriting its existing content, and writes all user records except the one selected for deletion to the file. It then removes all entries from the UserList object, sets the UserCount variable to zero, and calls PopulateList to repopulate the list with the remaining entries.

It may seem simpler to use the remove function to remove only the selected entry from the list box. However, that entry would remain in the array of UserInfo objects. Resetting the UserCount variable to zero causes PopulateList to overwrite existing array elements when it loads all remaining entries from the user file.

Define Functions for Adding, Editing, and Saving Entries

You still need to add the following user functions:

For each of these functions, you should add a simple connection in the Composition Editor, starting with the buttonClickEvent for the appropriate button, and ending with a Member function connection to a member function whose name matches the appropriate name above. Don't forget to save and generate part source once you have made these connections.

Add the following declarations to MyGui.hpv for these functions:

void AddUser(),
     EditUser(),
     SaveUser();

Define the functions as shown in the sections below. Before you add them, you should add the following to the top of MyGui.cpv, just below the #include directives. The LastEntryEdited variable is used to keep track of which item in the user list was most recently moved to the edit fields, while the AuthLevel and AuthString functions are used to translate either way between integer authority levels and their corresponding strings.

unsigned long LastEntryEdited=IBaseListBox::notFound;

int AuthLevel(IString Auth) {
   if (Auth=="Reviewer") return 2;
   else if (Auth=="Author") return 3;
   return 1;
}

IString AuthString(int level) {
  switch (level) {
     case 1: return "Reader";
     case 2: return "Reviewer";
     case 3: return "Author";
     }
   return "";
}

Define AddUser (MyGui.cpv)

The AddUser function adds the information for the user identified by the two entry fields and the text spin button, provided neither the user's name nor their key has already been added. It then resets the UserCount variable to zero, clears the list box of displayed users, and updates the list. It also resets the LastEntryEdited variable, to prevent you from accidentally overwriting the information for the user you most recently asked to edit with the new user's information.

void MyGui::AddUser() {
// Get the input information for the user
   IString UserName=fImpl->iUserName()->text();
   IString UserKey=fImpl->iUserKey()->text();
   int Authority=AuthLevel(fImpl->iAuthorityLevel()->text());

// Check that this user isn't already in file; return if it is.
   for (int i=0;i<UserCount;i++) {
      if (UserData[i].Key==UserKey) return;
      if (UserData[i].Name==UserName) return;
   }

// Add to the file.
   ofstream UFile(UserFilepath,ios::app);
   UFile << UserKey << " "
         << Authority  << " "
         << UserName.change(" ","_") << endl;
   UFile.close();

// Clear list and force repopulation
   UserCount=0;
   LastEntryEdited=IBaseListBox::notFound;
   fImpl->iUserList()->removeAll();
   fImpl->iUserName()->setText("");
   fImpl->iUserKey()->setText("");
   PopulateList();
}

Define EditUser

The EditUser function determines which user is selected in the user list, and copies the information for that user to the name, key, and authority fields at the right. Because the index of the selected user is stored in the LastEntryEdited variable, this variable is also accessible to the SaveUser function defined below.

void MyGui::EditUser() {
   // Determine the item selected in the list, and save for SaveUser
   LastEntryEdited=
    fImpl->iUserList()->selection();
   // Copy this user's information to the input fields at right
   if (LastEntryEdited!=IBaseListBox::notFound) {
      UserInfo* up=&UserData[LastEntryEdited];
      fImpl->iUserName()->setText(up->Name);
      fImpl->iUserKey()->setText(up->Key);
      fImpl->iAuthorityLevel()->setText(AuthString(up->Authority));
   }
}

Define SaveUser

The SaveUser function uses the value of the LastEntryEdited variable to ensure that the information being saved was actually requested from a call to EditUser, and to determine which element of the UserData array should be changed. It writes all user information out to the file, then forces the user list to be repopulated.

void MyGui::SaveUser() {
   // Make sure this is the last entry requested for editing
   // and that it's within the current array size
   if (LastEntryEdited<UserCount &&
      LastEntryEdited!=IBaseListBox::notFound) {
   // "up" is used as a shorthand for the element we want
      UserInfo* up=&UserData[LastEntryEdited];
   // Get the information from the input fields
      up->Name=fImpl->iUserName()->text();
      up->Key=fImpl->iUserKey()->text();
      up->Authority=AuthLevel(fImpl->iAuthorityLevel()->text());
   // Write the entire file out, replacing old contents
      ofstream UserFile(UserFilepath);
      for (int i=0;i<UserCount;i++)
         UserFile << UserData[i].Out();
      UserFile.close();
   // Update the user list.
      fImpl->iUserList()->removeAll();
      UserCount=0;
      PopulateList();
   }
}

Once you have added this code to MyGui.cpv, rebuild the project (make sure you have done a Save and Generate in the Visual Builder, since the last Visual Builder changes you made). Run the program; you should be able to do the following with the tool:

Congratulations!

You have now completed the Visual Builder portion of the VisualAge C++ tutorial. In this tutorial you learned most of what you will need to know in order to create simple visual user interfaces and to implement C++ code for them. For more in-depth information see the Tasks information in the VisualAge C++ help system. Look under Develop an Application Using Parts for common Visual Builder tasks.

If you have already done the other parts of the tutorial, and you still feel you need more practice, try loading one of the sample projects, either from the Samples navigation in the help system, or from the welcome screen of the IDE.