Adding Delete Functionality to a Screen or Control

From OpenPetra Wiki
Jump to navigation Jump to search

Overview

Nearly all the code to delete a specific record from a table can be auto-generated by Open Petra's code generation applications. A small amount of code is generated on the client and a larger amount is generated in the server. You can activate all this code by adding a few simple lines to the YAML file that defines the behaviour of the screen or user control. When you do this you will get

  • a delete button with a label of your choice - but Delete by default
  • code that enables or disables the button depending on the circumstances. Some records in Open Petra are specifically marked as being non-deletable.
  • code that checks whether the row is referenced by another table or tables as a foreign key. If it is, a message box is displayed giving helpful information about which table(s) reference the data, and the delete action is abandoned.
  • code to ask for pre-confirmation of the action.
  • code to delete the relevant record.
  • code to confirm a successful outcome.

In addition there are optional manual code file extensions that can be made before, during and after the delete action.

This auto-generated code only applies to screens that have a grid capable of displaying multiple selectable records.

Coding the YAML File

There are a few simple steps to code the YAML file to include standard deletion. You just need one line in the Actions section and some simple lines in the Controls section.

A typical Actions section will look like this

    Actions:
        actNew: {Label=&New, ActionClick=NewRecord}
        actDelete: {Label=&Delete, ActionClick=DeleteRecord}

This has one action for the New button and one action for the Delete button

The equivalent Controls section would look like this

        pnlButtons:
            Dock: Right
            Controls: [btnNew, btnDelete]
        btnNew:
            Action: actNew
            Stretch: horizontally
        btnDelete:
            Action: actDelete
            Stretch: horizontally

This has a panel containing the two buttons docked to the right. Each button specifies the associated action and, in order to make the buttons have the same size, they are both stretched horizontally.

It is as simple as that! The only rules are that the button must be named btnDelete and the action must be called actDelete. The label does not have to be Delete. The ActionClick does not have to be DeleteRecord but there is normally no reason to change these internal names.

Generating the C# Code

Normally you can make changes to a YAML file and it is a simple matter to create the C# code for the equivalent client screen and re-compile the client. But a YAML file with a delete button may require you to do more than this.

The critical occasions are

  • when you edit a YAML file and add a new Delete button
  • or when you create a new YAML file that contains a Delete button

If either of these cases apply then you will need to do the following

  • save the YAML file(s)
  • run generateORMReferenceCounts either using nant or the Developer's Assistant
  • run generateGlue either using nant or the Developer's Assistant
  • run generateWinform on the YAML file(s) (or generateWinforms for all forms) - again using nant or the Developer's Assistant
  • compile both the server and the client

Please understand that once you have done these actions once on the YAML file there is no need to repeat them again because you now have generated all the code on the server that you need. Any subsequent changes to the YAML file that you make (for example laying out the controls so that they look nice) can be compiled to C# and/or previewed in the normal way because the server code will not change when you do that.

Auto-generated Client Code

So what code gets generated on the client? There are three snippets of code that we generate on the client.

First there is a click event handler that simply calls a standard method. This code example deletes a record from the p_business table.

    private void DeleteRecord(object sender, EventArgs e)
    {
        DeletePBusiness();
    }

Second there is a line of code that handles the enable/disable state of the button

        FPetraUtilsObject.EnableAction("actDelete", ((ARow != null) && (ARow.Deletable == true) && !FPetraUtilsObject.DetailProtectedMode));

Finally there is the deletion code itself - in this example in the method DeletePBusiness()

    private void DeletePBusiness()
    {
        bool allowDeletion = true;
        bool deletionPerformed = false;
        string deletionQuestion = Catalog.GetString("Are you sure you want to delete the current row?");
        string completionMessage = string.Empty;
        TVerificationResultCollection VerificationResults = null;

        if (FPreviouslySelectedDetailRow == null)
        {
            return;
        }

        this.Cursor = Cursors.WaitCursor;
        TRemote.MPartner.ReferenceCount.WebConnectors.GetCacheableRecordReferenceCount(
            "BusinessCodeList",
            DataUtilities.GetPKValuesFromDataRow(FPreviouslySelectedDetailRow),
            out VerificationResults);
        this.Cursor = Cursors.Default;
        if ((VerificationResults != null)
            && (VerificationResults.Count > 0))
        {
            MessageBox.Show(Messages.BuildMessageFromVerificationResult(
                    Catalog.GetString("Record cannot be deleted!") +
                    Environment.NewLine +
                    Catalog.GetPluralString("Reason:", "Reasons:", VerificationResults.Count),
                    VerificationResults),
                    Catalog.GetString("Record Deletion"));
            return;
        }

        if(allowDeletion)
        {
            if ((MessageBox.Show(deletionQuestion,
                     Catalog.GetString("Confirm Delete"),
                     MessageBoxButtons.YesNo,
                     MessageBoxIcon.Question,
                     MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes))
            {
                int nSelectedRow = grdDetails.SelectedRowIndex();
                FPreviouslySelectedDetailRow.Delete();
                deletionPerformed = true;

                if (deletionPerformed)
                {
                    FPetraUtilsObject.SetChangedFlag();
                    // Select and display the details of the nearest row to the one previously selected
                    SelectRowInGrid(nSelectedRow);
                }
            }
        }

        if(deletionPerformed && completionMessage.Length > 0)
        {
            MessageBox.Show(completionMessage,
                             Catalog.GetString("Deletion Completed"));
        }
    }

This snippet of code does the following.

  • It checks that the row is not empty
  • It queries the server to find out of the row is currently referenced by another table or tables. If it is it displays a helpful message and exits the function.
  • It asks the user to confirm deletion. The user can abandon deletion at this point.
  • It deletes the record
  • It displays a 'success' message

The reference count message is something like: You cannot delete this record. It is used by 3 records in the XXX table and 19 records in the YYY table. An example of a record that uses this record is found in Partner with a key of 43005009.

You can modify the behaviour of the deletion process by including any or all of the following methods in your manual code file.

private bool PreDeleteManual(PInternationalPostalTypeRow ARowToDelete, ref string ADeletionQuestion)

private bool DeleteRowManual(PInternationalPostalTypeRow ARowToDelete, out string ACompletionMessage)

private void PostDeleteManual(PInternationalPostalTypeRow ARowToDelete, bool AAllowDeletion, bool ADeletionPerformed, string ACompletionMessage)
  • If the first method returns false the deletion will be abandoned. You can use this method to modify the deletion question.
  • The second method can be used to replace the standard record deletion code with more complex code of your choice. You can modify the completion message. You return true or false depending on whether the deletion succeeded.
  • The third optional manual method can be used to do manual clean-up after deletion has occurred. The parameters tell you if deletion was initially allowed/disallowed, whether deletion actually succeeded and what the recommended message is that should be shown.

Auto-generated Server Code

You will notice from the client code above that the client calls a method on the server named

TRemote.MPartner.ReferenceCount.WebConnectors.GetCacheableRecordReferenceCount

using a web connector method. (There is an equivalent non-cacheable table method too). All the code to implement the connectors, interfaces and implementations of these methods is auto-generated for the server.

The implementations are all found in the web folder beneath Server/lib/ModuleName in a file named ReferenceCount-generated.cs. So, for example, there is a file csharp/ICT/Petra/Server/lib/MPartner/ReferenceCount-generated.cs. These implementations all call standard Data Access methods to determine the reference counts and construct a Verification Result Collection that should be returned to the client.