Rfc Connector Help

Introduction to Rfc Connector

What is Rfc Connector?

Rfc Connector is a COM object library which enables easy access to SAPTM systems from almost any programming or scripting language on the Microsoft WindowsTM platform. Besides calling SAP function modules and BAPIs with both RFC and SOAP, Rfc Connector allows applications to receive function calls from SAP ("RFC Server"), to read data from SAP tables and to integrate Business Server Pages (BSP) and WebDynpro screens. Rfc Connector supports Unicode (international character sets) and SSO (Single Sign On) and is compatible with all SAP systems from release 4.0 onwards.

  • Using Rfc Connector
  • Advanced Topics
  • Examples
  • Reference
  • Getting Support


Using Rfc Connector

RFC Connector consists of several COM objects which facilitate calling Function Modules and BSP Applications from SAP Systems.

Function Modules can be called using either SAP's own RFC protocol, or SOAP (SOAP is not available with Basis Releases prior to 4.6C).

To use RFC, you must have LIBRFC32U.DLL and its dependent DLLs installed at your system, either by installing SAPGUI or the RFC SDK, which are both available for download to SAP customers at the SAP Service Marketplace.

Please refer to Knowledge Base Entry #0009 for information on how to obtain and install this library.

Quick Start: Calling your first BAPI

To call a Function Module using RFC, create an Instance of RfcSession, fill its LogonData and RfcSystemData properties, and connect to the SAP System using the connect() method:

  RfcSession session = new RfcSession();

  session.RfcSystemData.ConnectString = "SAPLOGON_ID=ABC";

  session.LogonData.Client = "000";
  session.LogonData.User = "TEST";
  session.LogonData.Password = "***";
  session.LogonData.Language = "EN";

  session.Connect();

Use ImportCall to import a function call prototype:

  FunctionCall func = session.ImportCall("BAPI_FLIGHT_GETLIST");

Set the importing parameters

  func.Importing["AIRLINE"].value = "LH";

Call the function

  session.CallFunction(func, true);

Read out the results

  for (int i=1;i<=func.Tables["FLIGHT_LIST"].Rows.Count;i++)
  {
    Console.WriteLn(func.Tables["FLIGHT_LIST"][i]["FLIGHTDATE"].Value.ToString());
  }

Tasks in Detail

  • Importing the Rfc Connector library
  • Connecting to SAP systems
  • Calling function fodules
  • Using parameters
  • Reading database tables
  • RFC servers
  • BSP Applications
  • Advanced Topics


Importing the Rfc Connector library

Before you can work with Rfc Connector, it is necessary to add a reference to the library itself to your project. In Visual Studio, this is done by right-clicking the project in the Solution Explorer and selecting "Add Reference".

In the Add Reference window, go to the "COM" tab and select "secept Rfc Connector":

Screenshot: Adding the Rfc Connector reference

Adding the namespace

Though not strictly necessary, importing the RFCCONNECTORLib namespace into your project will save you a lot of unnecessary typing.

In C#, you can import a namespace with the using directive:

    using RFCCONNECTORLib;

In VB.NET, the namespace can be imported globally in the references tab of the project settings dialog:

Importing namespace in Visual Basic .NET

Next: Connecting to SAP Systems


Connecting to SAP systems

Determining connection parameters for RFC

To be able to connect a SAP system, you need to know the connection parameters. In our example, we assume that you have a system named EX1 located at the server myserver with system number 00. If you are not sure what your hostname and system number are, you can look them up in SAPLogon:

Screenshot: Using SAPLogon to determine the hostname and system number

If you are using a message server (load balancer), your connection string will look like that:

    Dim session as New RfcSession
    session.RfcSystemData.ConnectString = "MSHOST=msgserver MSSERV=myservice"
If you are using an appserver without message server instead, use
    Dim session as New RfcSession
    session.RfcSystemData.ConnectString = "ASHOST=myhost SYSNR=00"

Alternatively, you can reference the entry in SAP Logon instead of specifying parameters directly:

    Dim session as New RfcSession
    session.RfcSystemData.ConnectString = "SAPLOGON_ID=EX1"

Determining connection parameters for SOAP, BSP and Web Dynpro

For SOAP, BSP and Web Dynpro connections, there is no connection string, but instead a hostname or IP (which is equal to the hostname and IP in the SAP Logon shown above) and a port number, which is typically 8000+system number, e.g. 8001 for SYSNR=01, but may be configured differently. If in doubt, ask your system administrator about the web service port or check with transaction SMICM(use "GoTo" -> "Services"):

    Dim session as New SOAPSession
    session.HttpSystemData.Host = "myhost"
    session.HttpSystemData.Port = "8000"

Setting logon data

The SAP system won't let you connect without proper authorization, which means you need to set at least the SAP client (a 3-digit number), a user and a password. You can also set the language in which you want to receive translateable texts such as error messages:

    session.LogonData.Client = "001"
    session.LogonData.User = "DEVELOPER"
    session.LogonData.Password = "developer"
    session.LogonData.Language = "DE"

Connecting and checking for errors

Now that all is set up properly, it's time to connect to the system. If Rfc Connector cannot connect for some reasons, the Error property will be set to true and the ErrorInfo property will contain details about the error:

    session.Connect()

    If session.Error Then
        MsgBox(session.ErrorInfo.Message)
        Exit Sub
    End If
If you get an error about insufficient permissions, ask your system administrator to add S_RFC, S_RFCACL and S_RFC_VERS permissions to your user, or assign the profile SAP_ALL (the latter is not recommended in production for security reasons).

Next: Calling Function modules


Calling Function Modules

In this chapter, we will show step by step how to call a function module in SAP with RFC Connector.

Note: This example is written using Visual Basic .NET, however you can use any language which supports COM with RFC Connector. See the Example Section for examples how RFC Connector can be used in other languages.

Importing a function module

Before you can call a function module, you must know its signature, that means the type and name of the parameters. The function prototype can be imported from the SAP system with the ImportCall() method.

    Dim fn as FunctionCall
    fn = session.ImportCall("BAPI_FLIGHT_GETLIST")

Setting outgoing parameters

The function module BAPI_FLIGHT_GETLIST has a number of IMPORTING parameters, which can be used to select which table entries will be returned.

To find out about the parameters of a function module and their meaning, you can use the BAPI browser (transaction code BAPI) or the function builder (transaction code SE37) from SAP GUI

To access IMPORTING parameters, use the Importing property of the function call object. For this example, we want to retrieve all flights of American Airlines ("AA") starting from San Francisco ("SFO"). Note that the AIRLINE parameter is a scalar value, whereas the DESTINATION_FROM parameter is a structure, for which the individual fields can be accessed through the Fields property. The different types of parameters will be discussed in more detail in the next chapter, Using Parameters).

    fn.Importing("AIRLINE").value = "AA"
    fn.Importing("DESTINATION_FROM").Fields("AIRPORTID").value = "SFO"

Calling the function

After all importing parameters are set, it's time to call the function. The second parameter to the CallFunction function determines whether the call will be blocking (the function returns only after the results has been received from SAP) or non-blocking (the function returns immediately and the data is received in the background). After calling the function, it's good to check again for errors:

    session.CallFunction(fn, True)

    If session.Error Then
        MsgBox(session.ErrorInfo.Message)
        Exit Sub
    End If

Processing the call results

Since we made our call synchronous (blocking), we can process the result right here. If the call would have been asynchronous, we would have to either poll the CallActive property, or subscribe to the CallFinished-Event.

To read the rows of the FLIGHT_LIST table, we can simply enumerate the Rows property with For Each:

    For Each Row In fn.Tables("FLIGHT_LIST").Rows
        Console.WriteLine(Row("AIRLINE").value & " " & Row("FLIGHTDATE").value)
    Next
If you do not receive any result although there is no error, you might need to run the report SAPBC_DATA_GENERATOR to fill the tables with some demo data.

In the next section we'll be looking at parameters in more detail.


Using Parameters

The difference between Importing, Exporting, Changing and Tables

SAP function modules have four parameter lists: Importing, Exporting, Changing and Tables. The various parameter lists differ on whether they are transported to the function, returned back from the function, or both:

  • Importing parameters are transported from the caller to the function module
  • Exporting parameters are transported from function module to the caller
  • Changing parameters are transported in both directions
  • Tables parameters are also transported in both directions, and are multidimensional (=of type Table). Also, other than Exporting and Changing parameters, Tables are transported back even when the function module throws an exception (Exporting and Changing parameters are empty in this case).

Scalar parameters, Structs and Tables

There are different types for individual parameters in SAP: scalar values, which consist of a single value (for example, a string, a date or a numeric value), structures, which consist of several fields (just like a struct in C/C++/C# or VB), and tables, which consist of rows and columns.

Scalar Parameters

Scalar parameters only have a single value, which can be read and written through the value property of the respective parameter:

    ' in Visual Basic, use regular brackets to access parameters
    fn.Importing("AIRLINE").value = "AA"
    ' ...
    result = fn.Exporting("RETVAL").value

    // in C#, use square brackets instead
    fn.Importing["AIRLINE"].value = "AA";
    // ...
    string result = fn.Exporting["RETVAL"].value;

Structs

Structs are sets of several (scalar) values, and can be accessed to the Fields property of the respective parameter:

    ' Visual Basic
    fn.Importing("DESTINATION_FROM").Fields("AIRPORTID").value = "SFO"
    ' ...
    message = fn.Exporting("BAPIRET").Fields("MESSAGE").value

    // C#
    fn.Importing["AIRLINE"].value = "AA";
    // ...
    string message = fn.Exporting["BAPIRET"].Fields["MESSAGE"].value

Tables

Tables are multidimensional arrays consisting of rows and columns (like a spreadsheet). Since technically SAP (and Rfc Connector) represents them as arrays of structs, always the row is first selected and then the column. You can either enumerate rows with For Each, or you can access single rows by its row number.

Iterating through all rows of a table

    ' Visual Basic
    For Each Row In fn.Tables("FLIGHT_LIST").Rows
        Console.WriteLine(Row("AIRLINE").value)
    Next

    // C#
    foreach (RfcFields row in fn.Tables["FLIGHT_LIST"].Rows)
    {
        Console.WriteLine(Row["AIRLINE"].value);
    }

Accessing rows by index

In SAP and Rfc Connector, numerical indexes to arrays always start with 1, which means that Rows[1] yields the first row, whereas Rows[0] is not defined and accessing it will cause a runtime error.
    ' Visual Basic
    data = fn.Tables("RESULTS").Rows(1).Fields("DATA").value

    // C#
    data = fn.Tables["RESULTS"].Rows[1].Fields["DATA"].value;
    // short notation, possible in C#, but not in VB
    data = fn.Tables["RESULTS"].Rows[1]["DATA"].value;

Adding rows to a table

To add rows to a table, use the AddRow method to add a single row, or AddRows to add a number of rows:

    ' Visual Basic
    row = fn.Tables("DATA").Rows.AddRow()
    row("FIELD1").value = "foo"

    // C#
    RfcFields row = fn.Tables["DATA].Rows.AddRow();
    row["FIELD1"].value = "foo";

Parameter conversion

Rfc Connector automatically converts values between SAP Types and VARIANT using the following conversion methods:

SAP Type | VARIANT Typecode | Description
CHAR, STRING | VT_BSTR | string
NUM, BCD | VT_BSTR | string consisting only of digits (0-9), decimal point(.) and minus sign(-)
BYTE, XSTRING | VT_ARRAY|VT_UI1 | array of bytes
FLOAT | VT_R8 | double
DATE | VT_DATE | date
TIME | VT_DATE | time

Working with SAP Dates and Times

SAP internally represents dates as 8-character strings (YYYYMMDD) and times as 6-character strings (HHMMSS), whereas VARIANT and .NET have a special DateTime type. For data going to SAP, Rfc Connector accepts both formats, in addition to date strings using the current locale/culture (for example, 03/31/2010 in en-us culture). Data coming from SAP will automatically be converted into DateTime objects. For time values, only the Hour, Minute and Second are considered, whereas the other members of the DateTime object are undefined. SAP also has a 15-character TIMESTAMP type (YYYYMMDDHHMMSS), which is rarely used and NOT converted by Rfc Connector in either direction (since it is not a real ABAP datatype, but merely a database convention)

    ' dates in VB
    fn.Importing("DATE").value = "20100331" ' this is safe for all cultures
    fn.Importing("DATE").value = "03/31/2010" ' not recommended, will cause error in non-US locale
    fn.Importing("DATE").value = new DateTime(2010,03,31) ' safe for all cultures

    Dim dt as DateTime
    dt = fn.Exporting("DATE").value
    year = dt.Year

    // dates in C#
    fn.Importing["DATE"].value = "20100331";   // safe for all cultures
    fn.Importing["DATE"].value = "03/31/2010"; // not recommended, will cause error in non-US locale
    fn.Importing["DATE"].value = new DateTime(2010,03,31); // safe for all cultures

    DateTime dt = fn.Exporting["DATE"].value;

Next: Reading database tables


Reading database tables

With the TableReader object it is possible to read data from SAP tables quite easily.

Simple call

To read all rows of a database table, simply call the Read() method, leaving all other parameters unchanged

    Dim tr As TableReader
    tr = session.GetTableReader("SFLIGHT")
    tr.Read(0,0)
    For Each row in tr.Rows
        Console.WriteLine(row("FLDATE").value & " " & row("CONNID").value)
        ' ...
    Next

Limiting the number of rows

The parameters of the Read method can be used to limit the number of rows to be read, and to determine the starting row:

    Dim tr As TableReader
    tr = session.GetTableReader("SFLIGHT")
    ' read 20 rows, starting with row #10
    tr.Read(20,10)

Reading only some columns

To reduce the amount of transfered data and to overcome the 500 character width limit (see below), it is possible to specify the desired columns with the Fields property:

    Dim tr As TableReader
    tr = mySession.GetTableReader("SFLIGHT")
    ' read only CONNID and FLDATE
    tr.Fields.Add("CONNID")
    tr.Fields.Add("FLDATE")
    tr.Read(0,0)

Filtering rows

With the Query property, it is possible to only read rows which meet certain criteria. The Query property consists of one or more rows (max. 72 characters per row) which together form an ABAP/Open SQL WHERE statement:

    Dim tr As TableReader
    tr = mySession.GetTableReader("SFLIGHT")
    ' read only rows where CARRID has the value 'LH'
    ' note that constant values must be quoted with single quotes
    tr.Query.Add("CARRID EQ 'LH'")
    tr.Read(0,0)

TableReader permissions

The TableReader internally uses the RFC_READ_TABLE function module, which is present in every SAP system. The user which is used in the TableReader's session must have the necessary permissions to call the RFC_READ_TABLE function module, and must also have S_TABU_DIS and S_TABU_CLI permissions (activity '03') for the table(s) being read.

500 Character Row Width Limit

RFC_READ_TABLE limits the width of the columns being read to 500 characters. If your table is wider than 500 characters, you will get a DATA_BUFFER_EXCEEDED exception.

To overcome this limitation, you can either

  • use the Fields property to limit the number of columns or
  • (if you have a development user) copy the RFC_READ_TABLE module to a new module (e.g. ZRFC_READ_TABLE), and copy the TAB512 structure to another struct (e.g. TAB4096). After this, change the DATA to use the new structure, and make the WA field of the newly created struct sufficiently wide. Finally, call tr.Option("tablereader.transportcall") = "name_of_new_function_module"
    • so the TableReader will use the new function instead of RFC_READ_TABLE).

Transfering data in raw format

As with function calls, TableReader will convert received SAP datatypes to VARIANT, as described in Parameter Conversion. If this conversion is not desired, it can be turned off with the tablereader.rawstrings option. In this case, there will be no conversion and all fields are transmitted as strings in the internal SAP format.

    tr.Option("tablereader.rawstrings") = "1"

Next: RFC servers


RFC servers

The RfcServer object allows you to add RFC Server functionality to your program.

Introduction to RFC servers

In some situations, the flow of events does not originate from the client application, but from the SAP system itself. For example, the SAP system may send IDOCs to notify another application about data changes, or a SAP transaction may delegate calculations or acquire additional data to/from a third party system. When for these kind of communications RFC is used, the application in question needs to implement a RFC server.

In SAP, possible destinations for remote function calls are called "RFC destinations". The list of available RFC destinations can be administered with transaction SM59. For each RFC destination in SM59 (for Rfc Connector, only the "TCP/IP connections" subtree is relevant), a Program ID and an activation type is maintained. For RFC servers created with Rfc Connector, the activation type is always "Registered Server Program"

When the RFC server is started, it registers with the SAP system and the Program ID, which must match the one defined in SM59. Through this registration, the SAP system knows the address of the listener(s) and is now able to dispatch RFC calls to them. You can check available listeners for a specific RFC destination with the "Connection Test" button in SM59, and you can get a list of all listeners currently registered with transaction SMGW (use "Go To"->"Logged In Clients")

Implementing an RFC server

To implement an RFC server which can receive function calls from SAP, the following steps are necessary:

  1. Create a server object and set the necessary parameters: GatewayHost, GatewayService, ProgramID
  2. Create or import one or more FunctionCall prototypes and install them using the InstallFunction method
  3. (optional) Subscribe to the Logon event, if you want to control access to your server
  4. Subscribe to the IncomingCall event
  5. Run the server and wait for incoming calls

Create a server and set the necessary parameters

Create an instance of RfcServer and set the necessary parameters: ProgramID determines the program id under which to register (as configured in SM59), GatewayHost is the host name (or IP) of the SAP system to register with, and GatewayService determines the system number (port) of this SAP system:

The parameter GatewayService is given in form of a string starting with "sapgw" followed by the 2-digit system number. For example, SYSNR=00 in a connection string corresponds to sapgw00, SYSNR=01 corresponds to sapgw01, and so on.

    Dim WithEvents srv As RfcServer 'WithEvents is important here
    srv = New RfcServer
    srv.ProgramID = "ZRFCCTEST"
    srv.GatewayHost = "mysaphost"
    srv.GatewayService = "sapgw01"

Create a function call and install it to the server

To be able to decode the incoming parameters, Rfc Connector needs to know the signature/prototype of the RFC function(s) which are going to be called. In this case, we just import it from the server, but it would also be possible to load it from serialized XML or build it manually:

    ' import function definitions
    Dim Session as New RfcSession
    Dim prototype as FunctionCall, fn2 As FunctionCall
    Session.RfcSystemData.ConnectString = "SAPLOGON_ID=N4S"
    Session.LogonData.Client = "001"
    Session.LogonData.User = "user"
    Session.LogonData.Password = "password"
    Session.Connect()
    If Session.Error Then
        Console.WriteLine("Error: " + Session.ErrorInfo.Message)
    End If
    prototype = Session.ImportCall("BAPI_FLIGHT_GETLIST")
    Session.Disconnect()

    ' now register them with server
    srv.InstallFunction(prototype)

Subscribe to the Logon event

Now we add a handler for the Logon event, which is used to determine whether a request is allowed or not. For this example, we just check the username:

Subscribing to the Logon event is optional. If you do not subscribe to this event, every access will be accepted automatically (which is fine if your service does not require special protections)
    Private Sub srv_Logon(ByVal li As RFCCONNECTORLib.RfcServerLogonInfo) Handles srv.Logon
        If li.User = "DEVELOPER" Then
            li.RequestAllowed = True
        Else
            li.RequestAllowed = False
        End If
    End Sub

Subscribe to the IncomingCall event

In the handler for the IncomingCall event, the actual request processing is done. To keep this example simple, we reply with some static data only (real-world examples would be, of course, much more complex):

If parameters are marked "optional" in the function module definition, they may not be set by the caller. Therefore, for optional parameters use the HasKey-function to check whether they are set or not before accessing them. Otherwise, you would get an exception.
    Private Sub srv_IncomingCall(ByVal fn As RFCCONNECTORLib.FunctionCall) Handles srv.IncomingCall
        Select Case fn.Function
            Case "BAPI_FLIGHT_GETLIST"
                Dim airline As String, dest_from As String, dest_to As String
                If fn.Importing.HasKey("AIRLINE") Then
                    airline = fn.Importing.HasKey("AIRLINE")
                Else
                    airline = "LH"
                End If

                If fn.Importing.HasKey("DEST_FROM") Then
                    dest_from = fn.Importing.HasKey("DEST_FROM")
                Else
                    dest_from = "SFO"
                End If

                If fn.Importing.HasKey("DEST_TO") Then
                    dest_from = fn.Importing.HasKey("DEST_TO")
                Else
                    dest_from = "JFK"
                End If

                ' add some static rows
                Dim r As RfcFields, dt As DateTime
                dt = DateTime.Today
                For i = 1 To 10
                    r = fn.Tables("FLIGHT_LIST").Rows.AddRow()
                    r("AIRLINEID").value = airline
                    r("AIRPORTFR").value = dest_from
                    r("AIRPORTTO").value = dest_to
                    r("CONNECTID").value = i
                    r("FLIGHTDATE").value = dt.AddDays(i)
                Next
            Case Else
                ' we don't know about this function, so we raise an exception
                fn.RaiseException("SYSTEM_ERROR")
        End Select
    End Sub

Run the server and wait for incoming calls

Now that we have implemented our handlers, it is time to start the server and wait for incoming calls (this is done in the main method). Note that the server always runs in another thread, so Run() will always return immediately after registering with the SAP system. In this example, we will run the server until the user presses a key:

    If srv.Error Then
        Console.WriteLine("Error: Could not start server.")
        Console.WriteLine(srv.ErrorInfo.Message)
        Exit Sub
    End If

    Console.WriteLine("Server running. Press key to stop...")
    Console.ReadLine()

    srv.Shutdown()

    Console.WriteLine("Server exited. Press key to leave...")
    Console.ReadLine()

Handling errors while the server is running

It may happen that the server encounters an error (for example, a temporary network problem, or the SAP host being restarted) while listening for requests.

To handle these cases, applications should subscribe to the ServerError event, which offers also an option to just restart the server (which is recommended for servers which are designed to run unattended for a longer time):

    Private Sub srv_ServerError(ByVal ei As RFCCONNECTORLib.RfcServerErrorInfo) Handles srv.ServerError
        ' log the error to console
        Console.WriteLine(ei.Message)
        ' restart the server
        ei.Restart = True
    End Sub

Next: BSP and Web Dynpro applications


Using BSP and Web Dynpro Applications

RFC Connector offers a simple and straightforward way of integrating SAP web applications like Web Dynpro and BSP.

Using the BSPApplication object offers several advantages in comparison to launching the application in the web browser:

  • You can preset user and password; SSO is also supported
  • You have complete control about the window size, title and position
  • BSPApplication windows are modal (blocking the UI of the host application)
  • BSPApplication windows have no back buttons or address bar, so the user cannot navigate away
  • BSPApplication can return parameters from the web app to the host application
  • The web app can close itself, and you can (optionally) warn the user if he uses the close button

Creating a BSPApplication object

Before calling the web application, you must create the BSPApplication object, and set its HttpSystemData, LogonData and Window properties:
The port number is normally Sysnr+8000. You can look it up in the system with transaction SMICM (use "GoTo" -> "Services")

 Dim bsp As New BSPApplication

 bsp.HttpSystemData.Host = "myhost"
 bsp.HttpSystemData.Port = "myport"

 bsp.Window.Left = 100
 bsp.Window.Top = 100
 bsp.Window.Height = 800
 bsp.Window.Width = 600
 bsp.Window.Title = "My BSP Window"

 bsp.LogonData.Client = "000"
 bsp.LogonData.User = "myuser"
 bsp.LogonData.Password = "mypassword"
 bsp.LogonData.Language = "en"

Optionally, you can define a warning message which is displayed when the user clicks on the close button:

 bsp.Window.CloseWarning = "Do you really want to close this window?" & vbCrLf & "Data loss may occur"

Calling the Application

Before you can use a BSP Application, you need to activate it in the SAP System using transaction SICF

To launch a BSP Application, we call the ShowApplication method:

 bsp.ShowApplication "/sap/bc/bsp/sap/htmlb_samples/default.htm"

Exit Pages

Sometimes it is useful for a web application to return values to the caller, and/or to close itself when the user has finished working with it. With RFC Connector, these functionality can be implemented by using exit pages.

The idea behind exit pages is that a web application contains links or buttons which link to a special page (the exit page). If the user navigates to that page, the BSPApplication object intercepts that navigation, closes the window and returns the parameters submitted.

In the following section, we implement a simple BSP application which contains an input field and a button. If the user presses the button, the value entered in the input field is transmitted to the calling program.

Source Code for the BSP Application

The following code must be entered in the SAP system. To create the web application in SAP, use transaction SE80. In SE80, choose "Workbench" -> "Edit Object" -> "Web Objects" -> "BSP Application" and enter Z_EXITPAGE as name. After the application is created, create a page named index.htm by right-clicking the Z_EXITPAGE node on the left and choosing "Create" -> "Page" from the context menu. Select "Page with Flow Logic" as page type, then paste the following source code

Source Code (Plain HTML)

<html>
 <body>
  <form action="ExitPage.htm">
   <input type="text" name="input1" />
   <input type="submit" value="Exit Application" />
  </form>
 </body>
</html>

Alternative Source Code (HTMLB)

If you are using HTMLB, the code is slightly more complicated, because you need to call the exit page in an event handler. Here's the sample page source in HTMLB:

<%@page language="abap"%>
<%@extension name="htmlb" prefix="htmlb"%>

<htmlb:content>
 <htmlb:page title = "Exit Page Example">
  <htmlb:form>
   <htmlb:inputField   id            = "Input1" />
    <htmlb:button      text          = "ExitApplication"
                       onClick       = "ExitButtonClick" />
   </htmlb:form>
 </htmlb:page>
</htmlb:content>

Note that we do not navigate to the exit page here, because that happens in the OnInputProcessing event handler:

* event handler for checking and processing user input and
* for defining navigation

DATA: event TYPE REF TO cl_htmlb_event,
      value TYPE string.

event = cl_htmlb_manager=>get_event( runtime->server->request ).
IF event->name = 'button' AND event->event_type = 'click'.
  value = request->get_form_field( 'input1' ).

  navigation->set_parameter( name = 'input1' value = value ).
  navigation->goto_page( 'ExitPage.htm' ).
ENDIF.

Source Code for the calling program

Regardless of whether you went for the plain HTML or HTMLB solution above, the coding on the client side is the same: Call ShowApplication with the name of your exit page as the second parameter, and read out the Parameters property after the method has returned:

 bsp.ShowApplication "/bc/bsp/sap/z_exitpage/index.htm", "ExitPage.htm"

 MsgBox "You have entered " & bsp.Parameters("input1").Value

Using Single Sign On (SSO)

Single Sign On with BSPApplication is not different to Single Sign On with sessions. Just set the SSO cookie to LogonData.SSO2Ticket and call the application.

More Information about SSO


Advanced Topics

The following sections contain more information about advanced topics:

  • Single Sign On (SSO)
  • Transactional RFC (tRFC)
  • Rfc Connector in 64-Bit (x64) Environments
  • Troubleshooting: Debugging and Tracing
  • Upgrading from Rfc Connector 1.0


Single Sign On (SSO)

RFC Connector can retrieve SAP SSO2 tickets via RFC, and can use them to authenticate against an SAP backend using RFC or BSP.

Recommended reading about Single Sign On: Single Sign On in the SAP Library, Note 352295, Note 595341. Access to SAP Notes requires a SAP customer ID.
If you want to retrieve SSO2 tickets from non-Unicode Systems you might need to install Note 1293856, which contains a kernel patch to resolve a unicode- and SSO-related bug in the RFC library.

To retrieve a SSO2 ticket, use the following code:

Dim sess As new RfcSession, ticket As String

sess.RfcSystemData.ConnectString = "ASHOST=myhost SYSNR=mysysnr SNC_MODE=1 SNC_PARTNERNAME=p:SAPServiceXXX@mydomain SNC_LIB=gsskrb5.dll GETSSO2=1"

sess.Connect
ticket = sess.GetSSO2Ticket
sess.Disconnect

To use an existing SAPSSO2 cookie to authenticate, just set the SSO2Ticket property of the LogonData object:

sess.LogonData.SSO2Ticket = ticket


Transactional RFC (tRFC)

Rfc Connector supports both sending outbound and receiving inbound tRFC calls. tRFC is an extension to the RFC protocol which guarantees that a function module call is executed exactly once at the receiving side.

More information about tRFC can be found in the SAP Library.

Limitations of tRFC

Since tRFC is executed asynchronously, tRFC modules cannot return data to the caller (similar to CALL FUNCTION '...' IN UPDATE TASK). Therefore tRFC modules only support IMPORTING and TABLES parameters. EXPORTING and CHANGING parameters will be ignored by Rfc Connector when sending outbound tRFC calls, and will cause syntax errors in SAP if used for inbound calls.

Sending outbound tRFC calls with RfcSession

To send an outbound tRFC call with Rfc Connector, the following steps are necessary:

  1. Obtain a function module prototype through ImportCall(), by importing it from XML or by manually constructing it.
  2. Obtain a Transaction ID (TID) by calling Session.CreateTransID().
  3. Call the function module with Session.CallTRFCFunction(), using the TID from step 2.
  4. If the call fails, CallTRFCFunction can be called again later. As long as the same TID is used, the function module will be executed no more often than once in the target system.
  5. After successfully calling CallTRFCFunction(), call ConfirmTransID() to allow the target system to clean up its internal storage.

Note: You can use transaction SM58 to list recent transactions. Transactions for which ConfirmTransID() has been called will be deleted from this view (so for debugging purposes you might want to skip that call).

Receiving inbound tRFC calls with RfcServer

The RfcServer object can receive both regular and transactional RFC calls. To receive tRFC calls, the following steps are necessary:

  1. Implement a regular RFC server by registering the function prototype and subscribing to the IncomingCall and (optionally) the Logon event(s).
  2. Subscribe to the TransactionCheck event and implement a function which stores and checks the received transaction IDs. Implementations of this event are expected to keep track of the state of each transaction and return the appropriate result. Subscribing to this event and returning the appropriate result is required for tRFC. Servers which run more than one listener thread are also expected to implement appropriate locking on their behalf.
  3. Subscribe to the TransactionCommit event if your persistent storage supports transactional features (e.g. if your storage is a database, issue COMMIT WORK in response to this event). Subscribing to this event is optional.
  4. Subscribe to the TransactionRollback event if your persistent storage supports transactional features (e.g. if your storage is a database, issue ROLLBACK WORK in response to this event). Subscribing to this event is optional.
  5. Subscribe to the TransactionConfirm event to clean up your transaction state-tracking datastore. For example, if you use a database table to keep track of ongoing transactions, you can use this event to delete rows relating to the given TID. Subscribing to this event is optional.

Note: tRFC is currently not supported with SOAP clients.


Rfc Connector in 64-Bit (x64) Environments

Overview

Generally, Rfc Connector can be used in both 32- and 64-Bit Environments. However, since there exists no native SAP GUI for 64-Bit platforms, Rfc Connector itself is a native 32-Bit (x86) library which will run in the WoW6432 subsystem on x64 Windows.

Since native 64-bit applications cannot link to 32-bit libraries directly, applications using Rfc Connector must always be compiled for the x86 (32-bit) Platform.

Deploying Rfc Connector in a 64-Bit Environment

There are no special procedures necessary for deploying 32-bit Rfc Connector applications on 64-bit Windows because the WoW6432 subsystem will be activated automatically when the application is started.

Developing with Rfc Connector in a 64-Bit Environment

You can develop applications with Rfc Connector on 64-bit Windows just as you would with 32-bit Windows. However, you need to make sure that your project is configured to compile for x86 (32-bit) platforms only. Applications compiled for x64 or for "Any CPU" (.NET) would throw an exception when trying to access Rfc Connector objects.


Troubleshooting

Debugging in SAP

With SAP Basis Release 6.20 and higher, you can debug server-side code quite easy by using external breakpoints.

To debug a function module using external breakpoints, simply start transaction SE37 in SAP, open the function module in question and set an external breakpoint.

Then a debugger window will automatically pop up every time the function module is called with Rfc Connector.

Debugging in Visual Studio

Rfc Connector supports debugging the calling code as well as any event handlers through the Visual Studio debugger. To debug .NET code, set the debug mode to "Managed Code only" in the project preferences.

Trace files

RFC connector has some tracing capabilities which can be used to track down problems.

To enable tracing, use the following code:

// enable tracing for client
session.Option("trace.file") = "path\to\tracefile.txt"
// enable tracing for server
server.Option("trace.file") = "path\to\tracefile.txt"

Enabling the Rfc Connector trace will automatically enable the RFC library trace, too. The RFC library trace files will always be created in the current working directory, regardless of the path used for the Rfc Connector trace. Therefore it is recommended to change the current working directory to a suitable location before enabling the trace. In .NET, you can use the System.IO.Directory.SetCurrentDirectory() system call for this purpose.


Upgrading from Rfc Connector 1.0

To upgrade a project from Rfc Connector 1.0 to 2.x, the following steps are necessary:

  1. Uninstall Rfc Connector through the Control Panel and remove all instances of RfcConnector.dll and RfcConnectorInterop.dll
  2. Install the new version of Rfc Connector
  3. Recompile your project(s). This is necessary because some interfaces have been extended from Rfc Connector 1.0.
  4. In most cases, it will not be necessary to change the code, since properties and methods which were present in Rfc Connector 1.0 are still supported.

    However, due to naming conflicts with .NET it was necessary to rename the Type property of the Field object to RfcType. Most programs don't need to access this property anyway, but if your project does, you need to change the property name from Type to RfcType before you can recompile your project.
  5. If you roll out your project to a different machine, don't forget to upgrade Rfc Connector installation there, too, when rolling out the new version. It is not possible to have more than one version of Rfc Connector installed globally on one machine. It is, however, possible to have different versions at the same time by using techniques like COM side-by-side or Registration-Free COM Interop (see MSDN for details).


API Reference

  • ABAPTYPE
  • ERRORGROUP
  • RFCTYPEKIND
  • BSPApplication
  • BSPParameter
  • FunctionCall
  • FunctionCalls
  • HttpSystemData
  • LicenseData
  • LogonData
  • RfcError
  • RfcField
  • RfcParameter
  • RfcRows
  • RfcSystemData
  • RfcType
  • TypeCache
  • WindowProperties
  • Session
  • RfcSession
  • SoapSession
  • RfcServerErrorInfo
  • RfcServerLogonInfo
  • RfcServer
  • RfcServerTransactionInfo
  • TableReader


ABAPTYPE

Description

This enumeration contains a list of the supported scalar types:

Internal Type | Numeric Value
TYPE_CHAR | 0x00
TYPE_BCD | 0x01
TYPE_DATE | 0x02
TYPE_TIME | 0x03
TYPE_BYTE | 0x04
TYPE_NUM | 0x06
TYPE_FLOAT | 0x07
TYPE_INT | 0x08
TYPE_INT2 | 0x09
TYPE_INT1 | 0x0A
TYPE_STRING | 0x1D
TYPE_XSTRING | 0x1E

Use the following table to map builtin ABAP types to RfcConnector types:

ABAP Type | Internal Type
ACCP | TYPE_CHAR
CHAR | TYPE_CHAR
CLNT | TYPE_CHAR
CUKY | TYPE_CHAR
CURR | TYPE_BCD
DATS | TYPE_DATE
DEC | TYPE_BCD
FLTP | TYPE_FLOAT
INT1 | TYPE_INT1
INT2 | TYPE_INT2
INT4 | TYPE_INT
LANG | TYPE_CHAR
NUMC | TYPE_NUM
PREC | TYPE_NUM
QUAN | TYPE_BCD
RAW | TYPE_BYTE
RAWSTRING | TYPE_XSTRING
STRING | TYPE_STRING
TIMS | TYPE_TIME
UNIT | TYPE_CHAR

Further information can be found in the SAP Online Help


ERRORGROUP

Description

This enumeration contains a list of possible RFC errors:

RFCERROR_NO_ERROR | 0 | No error
RFCERROR_PROGRAM | 101 | error in RFC program
RFCERROR_COMMUNICATION | 102 | Error on network level
RFCERROR_LOGON_FAILURE | 103 | Could not log on to system (e.g. wrong credentials or locked user)
RFCERROR_SYSTEM_FAILURE | 104 | System error (e.g. SAP system exception raised)
RFCERROR_APPLICATION_EXCEPTION | 105 | The called function module raised an exception
RFCERROR_RESOURCE | 106 | Resource not available
RFCERROR_PROTOCOL | 107 | RFC protocol error
RFCERROR_INTERNAL | 108 | RFC internal error
RFCERROR_CANCELLED | 109 | The operation was cancelled
RFCERROR_BUSY | 110 | System is busy, try later


RFCTYPEKIND

Description

This enumeration contains a list of possible parameter types:

RFCTYPEKIND_UNDEFINED | 0 | type not defined
RFCTYPEKIND_SCALAR | 1 | scalar type (a single value)
RFCTYPEKIND_STRUCT | 2 | scalar type (a single value)
RFCTYPEKIND_TABLE | 3 | scalar type (a single value)


BSPApplication

Description

This object allows you to host a BSP Application.

See Using BSP Applications for details.

Properties

Name | Type | Description | Read-only
HttpSystemData | HttpSystemData | HTTP data of the SAP system which hosts the BSP |
LogonData | LogonData | Logon data for the SAP system |
Window | WindowProperties | Defines the window parameters (title and position) |
Parameters | BSPParameter [] | HTTP GET Parameters which are forwarded to the BSP application/page |
Option | string [] | Allows you to set and retrieve additional options, such as trace file location |
LicenseData | LicenseData | Allows you to set the license data programmatically (instead of using Registry keys) |

Method Summary

Method | Description
About | Show information about RFC Connector
ShowApplication | Show the BSP application

Method Details

About

Show information about RFC Connector

Parameters

none

Return Value

none

ShowApplication

Show the BSP application

Parameters

Parameter | Type | Description
application | string | application to call
exitPage | string | Optional: allows you to define an exit page)

Return Value

none


BSPParameter

Description

A single GET parameter for BSP application

Properties

Name | Type | Description | Read-only
Name | string | Name of parameter |
Value | string | Value of parameter |


FunctionCall

Description

This object represents a single function call

Properties

Name | Type | Description | Read-only
Function | string | name of the function module, e.g. RFC_PING |
Importing | RfcParameter [] | importing parameters of function module |
Exporting | RfcParameter [] | exporting parameters |
Changing | RfcParameter [] | changing parameters |
Tables | RfcParameter [] | table parameters |

Method Summary

Method | Description
ToXML | returns a XML representation of the function prototype.
FromXML | loads a function prototype from string
RaiseException | raise an exception (in RfcServer context)

Method Details

ToXML

returns a XML representation of the function prototype.

This can be used to persist function definitions, or for debugging purposes. Note that only the prototype will be persisted, but not the actual parameter values.

This method was introduced with RfcConnector 2.0

Parameters

none

Return Value

Type | Description
string | XML representation of the function prototype

FromXML

loads a function prototype created with FunctionCall.ToXML() from a string.

This can be used to reuse an already persisted function definition without having to re-import it from the SAP backend.
Note that this function must only be called on unused FunctionCall objects, e.g. you may not "reuse" these objects.

This method was introduced with RfcConnector 2.0

Parameters

Parameter | Type | Description
xml | string | XML representation of prototype

Return Value

none

RaiseException

This method can be used to raise an exception. This does only make sense in response to the FunctionCall event of the RfcServer object, and will be ignored in all other cases.

To raise an exception, call this method with the name of the exception and optionally an explanatory message.

For details, please refer to the documentation of the IncomingCall-Event.

Parameters

Parameter | Type | Description
exception | string | exception code
message | string | (optional) message (200 characters max.)

Return Value

none


FunctionCalls

Description

The FunctionCalls object represents a list of FunctionCall objects. Introduced with Rfc Connector 2.0.


HttpSystemData

Description

Connection data for HTTP connection (SOAP, BSP).

Note that some parameters (SoapEndpoint, Stateful) only apply to SoapSession, and are ignored by BSPApplication.

Properties

Name | Type | Description | Read-only
Protocol | string | Protocol to use, either HTTP or HTTPS. Defaults to HTTP |
Host | string | full qualified hostname of the SAP System, e.g. mysaphost.mydomain.com |
Port | integer | port the SOAP/HTTP server listens to (this is typically 8000+SYSNR, but may be changed by SAP admin) |
SoapEndpoint | string | Path to the SOAP service on the SAP server as defined in SICF. Under normal circumstances, there should be no need to change the default value "sap/bc/soap/rfc" |
Timeout | integer | Timeout (in milliseconds) for the HTTP request. Default is 60.000 (1 minute) |
ProxyHost | string | full qualified hostname of the proxy, if necessary |
ProxyPort | integer | port of the proxy |
ProxyUser | string | user for the proxy, if necessary |
ProxyPassword | string | password for the proxy |
Stateful | bool | If set to true, the SAP server is told to keep its state between SOAP requests. Default is false. Note: this property has no effect on BSP applications (in BSP, statefulness is defined by the application, not the client) |


LicenseData

Description

Object which holds license data, consisting of a user and a license key. This can be used instead of storing the license data in the registry.

Properties

Name | Type | Description | Read-only
Owner | string | Owner of the license. Must be entered exactly as in the registration |
Key | string | Licensed key, as received from secept |

Method Summary

Method | Description
IsValidLicense | Check whether the license data is valid

Method Details

IsValidLicense

Check whether the license data is valid

Parameters

none

Return Value

Type | Description
bool | true if the license data is correct


LogonData

Description

This object holds all the data necessary to authenticate the client to the SAP server

Properties

Name | Type | Description | Read-only
Client | string | SAP Client (always a three-letter, numeric string) |
User | string | SAP User |
Password | string | Password |
Language | string | Two-letter SAP language code (EN, DE, ...) |
SSO2Ticket | string | SAPSSO2Ticket as returned by RfcSession.GetSSO2Ticket Note: SAPSSO2Ticket is currently not supported by SOAPSession |
Option | string [] | Additional options for authentication (used for later extensions) |


RfcError

Description

This object contains extended error information

Properties

Name | Type | Description | Read-only
ErrorGroup | ERRORGROUP | The ERRORGROUP of this error |
ErrorGroupText | string | Textual representation of the numeric ERRORGROUP property |
Message | string | Error message |
ModuleName | string | The name of the module in which the error occured |


RfcField

Description

This object represents a field value. Depending on the type of the field, the values can be accessed through the Value, Fields or Rows property

Properties

Name | Type | Description | Read-only
name | string | Name of the field |
Type | RfcType | Type of the field |
Value | variant | Value of the field, if it is of scalar type (plain field, e.g. no struct or table) |
Fields | RfcField [] | Values of the field, if the field type is a struct |
Rows | RfcRows | Contains the table rows, if the field type is table |


RfcParameter

Description

This object represents a function module's parameter.

See Using Parameters for more information.

Properties

Name | Type | Description | Read-only
Name | string | Name of the parameter |
Type | RfcType | Type of the field | yes
Value | variant | Value of the parameter, if it is of scalar type (plain field, e.g. no struct or table) |
Fields | RfcField [] | Values of the field, if the parameter type is a struct |
Rows | RfcRows | Contains the table rows, if the parameter type is table |

Method Summary

Method | Description
DefineScalar | Assign this parameter a scalar type and optionally a value.
Define | Assign this parameter a complex type (struct or table)

Method Details

DefineScalar

Assign this parameter a scalar type and optionally a value.

Parameters

Parameter | Type | Description
name | string | name of the parameter
type | ABABTYPE | type of the parameter
length | integer | lenght of the parameter (only relevant for TYPE_CHAR, TYPE_BYTE, TYPE_NUM and TYPE_BCD. Ignored in all other cases). Default value is 0
decimals | integer | number of decimals (only relevant for TYPE_BCD, ignored in all other cases). Default value is 0
value | variant | value of this parameter (optional, defaults to empty string or 0, depending on the parameter type)

Return Value

none

Define

Assign this parameter a complex type (struct or table)

Parameters

Parameter | Type | Description
name | string | name of the parameter
type | RfcType | type of the parameter, as returned by Session.ImportType

Return Value

none


RfcRows

Description

This object represents the rows of a table.

See Using Tables for more information

Properties

Name | Type | Description | Read-only
Item[index] | RfcField [] | Access an existing row of the table by (numeric) index. Use AddRow or AddRows to append rows |
Type | RfcType | type of the table | yes
FileMode | bool | True if file mode is set | yes
DataCol | integer | If in file mode, contains the index of the data column |
IndexCol | integer | If in file mode, this field contains the index of the index column (if any) |

Method Summary

Method | Description
AddRow | Add a single row to the table
AddRows | Add count rows to the table
SetFileMode | Enable FileMode for this table
RemoveAll | Remove all rows from this table

Method Details

AddRow

Add a single row to the table

Parameters

none

Return Value

Type | Description
RfcField [] | the newly created row

AddRows

Add count rows to the table

Parameters

Parameter | Type | Description
count | integer | number of rows to add

Return Value

none

SetFileMode

Enable FileMode for this table

Parameters

Parameter | Type | Description
dataCol | integer | index of the column where the file data should be stored (mandatory)
indexCol | integer | index of the column where the index (autoincrement) should be stored (optional, default 0=no index)

Return Value

none

RemoveAll

Remove all rows from this table

Parameters

none

Return Value

none


RfcServer

Description

RfcServer allows you to implement RFC Server functionality in your program.

See RFC Servers for a detailed description on how to use this object.

This object was introduced with RfcConnector 2.0

Properties

Name | Type | Description | Read-only
Error | bool | indicates an error (in which case the ErrorInfo property will contain more information) | yes
ErrorInfo | RfcServerErrorInfo | error information | yes
LicenseData | LicenseData | license information |
ProgramID | string | Program ID under which the server registers at the SAP system |
GatewayHost | string | hostname of SAP system (e.g. 'mysaphost.mycompany.com') |
GatewayService | string | service name (this is always "sapgw" + system number, e.g. "sapgw01" for SYSNR=01) |
Option | Option | Allows you to set and retrieve additional options, such as trace file location | yes

Method Summary

Method | Description
Serve | Start the server
Shutdown | Shutdown the server
InstallFunction | Installs a function prototype

Event Summary

Event | Description
Logon | This event is fired to authenticate a caller before the IncomingCall event
IncomingCall | This event is fired when the server receives a function call
ServerError | This event is fired in case of server errors
TransactionCheck | This event is fired after an inbound transactional (tRFC) call is received
TransactionCommit | This event is fired after the inbound tRFC has been processed successfully
TransactionRollback | This event is fired after the inbound tRFC has failed
TransactionConfirm | This event is fired to confirm a transaction after it has been committed.

Method Details

Serve

After calling this method, the server will wait for incoming requests (=function calls). Since the listener is running in another thread, this method will return immediately after the server has been registered at the SAP system, but before any requests are received.

If the server could not be started (for example, if the SAP system is unreachable) the Error property will be set to true and the ErrorInfo property will contain additional information about the error.

The listener thread will be stopped when the server encounters an error (see ServerError event for details), when the Server.Shutdown() method is called or when the server object is disposed.

Parameters

none

Return Value

none

Shutdown

when this method is called, the listener thread will be stopped and the server unregisters itself at the SAP system.

Parameters

none

Return Value

none

InstallFunction

Installs a function prototype, which can be either retrieved by Session.ImportCall(), loaded from XML (with FunctionCall.FromXML()) or constructed manually.

It is necessary for the RfcServer to know the prototype of the served functions before requests are received, because otherwise the parameters could not be decoded properly.

Parameters

Parameter | Type | Description
type | FunctionCall | prototype of the function to install

Return Value

none

Events

Logon

This event is fired to authenticate a caller before the IncomingCall event. Applications can subscribe to this event and use the information in LogonInfo to decide whether the request should be allowed or not. Applications do not need to subscribe to this event. If there are no subscribers to the Logon event, all requests will be allowed. To allow the request, set the RequestAllowed property of the LogonInfo object to true.

Parameters

Parameter | Type | Description
LogonInfo | RfcServerLogonInfo | logon information

IncomingCall

This event is fired when the server receives a function call, and the request is not denied in the event handler for Logon events.

The call parameters can be retrieved through the Importing, Changing and Tables properties of the FunctionCall object. Changes made to the Exporting, Changing and Tables parameters will be transported back to the caller.

To raise an exception, applications can use the RaiseException method of the function call. If an exception is raised, only the Tables parameter, but not the Changing and Exporting parameters are transported back to the caller. If the server receives a call to a function which has not been installed previously through the InstallFunction method, the Importing, Exporting, Changing and Tables parameters of the FunctionCall object are empty, as the server has no means to determine the structure of the data received from the caller.

Parameters

Parameter | Type | Description
call | FunctionCall | function call object

ServerError

This event is fired when the listener thread is running and an error (or RFC_CLOSE from the gateway) is encountered. It is, however, not fired when the server could not be started or registered in the first place (to handle this situation, check the Error property of the RfcServer instance after calling RfcServer.Serve()).

By setting the Restart property of the ErrorInfo object to true, the application can indicate that the listener thread should be restarted, rather than terminated. If the Restart property is set to false, or if there are no subscribers to the ServerError event, the listener thread will terminate.

The recommended implementation is to subscribe to this event and set the Restart property to true, instead of creating new server instances. Creating new server instances in reaction to ServerError events may lead to resource and memory leaks and is generally not recommended.

Parameters

Parameter | Type | Description
ErrorInfo | RfcServerErrorInfo | error info object

TransactionCheck

The TransactionCheck event is fired after an inbound transactional (tRFC) call is received, and before the respective function module is called.

This event MUST be handled by Servers which support tRFC and such servers MUST set the Status field of the TransactionInfo property to one of the following values:

0 | transaction ID stored, transaction can be started
1 | transaction already done, skip the request
-1 | cannot lock transaction, internal error
By definition of tRFC it is allowed for the caller to call a tRFC function multiple times with the same transaction ID, and it is the responsibility of the tRFC server to make sure the function call is executed exactly once regardless of how often it is called (with the same TID). Therefore, consumers of this event are expected to
  • persist the transaction ID they receive and
  • determine whether the respective transaction has already been executed successfully, and, if yes, return 1 to indicate the call should not be repeated
  • return 0 when the transaction has not yet been started, or failed in the past and can be repeated right now
  • return -1 to indicate the transaction cannot be started right now (for example, because the transaction is currently being processed in another thread)

Parameters

Parameter | Type | Description
TransactionInfo | RfcTransactionInfo | transaction information

TransactionCommit

This event is fired after the inbound tRFC has been processed successfully and indicates that the server should persist the received information now (e.g. by calling COMMIT WORK when using a transactional database).

This event CAN be handled by Servers which support tRFC. There is no return value for this event, so Servers do not need to set the Status field.

Parameters

Parameter | Type | Description
TransactionInfo | RfcTransactionInfo | transaction information

TransactionRollback

This event is fired after the inbound tRFC has failed. It can be used to roll back changes to persistant storage, if necessary (e.g. by calling ROLLBACK WORK when using a transactional database).

This event CAN be handled by Servers which support tRFC. There is no return value for this event, so Servers do not need to set the Status field.

Parameters

Parameter | Type | Description
TransactionInfo | RfcTransactionInfo | transaction information

TransactionConfirm

This event is fired to confirm a transaction after it has been committed, and indicates there will be no further calls with the given TID. It can be used to clean up the persistent store of transaction IDs (which is filled in the TransactionCheck event).

This event CAN be handled by Servers which support tRFC. There is no return value for this event, so Servers do not need to set the Status field.

Parameters

Parameter | Type | Description
TransactionInfo | RfcTransactionInfo | transaction information


RfcServerErrorInfo

Description

Error information for RfcServer objects

Properties

Name | Type | Description | Read-only
ErrorGroup | ERRORGROUP | Error Group |
ErrorGroupTxt | string | Error Group (text) | yes
Message | string | Error Message | yes
RfcRc | string | RFC_RC returncode of last operation | yes
Restart | bool | indicates whether the server should be restarted (must be set by event receiver. only valid in event handler) |


RfcServerLogonInfo

Description

logon information for RfcServer objects. Will be transmitted as parameter of the RfcServer.logon event.

Properties

Name | Type | Description | Read-only
Function | string | name of the function which is going to be called | yes
Client | string | SAP client | yes
User | string | name of the user performing the request | yes
Language | string | language | yes
TCode | string | TCODE of transaction which is currently executed | yes
SNCEnabled | string | indicates whether the connection is encrypted | yes
SNCPartnerName | string | SNC partner name (only set when SNCEnabled = true) | yes
RequestAllowed | bool | indicates whether the request should be allowed (must set by event listener) |


RfcServerTransactionInfo

Description

This object keeps state and TID in tRFC (TransactionXXXX events)

Properties

Name | Type | Description | Read-only
TransactionID | string | tRFC transaction id (TID) | yes
Status | long | return value (meaning depends on the actual TransactionXXXX event, see there) |


RfcSession

Description

This object represents a session using the SAP RFC protocol, and implements all methods and properties of Session.

Note: To use RfcSession, you must have the RFC SDK in your path. The necessary DLLs are NOT included with RFC Connector, since they are copyrighted by SAP.

Please refer to Knowledge Base Entry #0009 for information on how to obtain and install this library.

Properties

Name | Type | Description | Read-only
RfcSystemData | RfcSystemData | connection data for this session |

Method Summary

Method | Description
GetSSO2Ticket | Retrieves an SSO2 ticket from the SAP system

Method Details

GetSSO2Ticket

Retrieves an SSO2 ticket from the SAP system

Parameters

none

Return Value

Type | Description
string | the MYSAPSSO2 ticket, which can be used with BSPApplication objects


RfcSystemData

Description

Connection data for RFC connection

Properties

Name | Type | Description | Read-only
ConnectString | string | Connect String (e.g. "ASHOST=host SYSNR=00...") for the system. Refer to documentation for RfcOpenEx() in the RFC SDK for details. |
VisualMode | integer | This value controls whether SAPGUI screens are enabled. Possible values are 0 (no GUI), 1 (GUI always open) and 2 (show GUI only if dialog appears) |
Debug | bool | Enables or disables remote debugging using SAPGUI (just set a breakpoint in SE80 and call the function module) |


RfcType

Description

Definition of RFC type

Properties

Name | Type | Description | Read-only
Name | string | Name of the type (only relevant for tracing etc.) |
Kind | RFCTYPEKIND | Defines which kind the type is (scalar, struct or table) |
ScalarType | ABAPTYPE | The scalar type (if type is scalar, not struct or table) |
ScalarLength | integer | The scalar type length (only relevant if ScalarType is TYPE_CHAR, TYPE_BYTE, TYPE_NUM or TYPE_BCD) |
ScalarDecimals | integer | number of decimals (only relevant if ScalarType is TYPE_BCD) |
StructOffset | integer | If the type is part of a struct, this field contains its offset |
StructLength | integer | If the type is a struct, this field contains the total length in bytes |
StructFields | RfcType [] | If the type is a struct, this collection contains its member fields |
RowType | RfcType | The structure of a table row, if the type is a table |

Method Summary

Method | Description
DefineScalar | Define this type as scalar
DefineStruct | Define this type as a struct (use AddScalarStructField and AddComplexStructField to add members)
DefineTable | Define this type as a table
AddScalarStructField | Append a scalar member to the struct
AddComplexStructField | Append a complex field as member of the struct

Method Details

DefineScalar

Define this type as scalar

Parameters

Parameter | Type | Description
name | string | name of the type (only relevant for logging)
abapType | ABAPTYPE | Type of the scalar
length | integer | length of the scalar field (only for CHAR, BYTE, NUM, BCD; defaults to 0)
decimals | integer | count of decimals (only for BCD)
structOffset | integer | Offset of this field, if the scalar is part of a struct

Return Value

none

DefineStruct

Define this type as a struct (use AddScalarStructField and AddComplexStructField to add members)

Parameters

Parameter | Type | Description
name | string | name of the struct (only relevant for logging)

Return Value

none

DefineTable

Define this type as a table

Parameters

Parameter | Type | Description
name | string | name of the table (only relevant for logging)
rowType | RfcType | Type for the table rows

Return Value

none

AddScalarStructField

Append a scalar member to the struct

Parameters

Parameter | Type | Description
name | string | name of the member
abapType | ABAPTYPE | Type of the member
length | integer | length of the scalar member (only for CHAR, BYTE, NUM, BCD; defaults to 0)
decimals | integer | count of decimals for scalar member (only for BCD)
structOffset | integer | Offset of this field in struct

Return Value

none

AddComplexStructField

Append a complex field as member of the struct

Parameters

Parameter | Type | Description
name | string | name of the member
type | RfcType | type of the field

Return Value

none


Session

Description

Session is an abstract class, which means that you cannot instantiate a Session object directly. To get a Session object, you must create a RfcSession or SoapSession instead (see examples).

Properties

Name | Type | Description | Read-only
CallActive | bool | True if there is an asynchronous call currently running | yes
Error | bool | True if error occured Note: This property is cleared after reading, e.g. the second call always returns False | yes
ErrorInfo | ErrorInfo | This property contains extended error information | yes
IsConnected | bool | True if currently connected to SAP system | yes
LicenseData | LicenseData | Allows you to set the license data programmatically (instead of using Registry keys) |
LogonData | LogonData | Use this property to specify logon data, such as client, user and language |
Option | Option | Allows you to set and retrieve additional options, such as trace file location | yes
SessionType | string | Evaluates to RFC or SOAP, depending on the session type | yes
SystemID | string | ID (e.g. "T01") of the SAP system you are connecting to |
TypeCache | TypeCache | The TypeCache of this session (this property can be used to share type information between two sessions) |

Method Summary

Method | Description
AbortCall | Abort currently running asynchronous call
About | Show information about RFC Connector
CallFunction | Call a function module
ChangePassword | Change the user's password
CheckPasswordExpired | Checks whether the user must change his password
Connect | Connect to SAP system
CreateCall | Create a new FunctionCall
CreateType | Create a new RfcType
Disconnect | Disconnect from System
ImportCall | Import a function definition from the SAP system.
ImportType | Import a struct definition from the SAP system.

Event Summary

Event | Description
CallFinished | This event is fired when an asynchronous call has returned from the system

Method Details

AbortCall

Abort currently running asynchronous call

Parameters

none

Return Value

none

About

Show information about RFC Connector

Parameters

none

Return Value

none

CallFunction

This function allows you to call a function module

Parameters

Parameter | Type | Description
call | FunctionCall | the call to execute
synchronous | bool | Call a function module

Return Value

none

ChangePassword

Change the user's password

Parameters

Parameter | Type | Description
newPass | string | new password for user

Return Value

none

CheckPasswordExpired

Checks whether the user must change his password

Parameters

none

Return Value

Type | Description
bool | True if user must change his password

Connect

Connect to SAP system

Parameters

none

Return Value

none

CreateCall

Create a new FunctionCall

Parameters

none

Return Value

Type | Description
FunctionCall | new FunctionCall object

CreateType

Create a new RfcType

Parameters

none

Return Value

Type | Description
RfcType | new RfcType object

Disconnect

Disconnect from System

Parameters

none

Return Value

none

ImportCall

New with Rfc Connector 2.0. This function will import the whole function module definition from the backend, eliminating the need to specify parameters manually

Parameters

Parameter | Type | Description
moduleName |  |
ignoreUnsupportedParams |  |

Return Value

Type | Description
FunctionCall | Function call definition

ImportType

This function is deprecated in Rfc Connector 2. Please change your code to use ImportCall() instead of defining module definitions manually.

Parameters

Parameter | Type | Description
type | string | name of the type to import

Return Value

Type | Description
RfcType | the imported type

Events

CallFinished

This event is fired when an asynchronous call has returned from the system

Parameters

none


SoapSession

Description

This object represents a session using the SOAP protocol.

This component uses the PocketSOAP library written by Simon Fell, which is licensed under the MPL. See http://pocketsoap.com for details.

Properties

Name | Type | Description | Read-only
HttpSystemData | HttpSystemData | connection data for this session |


TypeCache

Description

The type cache is used to share cached type definitions between sessions.

Under normal circumstances, an application programmer does not use the methods of this class directly, but assigns a cache object to a session instead:

        session2.typeCache = session1.typeCache
Important note: Please use caution when sharing caches between connections to different systems, since RFC Connector does not check if the cached type is the same in the other system, so if the types differ in detail, transmission errors may occur.

Method Summary

Method | Description
GetType | Retrieve a type from the cache
AddType | Retrieve a type from the cache
Clear | Remove all cached types

Method Details

GetType

Retrieve a type from the cache

Parameters

Parameter | Type | Description
name | string | name of the type to retrieve

Return Value

Type | Description
RfcType | cached type

AddType

Retrieve a type from the cache

Parameters

Parameter | Type | Description
name | string | name of the type
type | RfcType | type to add to cache

Return Value

none

Clear

Remove all cached types

Parameters

none

Return Value

none


TableReader

Description

The TableReader class can be used to retrieve the content of SAP tables conveniently. To get a TableReader object, call the GetTableReader method of the Session object.

See Reading database tables for a detailed description on how to use this object. This object was introduced with RfcConnector 2.0

Properties

Name | Type | Description | Read-only
Session | Session | Session which is used to retrieve table contents | yes
Table | string | Name of the table which is being read | yes
Query | StringList | (optional) WHERE clause. This can be used to determine which rows are being read |
Fields | StringList | (optional) This field can be used to determine which columns are being read. If there are no entries in the Fields property, all columns will be read. |
Rows | RfcRows | After a successful call to , this property will contain the database rows | yes
Error | boolean | TRUE if there was an error while executing the last Read() command | yes
ErrorInfo | ErrorInfo | contains additional info about an error (only valid when Error is TRUE) | yes

Method Summary

Method | Description
Read | Reads a number of rows from the server

Method Details

Read

Reads a number of rows from the server.

Parameters

Parameter | Type | Description
count | long | number of rows to read (0=no limit, fetch all rows)
startat | long | number of rows to skip (0 or 1=no skip, start with first line; x = start with line nr. x)

Return Value

none


WindowProperties

Description

Determines position, size, and appearance of a BSPApplication window

Properties

Name | Type | Description | Read-only
Left | integer | Space between the left of the screen and the window (in pixels) |
Top | integer | Space between the top of the screen and the window (in pixels) |
Width | integer | Width of window in pixels |
Height | integer | Height of window in pixels |
IconPath | string | Absolute path to the window's icon (defaults to "" = no icon) |
CloseWarning | string | Text which will be displayed if the user closes the window with the close button. Setting this makes only sense if you use the exitPage feature of BSPApplication |


Examples

Sample projects in many programming languages can be downloaded at http://rfcconnector.com/examples/


Licensing and Support

For support options and licensing options, check out our website at http://rfcconnector.com/