Category: ABAP Beginner

  • Everything you need to know about SAP ABAP Unit Test

    SAP ABAP Unit Test is a feature in the SAP Advanced Business Application Programming (ABAP) environment that allows developers to create and run unit tests for their code. This promotes better code quality, readability, and maintainability. Let’s delve deep into the concept:

    Introduction

    • ABAP Unit is SAP’s native framework for creating and executing unit tests in the ABAP development environment.
    • Unit tests are designed to test individual parts (units) of the software, typically at the method or function level.
    • It allows developers to test individual units of code, such as methods, function modules, and subroutines. This can help to identify and fix bugs early in the development process, and improve the overall quality of the code.

    Purpose of ABAP Unit Test

    • Quality Assurance: Ensures that individual units of source code are working as expected.
    • Refactoring Security: Allows developers to make changes to the codebase without fear of unintentionally introducing errors.
    • Documentation: Unit tests can serve as documentation because they demonstrate how certain functionality is expected to work.

    How It Works

    • ABAP Unit tests are written in the ABAP language itself.
    • The tests are generally located in the same development object or class they’re testing, but they are clearly separated from the actual implementation.
    • The tests can be executed in the ABAP development environment. The system provides instant feedback on whether the tests pass or fail.

    Key Concepts

    • Test Classes: These are special classes in ABAP where unit tests are defined. They typically end with the suffix _UT.
    • Test Methods: These are methods inside test classes that contain the actual test logic. They are marked with the addition FOR TESTING.
    • Test Fixtures: Methods that set up a consistent test environment before each test run. They are often used to initialize data or configurations needed for the tests.
    • Assertions: Used to check if a particular condition is met. If an assertion fails, the test fails.

    Benefits

    • Immediate Feedback: Developers receive immediate feedback after making changes, allowing for quicker debugging.
    • Consistency: Helps in maintaining consistency across the development environment as all developers can run the same tests.
    • Reduces Bugs: By catching issues early in the development process, it can significantly reduce the number of bugs in the production environment.
    • Facilitates Collaboration: Makes it easier for teams to collaborate as they can rely on tests to ensure the integrity of their code.

    Best Practices

    • Isolation: Unit tests should be isolated and independent. The result of a test should not be dependent on whether other tests pass or fail.
    • Granularity: Test only one aspect or behavior at a time.
    • Automate: Ideally, run unit tests as part of an automated build or integration process.
    • Consistency: Ensure that unit tests are consistently maintained and updated as the codebase evolves.

    Limitations

    • Unit tests in ABAP or any language are not a substitute for other testing levels like integration tests or end-to-end tests.
    • They don’t typically interact with external systems like databases or third-party services, so while they can ensure a function works as expected in isolation, they can’t guarantee broader system functionality.

    Creation in ABAP

    • Local Test Classes: Within the ABAP environment, developers can create local classes (within programs or global classes) to write unit tests. These are typically nested within the main program or global class.
      CLASS lcl_test DEFINITION FOR TESTING INHERITING FROM cl_b2p_call.
      
        PRIVATE SECTION.
          DATA: lt_key       TYPE TABLE OF /bobf/t_frw_key,
                lt_messages  TYPE TABLE OF symsg_tab,
                lv_error_msg TYPE string.
      
        METHODS:
          setup,
          teardown,
          test_send_outbproxy_success,
          test_send_outbproxy_error.
      
      ENDCLASS.
      
      CLASS lcl_test IMPLEMENTATION.
      
        METHOD setup.
          CLEAR lt_key.
          CLEAR lt_messages.
        ENDMETHOD.
      
        METHOD teardown.
          " Clean up if necessary
        ENDMETHOD.
      
        METHOD test_send_outbproxy_success.
          DATA: lt_key TYPE TABLE OF /bobf/t_frw_key,
                ls_key TYPE /bobf/t_frw_key.
      
          " Prepare input data
          ls_key-key = 'B7036E6334A61EEE96EC134C77E96235'.
          APPEND ls_key TO lt_key.
      
          " Call the method being tested
          CALL METHOD send_outbproxy
            EXPORTING
              it_key      = lt_key
            IMPORTING
              et_messages = lt_messages
              ev_error    = lv_error_msg.
      
          " Assertions
          cl_abap_unit_assert=>assert_equals( act = lv_error_msg
                                              exp = ''
                                              msg = 'Expected no error message for success.' ).
          
          cl_abap_unit_assert=>assert_equals( act = lines( lt_messages )
                                              exp = 1
                                              msg = 'Expected one message in the message table for success.' ).
      
          " Add more assertions based on your specific success criteria.
      
        ENDMETHOD.
      
        METHOD test_send_outbproxy_error.
          DATA: lt_key TYPE TABLE OF /bobf/t_frw_key,
                ls_key TYPE /bobf/t_frw_key.
      
          " Prepare input data
          ls_key-key = 'InvalidKey'.  " Simulate an invalid key
          APPEND ls_key TO lt_key.
      
          " Call the method being tested
          CALL METHOD send_outbproxy
            EXPORTING
              it_key      = lt_key
            IMPORTING
              et_messages = lt_messages
              ev_error    = lv_error_msg.
      
          " Assertions
          cl_abap_unit_assert=>assert_not_equals( act = lv_error_msg
                                                  exp = ''
                                                  msg = 'Expected an error message for invalid input.' ).
          
          cl_abap_unit_assert=>assert_equals( act = lines( lt_messages )
                                              exp = 1
                                              msg = 'Expected one message in the message table for error.' ).
      
          " Add more assertions based on your specific error criteria.
      
        ENDMETHOD.
      
      ENDCLASS.
      

      In this example:

      • The setup and teardown methods are used for initialization and cleanup.
      • test_send_outbproxy_success and test_send_outbproxy_error are test methods.
      • In each test method, you prepare the input data (lt_key), call the method being tested (send_outbproxy), and then perform assertions to check if the method behaves as expected for success and error cases.

      You can adjust the assertions and test data based on your specific requirements and the behavior of the SEND_OUTBPROXY method.

    • Methods: Within these classes, specific methods are marked with the addition FOR TESTING to indicate they are test methods.
    • Assertions: Inside the test methods, you use ABAP statements like ASSERT or ASSERT_EQUALS to validate the expected outcomes.

    Test in ADT and ABAP SE24

    • ADT (ABAP Development Tools): This is essentially the Eclipse-based IDE for ABAP. Developers can write and execute unit tests directly from here.
    • SE24: This is the Class Builder in the SAP GUI. You can create global classes, which include your test classes and test methods, and execute them directly from this transaction.

    Checkman T Code in SAP

    • CHECKMAN is the T-code for the Code Inspector, a tool for static code analysis in the SAP environment.
    • It helps in identifying performance issues, security vulnerabilities, and violations of coding conventions.
    • While it’s not directly a unit testing tool, it’s vital for ensuring code quality and adherence to best practices.

    Execute Unit Test in ABAP

    • After writing the unit tests, they can be executed directly from the ABAP environment.
    • When you run the unit tests, ABAP provides a detailed log of which tests passed and which failed.
    • For any failed test, you get an error message pointing out the assertion or the line of code causing the failure.

    ABAP Coverage

    • Test coverage in ABAP measures the amount of your codebase that’s tested by unit tests.
    • The ABAP Test Cockpit and ABAP Development Tools in Eclipse provide insights into which lines of code, methods, or classes have been executed during the tests.
    • This is crucial because high test coverage often correlates with fewer bugs, though it’s not a guarantee of software quality by itself.

    ATC Errors during ABAP Unit Test

    • ATC (ABAP Test Cockpit): It’s a central tool for developers to check the quality of their ABAP code.
    • While executing unit tests, you might come across ATC errors. These could be due to a range of issues, from syntax errors to violations of best practices or custom checks defined in your SAP environment.
    • Addressing ATC errors ensures your code is not only functionally correct but also adheres to established coding standards.

    Conclusion

    The ABAP Unit Test framework is a powerful tool in the SAP development toolkit. When used effectively, it can greatly enhance code quality, reduce debugging time, and ensure smoother deployments. Like all testing methodologies, it’s most effective when used in conjunction with other testing and quality assurance practices.

  • How to Upport and Down Port in SAP using TCode UDO

    Transporting changes between systems is crucial for maintaining consistency across your SAP landscape. Below are the steps to perform this operation:

    How to Upport and Down Port in SAP using TCode UDO

    1. Initiate the Process in the Source System:
    – Go to the system from which you want to port changes to other systems. [or you can also do from the target system where you are actually porting] – Open the SAP GUI and access the `UDO` transaction.
    – You will need the following parameters:
    – Source System Transport Request (TR)
    – Source System Name
    – Target System Name

    2. Execute in the Target System:
    – Log into the target system where you want the changes to be imported.
    – Open TCode `UDO`.
    – Input the following details:
    – Transport Request (TR) from the source system.
    – Source System Name accompanied by the client number.
    – Target System Name.

    3. Allocate a New Transport Request (TR):
    – Once the above details are provided, the system may prompt you to assign a new TR for this transport. This is to ensure that the changes are tracked and can be rolled back if needed.
    – Input or create a new TR as instructed.

    4. Confirm and Execute:
    – After all details are in place, review and confirm.
    – Execute the transport. The system will begin the process of porting the changes from the source to the target system.

    5. Monitor & Verify:
    – Upon completion, ensure that the transport has been successful.
    – Verify in the target system to ensure all ported changes are reflecting correctly.

  • Call Transaction Method in SAP BDC

    Introduction

    A Call transaction is a very simple report program. Once you execute and come out of the program, there is no log to cross check.

    Syntax:

    CALL TRANSACTION <transaction code> USING <it_bdcdata>
    MODE ‘A/E/N’
    UPDATE ‘A/S/L’
    MESSAGE INTO <it_msg_details>.

    Here, it_bdcdata represents the internal table that has instructions for one time execution of the t-code. This is the same table that we discussed in the section “SAP BDC Technical Details”. So, this internal table at one moment will hold instructions for only one record.

    Here, we have three different options for MODE. The modes determine the control over screen display.

    • A: It means, while execution of the program, all screens will be displayed. It is best suited for testing purpose as it is a foreground testing.
    • N: It means, while execution of the program, no screens will be shown even in case of success or error. This is best suited for production execution as it is a background job.
    • E: It means, the screens with message will be displayed every time there is an error. This is also used for testing purpose, in case SY-SUBRC fails for method N, and you are not able to identify the position of error.

    Here, we have three different options for UPDATE. The update command signifies Create, Update and delete operation over table/database. And, this UPDATE command provided the control over the sequence of database operations. Like, if data will be saved for all external file one by one, or in parallel.

    • A: It means Asynchronous. It means irrespective of the face that first set of data was processed and data was being saved in db, the next round of data process will start and not wait for the completion of first. This also means for large amount of data, the speed of the program will be faster in this mode. But, also there is a very rare chance of getting errors.
    • S: It means Synchronous. It means, every time the command CALL TRANSACTION is executed, until the data is saved in table and a success SY-SUBRC comes, it will not execute the CALL TRANSACTION for the next set of data. It is preferred in Production mode, as it is error free (Although slower).
    • L: It means Local. This is the command which signifies that the update for entire data (whole excel or csv or txt) will be executed at once, in the end, and only after the “COMMIT WORK” statement. The use case for Local Update or Update Function Module is where you either want all data to updated or none. The best use case is updating header and detail, and if detail or header fails, none of these tables will be updated. You can read more about it here.

    Here, it_msg_details saves all the messages that are produced over the screen (success, warning, information or error).

    Call Transaction Method Flow

    As you can see in the above design flow, the excel will be converted into internal table, and then BDC Codes (CALL TRANSACTION) will be called where <it_bdcdata> will be in form of BDCDATA format with various fields such as Program, DYNPRO, etc including field and value holding data of first row of the excel. Once the database process completes, the next data of the excel will be processed and so on.

    Steps to upload data in SAP system using BDC

    To understand the above process, we will show case a simple example where we will:

    1. Create multiple tables for Employee Data that can be created using a report.

    We have created these tables: zBarry_emp (for employee basic information), zBarry_sal (for employee Salary information) and zBarry_add (for employee address details). The fields are as shown below:

    zBarry_emp

    Field Name Field Type
    EMPID (Key) INT4
    FNAME CHAR20
    LNAME CHAR20
    PHONE CHAR20

    zBarry_sal

    Field Name Field Type
    EMPID (Key) INT4
    SALARY CHAR20

    zBarry_add

    Field Name Field Type
    EMPID (Key) INT4
    CITY CHAR20
    PIN CHAR20
    STATE CHAR20
    COUNTRY CHAR20

    2. The report will be able to take many fields as input.

    Now, we will create a report ZBARRYEMP_REPORT to take multiple inputs via screen and save them in the above tables. The code of the same is shown below:

    REPORT ZBARRYEMP_REPORT.
    Data: ls_emp type ZBARRY_EMP,
          ls_sal type zbarry_sal,
          ls_add type zbarry_add,
          lv_MSG type char20.
    
    PARAMETERS: p_empid TYPE int4,
    p_fname type char20,
    p_lname type char20,
    p_phone type char20,
    p_salary type char20,
    p_city type char20,
    p_pin type char20,
    p_state type char20,
    p_con type char20.
    
    " mapping for Employee Info
    ls_emp-empid = p_empid.
    ls_emp-fname = p_fname.
    ls_emp-lname = p_lname.
    ls_emp-phone = p_phone.
    
    
    " mapping for Employee Salary
    ls_sal-empid = p_empid.
    ls_sal-salary = p_salary.
    
    " mapping for Employee Address
    ls_add-empid = p_empid.
    ls_add-city = p_city.
    ls_add-pin = p_pin.
    ls_add-state = p_state.
    ls_add-country = p_con.
    
    " SQL Operations.
    INSERT ZBARRY_EMP FROM ls_emp.
    If Sy-subrc = 0.
    lv_MSG = 'Create is successful'.
    else.
      lv_MSG = 'Create Failed'.
           Endif.
    
     INSERT ZBARRY_sal FROM ls_sal.
    If Sy-subrc = 0.
    lv_MSG = 'Create is successful'.
    else.
      lv_MSG = 'Create Failed'.
           Endif.
    
      INSERT ZBARRY_add FROM ls_add.
    If Sy-subrc = 0.
    lv_MSG = 'Create is successful'.
    else.
      lv_MSG = 'Create Failed'.
           Endif.
    
           if lv_MSG EQ 'Create Failed'.
             MESSAGE lv_MSG TYPE 'E' DISPLAY LIKE 'E'.
               ENDIF.

     

    Output:

    ABAP Report for BDC

    3. Then, we will create a t-code for our report.

    We will create a T-code “ZMYTCODE” using SE93 for our report “ZBARRYEMP_REPORT”.

    Tcode for BDC

    Steps to Record a transaction code using BDC

    4. Thereafter, we will run a BDC recording (using T-Code SHDB) and get BDCDATA from that recorder.

    Step 1. Go to t-code SHDB and click on “New Recording”

    SHDB New Recording

    Step 2: Provide T-Code, any name for recording and set update mode as “Synchronous”.

    Create Recording SHDB

    Step 3: It will open your Report. Now, provide all the data, and press execute.

    BDC Recorder

    Now click, back to see your BDCDATA, for our example it looks like this:

    INDEX PROGRAM DYNPRO DYNBEGIN FNAM FVAL
    1 T ZMYTCODE
    2 ZBARRYEMP_REPORT 1000 X
    3 BDC_CURSOR P_CON
    4 BDC_OKCODE =ONLI
    5 P_EMPID 12
    6 P_FNAME Rudra
    7 P_LNAME Pandey
    8 P_PHONE 99999999
    9 P_SALARY INR 9999999
    10 P_CITY Mughalsarai
    11 P_PIN 232101
    12 P_STATE Uttar Pradesh
    13 P_CON India
    14 ZBARRYEMP_REPORT 1000 X
    15 BDC_OKCODE /EE
    16 BDC_CURSOR P_EMPID

    Now, here you can see that all our entered data is also recorded in the recording.

    Here BDC_OKCODE “=ONLI” is for our “Execute” button, and BDC_OKCODE = “/EE” is showcasing that we pressed back. We will use the code until we press execute.

    You can test your recording by clicking “Process” button:

    Test BDC

    While testing, do change data with a new set. Before exiting, you must save your recording.

    Steps to Create a BDC Program

    5. Now, we will create a program that accepts excel input and convert that excel into an internal table.

    Step 1: Create a new ABAP report “ZBARRYEMP_BDC” using t-code SE38.

    Step 2: Create the following:

    • local structure of type “bdcdata” where we will map our excel data with bdcdata that we recorded earlier
    • local internal table of type “bdcdata” where we will push our local structure that we have created above
    • local structure and internal table of type “bdcmsgcoll” where we will save the message for every call that we make to the recording
    • local internal table and local structure to hold excel data that we will upload

    We have created the following:

    REPORT ZBARRYEMP_BDC.
    " local structure with combined fields of emp table, salary table and address table
    TYPES: BEGIN OF ls_emp,
      empid type INT4,
      fname type char20,
      lname type char20,
      phone type char20,
      salary type char20,
      city type char20,
      pin type char20,
      state type char20,
      country type char20,
      END OF ls_emp.
    
    DATA: ls_bdcdata TYPE bdcdata,
          ls_msg type bdcmsgcoll.
    
    DATA: lt_bdcdata TYPE TABLE OF bdcdata,
          lt_bdcmsg TYPE TABLE OF bdcmsgcoll,
          lt_bankdata TYPE TABLE OF ls_emp.

     

    Step 3: Now, we will import the excel data using Function Module ‘TEXT_CONVERT_XLS_TO_SAP’ and push it to our internal table it_empdata. You can read more about Excel upload in ABAP here.

    " Uploading Excel and converting it into Interna Table
    TYPE-POOLS truxs.
    PARAMETERS p_file TYPE rlgrap-filename.
    
    DATA : t_upload  TYPE STANDARD TABLE OF ls_emp,
           wa_upload TYPE ls_emp,
           it_type   TYPE truxs_t_text_data.
    
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file.
      CALL FUNCTION 'F4_FILENAME'
        EXPORTING
          field_name = 'p_file'
        IMPORTING
          file_name  = p_file.
    
    START-OF-SELECTION.
      CALL FUNCTION 'TEXT_CONVERT_XLS_TO_SAP'
        EXPORTING
          i_tab_raw_data       = it_type
          i_filename           = p_file
        TABLES
          i_tab_converted_data = t_upload[]
        EXCEPTIONS
          conversion_failed    = 1
          OTHERS               = 2.
      IF sy-subrc <> 0.
        MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                WITH sy-msgv1 sy-msgv2 .
      ENDIF.
    
    END-OF-SELECTION.

     

    Step 4: Now in a loop we will keep pushing the bdcdata parameters that is

    • PROGRAM, DYNPRO, DYNBEGIN: These will remain constant for one screen (in our case, constant for whole program as we have only one screen). These will be taken from the BDCDATA that we have generated i.e.
    ZBARRYEMP_REPORT 1000 X
    • FNAM, FVAL: These will hold the key and values (In our case, the keys are the parameters that we used for input in our ABAP report “ZBARRYEMP_REPORT” while the values will be taken from excel upload.
    • The first two fields for a screen are always BDC_CURSOR  and BDC_OKCODE.  The value can be retrieved from the generated BDCDATA. In this case, the values are ‘P_CON ‘ and ‘=ONLI’, respectively.

     

    Step 5: Once the values are taken as per BDCDATA structure, we call the “CALL TRANSACTION” statement. These entire statements will be looped until the operation finishes for the entire excel data.

    The syntax for CALL TRANSACTION is:

    CALL TRANSACTION <transaction code> USING <it_bdcdata>
    MODE ‘A/E/N’
    UPDATE ‘A/S/L’
    MESSAGES INTO <it_msg_details>.

     

    For our example, the above value will become:

    CALL TRANSACTION ‘ZMYTCODE’ USING lt_bdcdata
    MODE ‘N’
    UPDATE ‘S
    MESSAGES INTO lt_bdcmsg.

     

    Step 6: Now upload an excel file with the given format. In our example, we have an excel as shown below:

    Excel format BDC

    Note: Do not include the header. The excel should look like this:

    Excel with Data for BDC

    Once you are done with the ABAP Changes, then run the report, upload the excel file and once the ABAP Report executes, check the table to see if all the records are uploaded or not.

    ABAP Code for BDC Program

    REPORT ZBARRYEMP_BDC.
    " local structure with combined fields of emp table, salary table and address table
    TYPES: BEGIN OF ls_emp,
      empid type int2,
      fname type char20,
      lname type char20,
      phone type char20,
      salary type char20,
      city type char20,
      pin type char20,
      state type char20,
      country type char20,
      END OF ls_emp.
    
    DATA: ls_bdcdata TYPE bdcdata,
          ls_msg type bdcmsgcoll.
    
    DATA: lt_bdcdata TYPE TABLE OF bdcdata,
          lt_bdcmsg TYPE TABLE OF bdcmsgcoll,
          lt_empdata TYPE TABLE OF ls_emp.
    
    " Uploading Excel and converting it into Interna Table
    TYPE-POOLS truxs.
    PARAMETERS p_file TYPE rlgrap-filename.
    
    DATA : t_upload  TYPE STANDARD TABLE OF ls_emp,
           wa_upload TYPE ls_emp,
           it_type   TYPE truxs_t_text_data.
    
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file.
      CALL FUNCTION 'F4_FILENAME'
        EXPORTING
          field_name = 'p_file'
        IMPORTING
          file_name  = p_file.
    
    START-OF-SELECTION.
      CALL FUNCTION 'TEXT_CONVERT_XLS_TO_SAP'
        EXPORTING
          i_tab_raw_data       = it_type
          i_filename           = p_file
        TABLES
          i_tab_converted_data = t_upload[]
        EXCEPTIONS
          conversion_failed    = 1
          OTHERS               = 2.
      IF sy-subrc <> 0.
        MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                WITH sy-msgv1 sy-msgv2 .
      ENDIF.
    
      " Loop the above table t_upload[] data until all data is uploaded via BDC
      LOOP AT t_upload into wa_upload.
    * Screen 1 - Field 1 is always BDC_CURSOR
    ls_bdcdata-PROGRAM = 'ZBARRYEMP_REPORT'.
    ls_bdcdata-DYNPRO = '1000'.
    ls_bdcdata-DYNBEGIN = 'X'.
    ls_bdcdata-fnam = 'BDC_CURSOR'.
    ls_bdcdata-fval = 'P_CON'.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 2 - Always BDC_OKCODE
    ls_bdcdata-fnam = 'BDC_OKCODE'.
    ls_bdcdata-fval = '=ONLI'.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 3
    ls_bdcdata-fnam = 'P_EMPID'.
    ls_bdcdata-fval = wa_upload-empid.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 4
    ls_bdcdata-fnam = 'P_FNAME'.
    ls_bdcdata-fval = wa_upload-fname.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 5
    ls_bdcdata-fnam = 'P_LNAME'.
    ls_bdcdata-fval = wa_upload-lname.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 6
    ls_bdcdata-fnam = 'P_PHONE'.
    ls_bdcdata-fval = wa_upload-phone.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 7
    ls_bdcdata-fnam = 'P_SALARY'.
    ls_bdcdata-fval = wa_upload-salary.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 8
    ls_bdcdata-fnam = 'P_CITY'.
    ls_bdcdata-fval = wa_upload-city.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 9
    ls_bdcdata-fnam = 'P_PIN'.
    ls_bdcdata-fval = wa_upload-pin.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 10
    ls_bdcdata-fnam = 'P_STATE'.
    ls_bdcdata-fval = '=ONLI'.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 10
    ls_bdcdata-fnam = 'P_CON'.
    ls_bdcdata-fval = wa_upload-country.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    ENDLOOP.
    
    "Call BDC Transaction
    CALL TRANSACTION 'ZMYTCODE' USING lt_bdcdata MODE 'A' UPDATE 'S' MESSAGES INTO lt_bdcmsg.
    CLEAR lt_bdcdata.
    
    END-OF-SELECTION.

     

    Output

    BDC Program Output

  • BDC (Batch Data Communication) in SAP ABAP: Complete Guide

    Introduction

    In SAP environment, suppose you need to upload a data from an external source like an excel sheet. You have a program for the upload already in the system. You will therefore, visit the program or transaction, and then simply open the file location, upload the file, check for errors and that’s it.

    Therefore, these will be the steps that you will follow for a file upload. Suppose, you have Ten Thousand files to be uploaded via the same program. Wouldn’t it be a tedious job? SAP knew it, and hence created something called SAP BDC, which records your upload steps and automatically replicate it for next sets or batches of data. In this article, we will learn everything about SAP BDC with simple examples.

    What is BDC – Batch Data Communication in SAP ABAP?

    SAP BDC stands for Batch Data Communication. It was renamed by SAP to Batch Input, about 20 years ago. Still, the famous name i.e. BDC is used to refer it.

    In terms of definition, Batch Input or BDC are the sets of methods provided by SAP to transfer/migrate data from other SAP or Non SAP Systems.

    Why we need BDC?

    We need Batch Input of BDC for the following reasons:

    1. Data conversion or migration from Non SAP systems (e.g. csv, excel, text) to SAP Systems (e.g. SAP Table). It mostly happen for a new development (Master Data Migration) and SAP Upgradation.

    BDC Process Flow

    2. Automate daily tasks of a user. If the daily task of user is to upload data from a 3rd party to SAP System via T-Code.

    SAP BDC Design

    If you are asked to upload a set of data into database, in single table, you would quickly create a report, with file uploader, and use SQL to push that data into required table. But, if you are asked to upload hundred columns of data into tons of tables, based upon various conditions, based upon a T-Code, then it will be a tedious job.

    BDC solves our problem, by cutting our second task. Our part is to just push the excel until the transaction screen, and the rest is taken care.

    In below image, the usual case would be that you will open a t-code, enter required input and click save. In case of BDC, it creates recording of your upload process and give you the code of the recording. Using the provided code, you can create a program to upload excel and pass the data to that BDC recoded code, and the rest is taken care automatically.

    BDC Design

    SAP BDC Technical Details

    Every time you record your screen, a few fields are auto generated (called BDCDATA) as below:

    • Program Name (PROGRAM): The name of program for the transaction
    • Screen Number (DYNPRO): The screen number is auto generated
    • Field Name (s) [FNAM]: The field name for which value was provided. In case of multiple field, it will be repeated
    • Field Value (s) [FVAL]: For all the above fields, the entered value is recorded here
    • OK Code [BDC_OKCODE]: The event that occurred during recording. Either you pressed Enter or Clicked a button, the code for the same will be captured here
    • DYNBEGIN: This indicates that the new screen has started
    • BDC_CURSOR: It saves the current position of the cursor

    A common example based upon above structure is shown below:

    INDEX PROGRAM DYNPRO DYNBEGIN FNAM FVAL
    1 SAPMM07M 400 X
    2 BDC_CURSOR RM07M-LGORT
    3 BDC_OKCODE /00
    4 MKPF-BLDAT 22.12.2022
    5 MKPF-BUDAT 22.12.2022
    6 RM07M-BWARTWA 413
    7 RM07M-WERKS 2010
    8 RM07M-LGORT HRSL
    9 RM07M-WVERS2 X
    10 SAPMM07M 410 X
    11 BDC_CURSOR MSEG-UMLGO
    12 BDC_OKCODE /00
    13 MSEG-MATNR SLBW
    14 MSEG-ERFMG 20
    15 MSEG-ERFME to
    16 MSEG-WERKS 2010
    17 MSEG-LGORT HRSL
    18 MSEG-CHARG A693264
    19 MSEG-UMLGO HRSL

    You do not have to understand the above code, just check the field names discussed before and how they appear in the BDCDATA generated. You can even check the structure “BDCDATA” in SE11. Also, you can check another SE11 structure BDCMSGCOLL which is used for Collecting messages in the SAP System.

    Note: The recording by SHDB that we will discuss later is a client dependent process, and it has to be saved as a local file in desktop and has to be uploaded the same in to other systems.

    SAP BDC Transaction Codes (Tcode)

    The following T-Codes are used with respect to BDC or Batch Input:

    T-Code Use
    SM35 It is used to run Batch Input Sessions
    SHDB It is used to record a BDC (Batch Input) Session
    BDCUPDATE It is used to check updates in Batch Input

     

    Apart from these, you can find all other relevant T-Codes here.

    Methods of Batch Input or Types of BDC Call

    Now, we have a basic idea of BDC and its terminologies. Now, we will learn how to start with a BDC process. There are two different ways of doing the same. These are:
    1. Call Transaction Method
    2. Classical Batch Input Method or BDC Session Method

    We have discussed each individually in a different article (click them) and created respective programs.

    Error handling in SAP BDC

    There are many reasons due to which your BDC might fail; we will discuss a few issues and errors that are very generic to BDC.

    Important Guidelines for SAP BDC

    Following are the important guidelines in terms of SAP BDC:

    • BDC works by executing t-codes using data uploaded, hence all the data and logic validations are not done in BDC programs but are done in individual t-codes (the reports running behind those t-codes).
    • BDC is suitable for very large amount of data.
    • BDC should be tested in mode A and E, and should be deployed in production in mode N.
    • For different screens you must update the DYNPRO number, else the program will fail.
    • Every time you press enter or click, it is recorded in the BDCDATA. You should write code for every event in your BDC Program.

    Why BDC is not recommended

    BSC is closely associated with screens and t-codes. Every new release of a product in SAP, there might be chance of enhancing the screen; hence making the old BDC becomes non-applicable. Hence, BDC is not recommended for longer run.

    Alternative to SAP BDC

    The alternative to SAP BDC is SAP BAPI. There are several BAPIs that can replace the data transfer of a particular transaction. Even SAP recommends using BDC only in case there are no BAPIs for a t-code.

  • Exception and Error Handling in ABAP Reports

    Preface – This post is part of the ABAP Beginner series.

    Introduction

    A programmer always tries to code in such a way that his code is bug free and full proof. But there are certain scenarios, where his codes can fail. In such case, if the coder already knows the scenarios, then he handle them in form of Error handling. But, in case of situations, where an error can be generated due to unknown situations and left un-handled can cause serious dumps. For these scenarios, we have exception handling in SAP. In this article we will explore all scenarios of Exception and Error Handling in ABAP Reports

    Exception and Error Handling in SAP ABAP Reports

    As discussed above, a coder is required to handle known issues as well as intended error messages. These messages are shown to user in the output via MESSAGE statement.

    Different ways to catch Errors/Exception

    ABAP provides various ways to catch errors in an ABAP program.

    1. Using System Variable

    The simplest way is to use their system variables.

     SY-SUBRC EQ  0. "This statement indicates that an operation completed successfully.
     SY-SUBRC NE  0. "This statement indicates that an operation has failed.

    This way works directly if the entire code of report was process within the same program. It means, it cannot catch an error directly in case you have processed a Function Module or ABAP Class statements. For those entity, we need to raise exception from their end, and then exception can be handled in the report and processed accordingly.

    1. Catching Errors based on Exception

    In case, we implement a function module or method of a class, then it is important to raise exception from these classes and then we can catch these exceptions in report and show respective error.

    For Example:

    CALL FUNCTION 'Test_Function'
    
         EXPORTING
    
              DELIMITER =   ':'
    
              STRING        =   lv_string
    
         IMPORTING
    
              HEAD           =   lv_head
    
              TAIL             =   lv_tail
    
         EXCEPTIONS
    
              NOT_FOUND   =  1
    
              OTHERS       =   2.
    
    
    
    
    CASE SY-SUBRC.
    
         WHEN 1. ...
    
    // Show Error Message
    
         WHEN 2. ...
    
    // Show Error Message
    
         WHEN OTHER.
    
    // Show Error Message
    
    ENDCASE.

     

    1. Using TRY CATCH ENDTRY

    In case an exception is raised via a method of class, or an unexpected exception is raised, in these cases, we use TRY CATCH functionality of SAP ABAP. This is one of the best full proof way to handle all types of exceptions.

    Example:

    TRY.
    
         //Call your class or function module here
    
    CATCH CX_SY_ZERODIVIDE INTO O_REF. // The exception you have raised there
    
         MESSAGE “Your Error Message”.
    ENDTRY.

     

    Different ways to show Messages

    1. Using ABAP Statement

    Syntax:

    MESSAGE ‘<Enter Your Text here>’ TYPE ‘Enter the type of Message here’.

     

    Types of Message

    ABAP provides the following 6 types of messages:

    Message Type Meaning Explanation
    A Termination This message is shown during program termination.
    E Error This message is shown during Error.
    I Information This message is used to show any information.
    S Success This shown in the status of the Output screen.
    W Warning It behaves like an error message.
    X Exit It causes a short dump with error message.

     

    1. Using Predefined Function Modules

    ABAP provides following function modules that can be used to store, format and show messages altogether:

    Function Module Usage
    MESSAGES_INITIALIZE To Initialize the messages.
    MESSAGE_STORE To Store the messages to be displayed.
    MESSAGES_SHOW To Display all the messages together on a pop up
    FORMAT_MESSAGE To Format the messages
    HR_DISPLAY_ERROR_LIST To display all the error messages

    Example:

    1. Using Message Statement
    MESSAGE 'This is an error message' TYPE 'E'.

     

    1. Using Multiple functions to store and show messages:
    " It is Initialized only initially...
    * Initialize your messages
      CALL FUNCTION 'MESSAGES_INITIALIZE'
        EXCEPTIONS
          log_not_active       = 1
          wrong_identification = 2
          OTHERS               = 3.
    
    "One by one append all your messages here
          PERFORM store_messages USING 'E'
                                       w_pn
                                       w_batch2
                                       w_werks
                                       ' '
                                       w_msgno.
    
    FORM store_messages USING p_msgty
                              p_msgv1
                              p_msgv2
                              p_msgv3
                              p_msgv4
                              p_txtnr.
      IF p_msgty EQ 'E'.
        w_err_fg = 'X'.
      ENDIF.
    * Store all your messages meant to be displayed
      CALL FUNCTION 'MESSAGE_STORE'
        EXPORTING
          arbgb                  = 'ZCCH001'
          msgty                  = p_msgty
          msgv1                  = p_msgv1
          msgv2                  = p_msgv2
          msgv3                  = p_msgv3
          msgv4                  = p_msgv4
          txtnr                  = p_txtnr
        EXCEPTIONS
          message_type_not_valid = 1
          not_active             = 2
          OTHERS                 = 3.
    
    ENDFORM.                    " STORE_MESSAGES
    
    "In the end fetch all your message and show them altogether
    * This displays all the messages in a popup
      CALL FUNCTION 'MESSAGES_SHOW'
        EXPORTING
          show_linno         = ' '
        IMPORTING
          e_exit_command     = wa_exit_command
        EXCEPTIONS
          inconsistent_range = 1
          no_messages        = 2
          OTHERS             = 3.
    

     

    1. Using HR_DISPLAY_ERROR_LIST
    DATA:
    
    it_error        TYPE STANDARD TABLE OF HRERROR,"TABLES PARAM
    
    wa_error     LIKE LINE OF it_error .
    
    DATA(ld_no_popup) = 'some text here'.
    
    DATA(ld_no_print) = 'some text here'.
    
    DATA(ld_no_img) = 'some text here'.
    
    DATA(ld_no_msgno) = 'some text here'.
    
    DATA(ld_linesize) = '123 '.
    
    DATA(ld_listheader) = 'Check type of data required'.
    
    DATA(ld_colheader) = 'Check type of data required'.
    
    DATA(ld_hidemsg) = 'some text here'.
    
     
    
     
    
    "populate fields of struture and append to itab
    
    append wa_error to it_error.
    
    .
    
    CALL FUNCTION 'HR_DISPLAY_ERROR_LIST'
    
    * EXPORTING
    
    *   no_popup =                   ld_no_popup
    
    *   no_print =                   ld_no_print
    
    *   no_img =                     ld_no_img
    
    *   no_msgno =                   ld_no_msgno
    
    *   linesize =                   ld_linesize
    
    *   listheader =                 ld_listheader
    
    *   colheader =                  ld_colheader
    
    *   hidemsg =                    ld_hidemsg
    
    * TABLES
    
    *   error =                      it_error
    
      EXCEPTIONS
    
        INVALID_LINESIZE =           1
    
        .  "  HR_DISPLAY_ERROR_LIST
    
    IF SY-SUBRC EQ 0.
    
      "All OK
    
    ELSEIF SY-SUBRC EQ 1. "Exception
    
      "Add code for exception here
    
    ENDIF.

     

  • SAP Smart Styles

    Preface – This post is part of the ABAP Beginner series.

    Introduction

    SAP Smart Styles are used to define paragraph and character formats. It can be assigned to texts and fields in the Smart Forms. A Smart Style has to be assigned to each Smart Forms. This is done globally for the entire Smart Forms in the Form Attributes of the Navigation window. It can be applied locally to a node that applies it to the entire subtree, overruling the global settings. A Smart Style can be reused. It can be downloaded locally and uploaded again later.

    SAP Smart Style Feature

    A Smart Style contains the following features:

    • Header data: It contains the default values of the font for the Smart Style. If different values are not assigned to the paragraph and character formats, the system uses these default values.
    • Paragraph format: It contains information on indents, spacing, font settings, text colors, tabs, numbering, and outline. It must have a unique name for each paragraph format.
    • Character format: It is used to assign special output effects such as superscript and subscript, barcode, and font attribute to sections of texts or character strings within a paragraph. Each character format must have a unique name.
    • Colors and underlines can be added to paragraph and character format.
    • Preview option.

    SAP Smart Style Feature

    Each Smart Styles has 3 predetermined nodes in the navigation window, namely, Header data, Paragraph formats, and Character formats.  The Header node contains the standard settings of the font for the Smart Style. It can be seen in the maintenance window. At the bottom, one can see the preview of the selected font.

    Steps to create Smart Style

    1. SMARTSTYLES is the transaction code for Smart Style. Enter SMARTSTYLES in the common field.

    Steps to create Smart Style

    Note:  SMARTFORMS t-code can also be used to create Smart Styles.

    1. Enter the Style name.
    2. Click on
    3. To activate, click on Activate

    Note: To use and transport a Smart Style, it has to be activated first. During activation, if the system finds any error, it displays an error list.

  • SAP SmartForms Trace

    Preface – This post is part of the ABAP Beginner series.

    Introduction

    The SmartForms trace allows us to trace the processing of the Smart Form during printing. It can be analyzed to determine the sequence of the processing of the nodes and the point at which the processing was terminated due to an error.

    SAP SmartForms Trace

    To trace the SAP SmartForms processing, the SFTRACE transaction is used. When a trace is activated using the generated function module, the Smart Form stores the trace for each output in the database.  The degree of the details of the trace can be set. The trace is automatically deactivated after a day; however, the trace files are retained.  The trace output is user-specific which means it is activated only for the user who activated it.

    Trace Settings

    The following settings are available if the trace is active:

    • Level: Determines the degree of the details of the trace.
    • Logical Page (Name): Restricts the trace output to a specific page.
    • Window: Restricts the trace output to a specific window on a page.
    • ABAP Breakpoints: Warning and Error options are used internally.

    Trace Level

    This determines the degree of the details of the trace. Level 5 contains general information while Level 80 contains the most detailed trace.

    The following are the trace levels:

    • Warning or error (Level 5): It contains trace level, trace version, system date and time, and system information.
    • Document information (Level 15): It contains additional information like output channel, form attributes, form structure, and output results.
    • Pages (Level 30): It contains additional information like the name of the processed pages (except the name of the start page).
    • Window (Level 40): It contains additional information like names of the processed windows
    • Output area (Level 45): It also contains information about the table output area.
    • Cell change (table) (Level 47): It also contains the outputs on line types and cells processed in the tables.
    • Text information (Level 50): It also contains attributes values of the processed output nodes like text elements, text modules, etc.
    • Fields (Level 60): It also contains the names and values of the fields in the text outputs,
    • Scanner token (Level 80): It is the maximum trace level and also contains the scanner outputs when analyzing the texts in the text nodes.

    Activating and Configuring the Trace

    The trace is deactivated by default. To trace the form, trace has to be activated and configured. Steps to activate and configure the trace:

    1. Enter SFTRACE in the common field.

    SAP SmartForms Trace

    1. Click on Switch On Once clicked, the status changes from Trace Inactive to Trace Active.

    SAP SmartForms Trace Admin

    1. Set the trace level and other settings.
    2. Press Enter to confirm the entries.

    Once the trace is active for the user, whenever the Smart Form is called, a new trace is created every time. The trace is automatically deactivated after a day; however to manually deactivate the trace click on Switch Off pushbutton.

     

    Analyzing Trace Output

    Traces are stored in the Traces in the database frame of the SFTRACE transaction window. Use the Refresh button to get the updated trace.

    To analyze the trace in the system:

    1. Select the line by pressing the pushbutton on the left side of the table.

    Traces in Database

    1. Click on Display Trace to see the trace screen.

    Analyzing Trace Output

    The traces can be stored locally by selecting the Export   button. To read the locally stored trace, select Read trace from local file button.

    Trace Output

  • Output Types in SAP SmartForms

    Preface – This post is part of the ABAP Beginner series.

    Introduction

    In classic form printing, the forms are printed using a printer. Smart Forms provides different output types or formats for different use cases. Form Attributes under General Settings node is used to determine the default settings for the form output. The default settings can be overruled using the standard parameters while calling the Smart Forms. In this article we will discuss the Output Types in SAP SmartForms in details.

    Output Types in SAP SmartForms

    Different output types/formats for the SmartForms are:

    • Output Text Format (OTF): It is a standard output format for printing forms in SAP systems. It is the default format in the Form Builder. It can be converted to other formats. It is usually output using spool processing. For this output, in the system, a printer must be set up with a device type that understands OTF.
    • XML for Smart Forms (XSF): It is an XML schema designed for the output of form contents. It does not contain any layout information. It is used to connect to external components of the SAP system to process the contents of the form. To use spool processing for XSF output, at least one printer of type ‘XSF’ must be set in the system.
    • XML Data for Forms (XDF): It is an XML schema that describes the contents of the form. It neither contains the form content nor the layout. To use spool processing, at least one printer of type ‘PLAIN’ must be set in the system. It is stored in the spool in binary format to ensure that no data is lost during conversion.
    • Hypertext Markup Language (HTML): It is a combination of XSF and HTML format that generates the layout information to be able to display into the internet application in order to complete business processes via electronic media rather than using printed mail. The Smart Forms returns a number of structures and tables for HTML outputs.
  • SAP SmartForms Flow Control

    Preface – This post is part of the ABAP Beginner series.

    Introduction

    The flow of the processing of the Smart Form can be controlled using the tree hierarchy defined in the navigation window. In this article we will explain the flow control in SAP SmartForms.

    Conditions affecting Flow Control

    There are multiple options that affect the sequence of the processing of the form.

    Output Conditions:

    This is used to suppress the processing of individual nodes or entire subtrees in the tree structure.

    • To enter the output condition, select the node and go to the Condition tab in the maintenance window.
    • In this tab, a condition can be entered with two operands in each line. An operand can be a value or a field. To select a comparison operator, press on the pushbutton between the two columns. The most important operators are AND and OR. By default, the conditions are evaluated using AND
    • Perform local check to validate output conditions.
    • The output conditions can be linked to output events of pages and windows. Using AND condition in Additional event box is used to link them.

    When the conditions are met, the system processes the nodes/sub-nodes according to the condition value. If not, the system ignores the current node and its sub-nodes.

     

    Alternative Execution:

    It is used to process one of two inferior nodes. To do so,

    • Create a Alternative node in the navigation tree.
    • On the General Attributes tab, define an unstructured condition in the Node Conditions
    • This node has two directly inferior nodes: TRUE and FALSE. Insert the inferior nodes here.
    • Perform local check to validate output conditions.

    If the condition is met, the system processes the directly inferior node TRUE, if not, FALSE.

    Repeated Output:

    To process the output repeatedly, loop nodes are used which reads the data from the internal table line by line. To do so,

    • Create a Loop node in the navigation tree.
    • Enter a unique name and description for the node.
    • Read the data from an internal table to a work area and create inferior nodes that display the fields of the read table lines.

     

    Dynamic Processing:

    This is done by page sequence and numbering. This is determined by

    • The Next page attribute
    • The volume of the data and space available in the main window
    • As soon as a page is full, the Smart Form triggers a page break, known as a dynamic page break.

    During the processing of the form, the system maintains internal counters, which can be used to display the current page number.

  • Node Types in SAP SmartForms

    Preface – This post is part of the ABAP Beginner series.

    Introduction

    When a Smart Form is created, the form builder already has two nodes in the Navigation window. “Global Settings” and “Pages and Windows” are the two roots that are created by default for every Smart Form.  In this article we will explore more about Node Types in SAP SmartForms.

    Nodes in SAP SmartForms

    The inferior nodes of the Global Settings are used to maintain Form Attributes, Form Interface, and Global Settings.

    The inferior nodes of the Pages and Windows are used to create pages of the form, position elements on the pages, and determine the flow of the process of the elements.

    Each sub-node of the two root nodes has attributes. These attributes are maintained in the Maintenance Window. The attributes that can be maintained are General Attributes, Output Options and Conditions are the same for almost every type of the nodes.

    • General Attributes shows the general description of the node.
    • Output Options contain properties such as Positions, Style, Box and Shading. It may have additional options depending on the position of the node.
    • Conditions allow the processing of the node only if the conditions are true.

    Node Types in SAP SmartForms

    Let’s discuss the types of nodes:

    1. Output Areas:

    Output Areas

    1. Elementary Nodes:

    Elementary Nodes

    1. Table Outputs:

    Table Outputs

     

    1. Flow Control:

    Flow Control