Sunday, March 11, 2012

Beginners Guide to the CA Plex Model API using C# .NET - Part IV – ‘Some DotNet Tips and Tricks’


I have written about the inspiration behind using the ModelAPI and alluded to some good examples of where it is being used in the real world including my own ‘Entity Creator’ project.

I have covered the concepts behind the ModelAPI and its relation to the Plex IDE and in particular to the Model Editor and Object Properties windows in Plex which are critical in helping you understand the ModelAPI.

I have blogged about some of the methods that are available to Plex developers to manipulate and extract information from the underlying model.  

Plex 7.0 is here now (available via electronic download and going GA soon) and it introduces 5 new methods that would be useful for us ModelAPI converts.


  • FindRealObj
  • FindOrAddRealObj
  • ShowObjHelp
  • GetObjSurrogate
  • GetObjPackageName


To my surprise after a count in Plex 7.0 (Version 4.0 of the Model API) there is now a staggering 92 methods and I have enhancement requests in the pipeline for a further 3.

The Tutorial

Part IV in this series I promised to walk you through a C#.NET tutorial for building your first (basic) ModelAPI program outside of Plex.  If you prefer to use Java or even Plex then some of the concepts and the code outline will help but you are on your own from the implementation syntax perspective.

To keep it simple we are going to create a standard WinForm application.  

Assumptions

This tutorial assumes you are using CA Plex 6.1 and will work with all build levels.  If you are serious about the ModelAPI then upgrade to build 32 ASAP, there have been lots of improvements made in the API and some critical fixes to some of the methods.  You could also upgrade to 7.0 too.

Visual Studio 2008 is used in this tutorial.  I would suggest that 2010 can also be used although the screen layouts and some menu options may differ.  

Directory locations implied or pictured may need to be altered for your environment depending on your own personal setup.

I assume that you have some Visual Studio programming knowledge and are aware of the control types of TextBox, Label and DataGridView and basic syntax like declaring of fields in C#.  However, I think that you will be able to follow this through as I have written with the 100% novice in mind.
Disclaimer

This is my crappy C# coding.  I haven’t been formally trained and there may be better ways of achieving some of the coding I have created but I am willing to receive feedback and will adjust as required.

Let the tutorial begin.

A screen print of the finished tutorial is below so you know what you are creating and you can add your controls to forms canvas in a similar manner. 



Links to these posts, a PDF document consolidating all posts and a ZIP archive for the completed source code will be available on the Plex Wiki.

1. Create a new folder on your C:\ called C:\PlexTutorials
2. Open Visual Studio
3. From the main menu select File, New, Project
4. Complete the New Project dialog as follows



Note: If C# doesn’t appear then you will need to look at your Visual Studio installation.  
Also understand that your screen might be slightly different depending on what project templates you have installed in your environment.

5. Click Ok to confirm
6. Your screen should like something like this



The key windows are Toolbox, Solution Explorer and Properties.  If you don’t get these showing you can toggle them on via the View menu or by using the keyboard shortcuts.



If these are not shown it might be that they are hidden on the screen.  In which case like this example with a hidden toolbox you need to click as below.



You need to click the Toolbox tab and it will automatically reveal.  Then just toggle the Auto Hide option.



GUI Layout

7. If you haven’t already, click on the Form1 in the main canvas.  It will now have the control handles around the outside if you have, then  adjust the following properties in the properties window (See screen below) – Note they are in bold if different from the default.  Same as Plex and the L (local) override indicator.
a. Text = Show Field Triples
b. Size = 600,400




8. Now let’s add the controls we need to the Form.  In the Toolbox click on the Label control and drag it across to the canvas, let go of mouse and then set its properties as follows
a. Text = Field name:

9. Now add a TextBox next to the label on the Form and set the following properties (Remember the complete image above)
a. Name = TextBoxFieldName
b. Size = 250,20
10. Now ‘Double Click’ the Button control in the ToolBox and it will automatically be added to the Form.

11. Now drag this new button to be to the right of the TextBox just added and set its properties as follows:-
a. Name = ButtonShowTriples
b. Text = Show Triples
c. Size = 100,23

The Form should look something like this...




12. Now add a DataGridView (Grid) control to the Form.  These are located further down the toolbox in the Data folder.  Add to the form and accept the defaults from the DataGridView Tasks pane for now.

13. If not selected, select the grid and set the following properties:-
a. Size = 560,280
b. Location = 14,70
c. Name = GridTripleDetails
d. AllowUserToAddRows = False
e. AllowUserToDeleteRows = False

14. You will notice that the Grid has a small right facing arrow at the top right hand side.  Click this to show the Tasks pane again and then select Edit Columns... to bring up the editor for the grid control.  (The tasks pane shows the most common properties and editor for a particular control).





15. Currently we have no columns.  As you can see with our completed project we want one column in the Grid called Triple Details where we show the full triple details for the YesNo field.

16. Click Add to add a new column and complete the Add Column dialog as below and the press Add button.



17. Now click the Close button to close the Add Column dialog which returns you to the edit Columns dialog.

18. Now set the Column Width property to 500 and press the OK button to close.

19. Your form should now have a Grid Header row with ‘Triple Details’ and the width of the field should cover most of the grid.

20. That’s it for now with the Form Design to this would be a good time to save progress so far using the familiar save icon on the toolbar.


Coding

Now for the coding but before we start I’ll give you a quick overview of what we are about to do.

We are going to declare the Plex ModelAPI and then instantiate it in C#.
Then we are going to write the code that reacts to the ‘Show Triples’ button being pressed.  As with Plex we link the act of clicking the button to a logical event that executes the code.  If you have used Visual Basic or Access you would have done this a hundred times.

21. Right click anywhere on the Form but not on a control and select the View Code menu shortcut.


If you have more menu items than this then it is likely you have selected a control and NOT the form.  Anyhow, View code will open a new tab and show the Form as Code View.  It should as below.





22. In order to program against the CA Plex Model API COM Component Visual Studio must know about it.  This is what we call a reference.

23. In the Solution Explorer window (The one on the right hand side of the code window), right click on the ShowFieldTriples project and the select ‘Add Reference’ menu option.  You could also have selected Project from the Main Menu and selected Add Reference from there.



24. WAIT....This will bring up the Add Reference dialog but depending on the speed of your system and the number of potential references that can be added this might take a few seconds to appear (over 30 seconds elapsed on my laptop).  See below.


If you have by now upgraded to Plex 7.0 then this might say PlexAPI 4.0 Type Library (Depending on what CA do here).

25. Click on COM tab and then scroll down to select the PlexAPI Library.
26. Click OK to add the reference.
27. PlexAPILib should now appear in the Solutions explorer under the References folder.



28. Back to the Code View tab and immediately under the last using statement enter the following.


using PlexAPILib; //Declare Plex Model API

29. After

public Form1()
        {
            InitializeComponent();
  }

        Enter

    //Instantiate a version of the Model API in memory and refer to it as "_Plex" from now on.
    private static PlexAPIClass _Plex = new PlexAPILib.PlexAPIClass();

Note:  For Visual Studio 2010 you will need the following instead.

    //Instantiate a version of the Model API in memory and refer to it as "_Plex" from now on.
    private static PlexAPI _Plex = new PlexAPILib.PlexAPI();

30. Your code should now look like this


Screen print is for Visual Studio 2008 solution – see note above.

Recap.

Now Visual Studio references the Plex API and will load a copy of the interface into memory when the application is run and is named _Plex.  All we have to do now is react to the form and interrogate the model via the API methods and display them in the grid.  Simple!!!!


31. Click on the Form1.cs [Design] tab above your code window
32. Double Click the Show Triples button to create the ButtonShowTriples_Click event handler.  The following should now be shown in your code window.

        private void ButtonShowTriples_Click(object sender, EventArgs e)
        {


        }

33. Position your cursor between the braces and enter the following.

        //This is the area where I declare ALL the variables that are used by this program
        int MyFieldObjID = 0;

The MyFieldObjID field above may be underlined green (like the Word grammar checker) at this point. Don’t worry about this, this is just Visual Studio telling you that a field has been declared but is not used.

As mentioned in a previous post all objects in CA Plex have a unique internal number.  In order to obtain this we use the FindObj method from the ModelAPI.  You will recall it takes three parameters the object name, object type and returns the ID of the object.

34. Leave a couple of lines gap after the last entry and now let’s enter the following code snippet.

       _Plex.FindObj(TextBoxFieldName.Text.Trim(), 6, ref MyFieldObjID);





Here is a summary of what this line is doing....Using the _Plex ModelAPI that we instantiated into memory call, its FindObj method (function) and pass in the contents of the TextBoxFieldName after trimming any trailing blanks.  Let the FindObj API know we are looking only for a field (Object Type = 6) and then store the returned ID of the object (if found) to my new field MyFieldObjID.

35. If an object is found that matches the name and type then the internal ID is returned, otherwise it will be 0.  We only want to proceed if an object exists otherwise we will send a message to the user.  Enter the following immediately below the FindObj statement.

            if (MyFieldObjID != 0)
            {


            }
            else
                MessageBox.Show("Field " + TextBoxFieldName.Text.Trim() + " not found in this local model");

36. If everything has gone to plan then your code window should look like the image below.




37. If not already open, Open Plex and a local model of your choice.  If all is well you can run the tutorial program from inside Visual Studio by pressing the debug button.



38. This will build the project and execute the code.  Try entering a field you know doesn’t exist and you will see our error message and when you type a correct field like YesNo then the message will not appear.



39. Now you have tested what we have so far.  Stop the debugger by clicking on the stop button or close the application using the Windows Close X button.

Now we have covered the basics of ModelAPI and Visual Studio I’ll expedite the completion of this tutorial now by asking you to enter the following two snippets of code.  The first snippet is the declaration of all the variables that we’ll be using and initialisation code to clear the grid after each invocation.  The second snippet is the heavy lifting to interrogate the API and append the details to the Grid.  The comments in the code should suffice.



40. Under the line int MyFieldObjID = 0; Enter the following.

      int MyFieldTriples = 0;   //The enumerator ID for the triples associated with the Field.
      int MyTriple = 0;         //When we loop through the triples this stores the Model ID for the Triple.
      string TripleNameDetails = ""; //The actual Triple returned from the GetTripleName method.
      int NumberOfTriples = 0;   //Stores the count of triples associated with the Field in the enumerator.
      int MyCounter = 0;         //Start point for the loop.


      //Clear the Grid
      GridTripleDetails.Rows.Clear();

Again the green underline will probably appear.  Again don’t worry.

41. Place the cursor inside the braces as below

   if (MyFieldObjID != 0)
       {

       }
       else
       MessageBox.Show("Field " + TextBoxFieldName.Text.Trim() + " not found in this local model");

42. Insert the following code snippet

      //Get all (0 = all i.e. no Verb selection like 'ENT has FLD') triples associated
      //with the object. In this case an entity
      _Plex.EnumTriplesBySource(MyFieldObjID, 0, ref MyFieldTriples);
      //An enumerator is basically an array(list).  
      //In this case it has all the triple(s) surrogate ID in the model
      //We subsequently create a loop to read through the enumerator but before that we 
      //calculate how many to loop through.
      _Plex.GetCountOfItemsInEnumerator(MyFieldTriples, ref NumberOfTriples);
           do
           {
               //Get the next triple in the enumerator (returns its ID)
               _Plex.GetNextTriple(MyFieldTriples, ref MyTriple);
               //Get the Full Triple Name Details
               _Plex.GetTripleName(MyTriple, ref TripleNameDetails);
               //Add to the grid control.
               string[] NewGridRow = new string[] { TripleNameDetails };
               GridTripleDetails.Rows.Add(NewGridRow);
               MyCounter++;  //Increment Counter that is looping through the enumerator (array).
           }
           while (MyCounter < NumberOfTriples); //When done stop querying the enumerator i.e. Exit Loop
           //Destroy the enumerator (Free up memory)
           _Plex.EndEnum(ref MyFieldTriples);   

43. If everything has gone to plan the code snippet for the button click should now look like the following image.



44. Press the debug button again and enter a valid field like YesNo and you should get the following.







Thanks for reading.
Lee.

No comments:

Post a Comment

Thanks for considering leaving some comments about my random rants for everything software development and more.