Showing posts with label DotNet. Show all posts
Showing posts with label DotNet. Show all posts

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.

Friday, March 2, 2012

Beginners Guide to the CA Plex Model API using C# .NET - Part II - 'Model API and the model repository'

The first post in this series late last year touched on the power of the Model API and how it could be useful for us Plexxers out there. 


I envisage us automating trivial tasks, extracting information from a model, import system designs into CA Plex, integrate the IDE with other environments/tools as well as code generation productivity tools like my Entity Creator!!!!!

Today we will cover some of the theory, Part III will highlight some of the core methods that you can use to interrogate/update the model and finally Part IV will show you a basic example in C#.NET (DotNet) and give you some other little tips and tricks along the way.

We all know what the Model API is, “don't we!”, but just in case here is my take on it.  Put simply, it is a gateway, interface, framework for interacting with your CA Plex environment and your local model(s) and it is implemented as a COM API.  CA ships a great local model and plenty of documentation to get you going and Google will reveal numerous posts from community members in our forums.

So let's get started.  To truly get the Model API and how it works you need to remind yourself of the underlying repository that CA Plex uses.  A great place to start is with the 'Model Editor' and understanding its design layout.  The ‘Model Editor’ is probably one of the most used editors and with a good understanding of how this triple store works you are set up for Model API programming and Meta Coding techniques also .

Fig 1. Below shows the CA Plex Model Editor focused on a field object FIELDS/YesNo which is a basic single byte status field with a couple of values that is shipped as part of the CA Plex patterns.


The next couple of images might be a bit patronising for the long term CA Plex user so apologies if the next minute of your life is repeating what you already know.

You will see that the model editor has three distinct columns.  Column A is the Source Object column in CA Plex terms, Column C indicates the Target Object and Column B contains the linking Verb that help describes the relationship between the two objects.  Collectively this line is known as a Triple, multiples of these are known affectionately as Triples and they reside in the Triple Store.

Above this area highlighted in yellow below are fields that tell you what the source and target objects are.   This is the Object Type.  i.e. Entity, Field, Table, Interface etc.

So let’s transpose this knowledge onto Fig 1.

Column A (Red) = Source Object(s)
Column B (Red) = Verb
Column C (Red) = Target Object(s)
Object Types (Yellow)
Triple (Blue)



Let’s recap, key learning items for Model API terminology are Source Object, Target Object, Verb, Triple and Object Type and these will be referred to throughout this series of posts.

Back to the Model Editor

We know that the Model Editor can show you all triples for a Source Object and defaults to one level.  All the triples at this level are known as real i.e. they are implicit and not inherited.  If you show the object properties for the field FIELDS/YesNo you will see this clearly in the Object Properties window.  This is a key reference window when using the Model API and is your friend, trust me.



The other three properties that are NOT real are of course inherited.  As inheritance is defined using the ‘Is A’ verb, in this case FIELDS/YesNo – FLD Is a FLD – FIELDS Status.  YesNo inherits from the FIELDS/Status field. 

Double click the Target Object FIELDS/Status in the Model Editor and you will see the inherited triples mostly relate to the details in the Object Properties window.  There is a small exception with the Control SYS triple which is a bug/feature/design consideration but I will leave that out of scope for this post, just note that it is there.



Generally speaking if a triple is repeated or overridden at a higher level it (the implicit triple) takes precedence over the inherited triple and therefore they are not shown.  i.e. The Limits SYS (All) triple only shows at level 1 but in fact it is entered at both Level 1 (FIELDS/YesNo) and Level 2 (FIELDS/Status).

The rest is just about understanding how to traverse through objects and related triples in the model.  There are also lots of other cool API methods to help with automation.

Post III will go into more detail about the methods that are available within the Model API with a focus on traversing the Model Editor and its triples.  Hopefully, introducing the concepts above will help you succeed.

Thanks for reading.
Lee.

Friday, December 16, 2011

The Sorcerers Apprentice.

Hi,

I have been aware of the 'Varianted Source Code' models that Roger Griffith has made available for the community for quite a while and today with the release of version 1.1 which has C# client code support all ready for the GA Release of CA Plex 7.0.  We now have some additional sources :-).  FYI - I don't know when this is coming out but it can't be far away now :-).

See the link below.


There are always Pro's and Con's of any approach but this solution seems pretty fair to me. Obviously, if you are a C++ and RPGIV typical client server customer and not changing in the near future then this post will be of little relevance (or is it - read on).  I can think of only one other small issue in that if you prefer to use triples for setting the language at a function level rather than variants then this might need some re-factoring.

If, however, you are planning on migrating your client (or server for that matter) to c# .NET/Java etc you may as well start to reduce your impact for the big move.  By replacing your own source code calls for the shipped code supported by the varianted models sooner in the process you can only win. Remember these are available NOW and can be used with Plex 6.1.

This only leaves your own 'personal' or 'application specific' source code.  A little like User Source in 2E sometimes these are just fit for a purpose and not migratable.  Others simply may need tweaking.  Not a bad time to do some impact analysis and determine whether you need to brush up on some C#.

Therefore, I have a small challenge for people.  If you have some useful generic Source Code.  Any language (Java, C++, RPG IV or C#), let's share it and see if others can convert it across all the platforms.  Then Roger and his team could keep the shipped models up to date and everyone's a winner.  For every routine that is sent to me I will PERSONALLY ensure that they are all converted to relevant C# code.  Any volunteers from the community to pick up C++, Java and RPG IV?  I can get these done but not as quickly I am afraid :-(.  This is courtesy of my bosses at www.sasit.co.nz

I'm thinking of advanced String routines like.


  • Count xString occurs y times in zString
  • Replace Double Spaces with single space
  • IsNumeric?
  • IsAlphaNumeric?
  • PasswordStrength
  • Is CharactersOnly
  • CalculateStringLength
  • ReserveString
  • SentenceStyleCase
  • IsEmailAddress?
  • Replace xString with yString in zString
  • GenerateRandomNumber (Start, Max, ZeroFill?)
  • GenerateRandomString xLength


I'm sure that this list could get quite exhaustive (Suggestions welcome) but I am happy to co-ordinate this effort if people just add some stuff they want to share to the comments section.  So cut and paste some code and a description or just make a request.  

Thanks for reading. 
Lee.

P.S. Disclaimer - if code is Copyright please include and acknowledge source etc.

Monday, October 17, 2011

Beginners Guide to the CA Plex Model API using C# .NET




Firstly thank you to Rob Layzell for inspiring this blog.   If it wasn’t for his lab exercises I would have done this Model API exercise and subsequent blog using CA Plex and component import.  Now, whilst this is probably a cool thing using a code generation tool to interrogate and update the code generation tool repository (I am sure there must be a word in the OO world to describe this. JJJ).  In the back of my mind I was also acutely aware that release 7.0 is entering beta testing and the much anticipated C#.NET (WPF) client will soon be upon us.  So there isn’t a better opportunity for me to sharpen the old grey matter with some learning than this. 

I chose to continue with the C# coding for the simple reason that it would be worthwhile me understanding what .NET developers need to do as I will ultimately be looking to target .NET for my future applications.  And, of course, enable me an opportunity to learn Visual Studio, some pigeon C# and understand the inner workings of this environment.  All worthwhile skills for when the 4GL needs a little investigation, tweaking or debuggingJ.

We have had C# for server code generation since release 6.0.  Release 6.1 brought WCF to strengthen this offering.  With 7.0 we will have the client side resolved too with the promise of XAML and WPF.  The web service import is another tool that simplifies the integration and consumption of web services, so, all in all, good times ahead.

So back to Rob's unintended blog influence.  His tutorials for .NET used numerous examples of Visual Studio and C#.NET.  One in particular that took my fancy was Lab 10 and related to consuming the PlexAPI COM component and creating triples in the local model.  The ModelAPI is described as being useful for pattern designers in the online help in order for them to automate much of the configuration and setup for using their patterns.  I also see it as an opportunity to ensure that another level of automation is included in the tool.

Anyhow, seasoned CA Plex developers know we already have metacode to influence the generated code.  We also have patterns and inheritance to ensure consistent design or as I call it, conformity to the application architecture.  There are still of course plenty of areas with regard to modelling that a developer could easily get wrong when entering the triples.

In my last blog I alluded to a small entity creation tool that I am creating (UPDATE – This has blown into a full blown too now).  This is to ensure that the fields and files that I enter into the application model conform to our standards i.e. naming, inheritance, default field lengths, narrative being entered and labels etc.  As we are a new CA Plex (long time 2E shop) I am still working on these standards and experimenting but I will share the code and a sample model on request (note that this does currently have a degree of hardcoding at the moment but more than enough detail for people to get acquainted).

For those that are interested in taking this further and perhaps helping me improve the utility, just drop me your email in the comments section. J

For me this (ModelAPI) is too quickly overlooked but if you are serious about CA Plex and modelling then these are exactly the type of utilities (Add-Ins) that one should be considering.  These will further improve your team’s productivity as it is pretty quick and easy to tailor for your environment once you get your head around the API and the underlying model structure.  Just take a look at the StellaTools from George.

I recommend any CA Plex developer to take some time to understand what you can achieve with this feature.  This is quite an in depth subject so I feel that this will eventually become a four part series, so, if you are keen....

Part II – ‘Model API and the model repository’ will cover the underlying architecture of the model.

Part III – ‘Key Model API commands’ will go into detail about some of the core commands that you will need to understand in order to develop against the COM API and sow some of the theory covered in part II together.

Part IV – ‘Some DotNet Tips and Tricks’ will show some programming tips and I hope should be enough to inspire a few of you to ‘RTFM’ with regard to the Model API.

All feedback is appreciated.  Until then.


Thanks for reading.
Lee.