Net Connector
Net Connector
Net Connector
NET Connector
Purpose
The SAP .NET Connector is a development environment that enables communication
between the Microsoft. NET platform and SAP systems. This connector supports RFCs
and Web services, and allows you to write different applications such as Web form,
Windows form, or console applications in the Microsoft Visual Studio.Net. With the SAP
.NET Connector, you can use all common programming languages, such as Visual Basic.
NET, C#, or Managed C++.
Features
Using the SAP .NET Connector and SAP .NET Proxy Wizard, you can:
Write .NET Windows and Web form applications that have access to SAP business objects
(BAPIs).
1. Develop client applications for the SAP Server. Here you can use either RFCs or
HTTP/SOAP/XML (outside-in).
2. Write RFC server applications that run in a .NET environment and can be installed starting
from the SAP system (inside-out).
Further Information
6. SAP.Net Connector: Architecture
7. Creating ASP .Net Applications using the SAP .Net Connector
8. SAP.Net Client
9. SAP.Net Server
10. SAP.Net Connector: Installation
11. SAP .Net Programmer’s Reference
For more information on the SAP .NET Connector, see the SAP Service Marketplace at
the internet address:
service.sap.com
You can use both RFC and SOAP for the connection between the SAP.Net Connector and the
SAP system. The choice of protocol depends on the release status of your SAP system and on its
availability inside or outside of the firewall.
The following example shows how to create a .NET project using Microsoft Visual
Studio .NET. In the example, a client application reads and displays customer data from
an SAP System using a search value and then displays it in a data grid.
The example uses the function module RFC_CUSTOMER_GET, which requires that
customer data exist in the target SAP System, for example, in IDES. Although it is
possible to rename all development objects and generated proxy classes, default names
are used in this example. This example is provided as part of the connector sample code
(DNCWebApp).
Procedure
...
You can also create a project in any other common programming language for .NET,
for example, in Visual Basic .NET. In this case, you must add the SAP .NET proxy
classes as a separate project in the Microsoft Visual Studio .NET solution.
If you select Save this login information will be stored as an encrypted cookie on
your computer and will provide an alternative single sign-on capability the next time
you wish to access the site. If you do not select Save, the login information will still
be saved in the ASP .NET session state but will be lost once the browser is closed.
14. Enter a search argument, for example A* in the TextBox field and choose Search.
Your application connects to the SAP System and displays the requested data in the
DataGrid.
Integration
As of SAP Web AS 6.10, the .NET Connector can communicate with the SAP server
either by RFC or using the SOAP protocol. Up to and including SAP_BASIS release
4.6D, communication is only possible using RFC.
As long as the .NET Connector client and the SAP server are both within a firewall,
communication can occur using both RFC and SOAP, although in this situation using an
RFC connection achieves considerably better performance. For communication outside
the firewall, SOAP must be used.
Configuration of the protocol call within the .NET client can be controlled using a
separate program.
Further Information
• Project Types
• RFC or SOAP
• Connecting to the SAP System
• Authentication
• Asynchronous Methods
• TRFC and QRFC Support
• Monitoring and Debugging
• IDoc
Project Types
We recommend using the SAP Connector Class project template for creating SAP .NET
Connector projects as you can reuse the proxy code. It is also worth considering placing
the SAP proxies in the global assembly cache if several applications are making use of
them.
Alternatively you can add the SAP connector class directly to another type of project
such as a Windows Form, ASP .NET web application or ASP.NET web service. With
other project types you can generate the SAP proxy directly in the project or reference an
existing SAP Connector Library. When you select an existing SAP connector library you
have to verify that your project has a reference to the SAP .Connector library
(sap.connector.dll).
RFC or SOAP
The choice of whether to use RFC or SOAP depends on which release of the SAP system
is available (for example, releases before 6.20) and other issues such as whether the
system is available on your intranet or outside the firewall. Depending on the connection
string used to create the proxy (for example, if it begins with http://), SOAP will be used
to connect to the SAP system otherwise RFC will be used to connect to the SAP system.
For applications that have many concurrent users, the connector provides a connection
pool object. It is possible to get the connection from the pool instead of creating one for
each client. In this way connections are reused and performance is improved.
Authentication
The SAP .NET Connector supports all SAP authentication options including user name,
password and various single sign-on options such as Kerberos, NTLM, X.509 certificates
and SAP Logon tickets. In addition, the connector makes it easy to perform SAP
authentication in your application with the SAPDestination and SAPLogonDestination
classes and in ASP .NET applications with the SAPLogin Form.
We recommend you use the SAP logon classes rather than manually creating a
connection string with the logon information. The SAP logon classes support getting
logon information at runtime from a configuration file, SAPGUI or as another alternative,
programmatically, for example from Microsoft Active Directory.
Asynchronous Methods
Client applications support asynchronous method invocations. The main benefit of this is
that your SAP client application remains responsive even when the RFC call is taking
some time.
Many areas of the .NET framework support asynchronous programming. SAP .NET
Connector classes are built in C# and take advantage of many .NET features including
asynchronous method invocations. Asynchronous programming techniques are important
with SAP RFC calls as some calls can take a long time to complete. During this time, a
single threaded client application seems to be unresponsive as the main thread of
execution is waiting for the SAP method call to complete. Many RFC calls happen very
quickly and the user may not notice, others may take some time and the application
appears to be unresponsive.
With .NET Connector, we can take advantage of many features of the Microsoft Common
Language Runtime (CLR) including support for easy asynchronous programming. This
powerful feature is not available on any other SAP connector at this time. In all other
connectors, BAPI and RFC calls are synchronous calls.
The Asynchronous method calls use the standard .NET delegate callback mechanism. It
provides the programmer with a familiar and powerful way of performing asynchronous
calls in the SAP Client application.
When we use asynchronous methods from the .NET Connector wizard, the proxy
contains two additional methods for each RFC: Begin<RFC Name> and End<RFC
Name> and three additional variables to manage the asynchronous result.
When Begin<RFC Name> is called, CLR queues the request and returns immediately
to the caller. The target method will be on thread from the thread pool. The original
thread is free to continue executing in parallel to the target method. If a callback has been
specified on Begin<RFC Name>, it will be called when the target method returns. In
the callback, the End<RFC Name> method is used to obtain the return value and the
in/out parameters. If the callback was not specified on Begin<RFC Name>, then
End<RFC Name> can be used on the original thread that submitted a request.
TRFC and QRFC Support
Transactional RFC (TRFC) guarantees that a function module is executed in the target
system exactly once. Queued Transactional RFC (QRFC) is a type of TRFC that is
executed only once and in a particular order.
Client applications can be used with normal synchronous RFC, TRFC and QRFC.
Normal Remote Function Calls (RFCs) are synchronous and are not guaranteed to
execute only once or to execute in any particular order. Normal RFC calls return some
value to the calling application, for example a list of customers. Transactional Remote
Function Calls (TRFCs) and Queued Remote Function Calls (QRFCs) do not return
anything if the function was successfully added to the SAP system. If the function was
not added correctly, they throw an exception.
In the connector there are separate method signatures generated for TRFC and QRFC
versus the normal synchronous RFC method. In the case of TRFC and QRFC, an
additional parameter called a transaction ID (TID) is used as a unique identifier within
the SAP system and when adding the function module execution request to the SAP
system. A TID is similar to a GUID. In fact, GUIDs can be mapped back and forth to
SAP TID using helper functions in the RFC library.
TRFC or QRFC should be used when information is added only once to the SAP system
(for example, when adding a sales order or submitting an IDOC). In the case where a
client application needs information from the SAP system, for example a list of
customers, it makes no sense to use TRFC as the SAP system will return nothing back to
the application other than an exception should something go wrong.
Queued RFC enforces the order of execution of the functions in the SAP system. To use
QRFC you must have the following:
1. • A name for the RFC queue to use on the SAP system. If the queue does not
already exist it will be automatically created.
1. • A TID
2. • A queue index to determine the sequence. The queue index begins with zero.
You can debug from your C# proxy directly into the SAP function module by setting the
ABAP_DEBUGflag. Debugging through to the SAP system is useful when you are
getting unexpected results back from the SAP system. To use the ABAP_DEBUGoption
you must have installed SAPGUI on your developer workstation. You cannot use the
integrated ABAP debug option with web applications because they run under another
Windows context that is invisible to the interactive user.
Detailed traces can be written using the tracing flag. Alternatively you can set the
environment variables RFC_TRACE and CPIC_TRACE to have trace files written to
your application directory.
During initial design and debugging it is often useful to run the SAP RFCfunction
directly in the SAP system using transaction SE37. It is easier to isolate the problem once
you are sure that input values are valid. In addition, you should reference the SAP
function module documentation. The SAP data dictionary, which is integrated in the
function editor, also gives you information on valid input values.
In the SAP system, there are automatic formatting functions that are not available in the
connector, for example to add leading zeroes to a customer or invoice number. If the
function is working in the SAP system but not in your proxy, it could be that the SAP
system has applied one of these automatic-formatting routines but you did not.
The SAP system provides extensive tracing and monitoring capabilities inside of the
system as well, for example within the area Tools → Administration → Monitoring.
IDOC
SAP Intermediate Documents (IDOCS) are EDI like documents that are asynchronous in
nature. IDOCS are often used in sending business documents (for example sales orders)
from your SAP system to a trading partner or other system. The actual TRFC call to
submit the IDOC to SAP is performed synchronously and very quickly, but the actual
business processing can happen at some later time defined in the SAP system. The
outbound result (for example, sales order confirmation) can also happen at some later
time. With RFC calls, the business processing is done immediately albeit on a different
thread if we make use of the asynchronous methods described above. IDOCS offer
additional queuing and retry capabilities.
SAP .NET Connector supports both submitting and receiving SAP IDOCs. The
SAPIDOCSender class submits IDOCs and the SAPIDOCReceiver class can be used
with a TRFC server to receive IDOCS.
To work with IDOCS you must use transactional RFC. In the SAPIDOCSender and
SAPIDOCReceiver classes, SAP provides for you a TRFC client implementation that
works with the appropriate function modules in SAP.
SAP .NET Server
Use
If you use a .NET program as an RFC server, your SAP system can handle .NET code
exactly as it would handle another SAP system. It can send a function call to the .Net
Server and receive the result.
Prerequisite
The .NET Server is defined as an RFC destination in the SAP system.
Integration
As of SAP Web AS 6.10, the SAP .NET Connector can communicate with the SAP
system either by RFC or using the SOAP protocol. Up to and including SAP_BASIS
release 4.6D, communication is only possible using RFC.
As long as the SAP .NET Connector server and the SAP system are both within a
firewall, communication can occur using both RFC and SOAP, although in this situation
using an RFC connection achieves considerably better performance. For communication
outside the firewall, SOAP must be used.
The .NET Server is configured as an RFC destination in the SAP system in exactly the
same way as any other (external) RFC server, using transaction SM59.
Further Information
• Key Steps
• Authentication
• Monitoring and Debugging
• TRFC and QRFC
Key Steps
When calling a .NET program from an SAP system, we distinguish the following key
steps, as shown above:
1. • The .NET program must register itself on the SAP gateway host
2. • The SAP system and the .NET program must implement the same method
interface, for example, the function module name and parameters from the SAP
system.
3. • The SAP system initiates the call to the .NET program using the CALL
FUNCTION DESTINATIONkeyword
4. • The .NET program must return the appropriate parameters to the SAP system
The SAP server code that is generated by the connector and provides the functionality
described above as well as a default implementation. This allows the Visual Studio
developer to focus on the implementation and not have to understand how RFC servers
work in detail.
Authentication
Unlike client applications, no user name and password is required to register a server on
the SAP gateway. Instead, the program ID, gateway host, gateway service and code page
must be provided. Once the server is registered on the gateway inside the SAP system, it
can be accessed from SAP programs. The computer where the RFC server is running
must grant permissions to the SAP service user to use the necessary resources on that
machine.
The SAP Gateway offers detailed tracing capabilities from within the SAP system. On
your RFC server you can also enable tracing by setting the environment variable
RFC_TRACE and CPIC_TRACE. The traces can be quite large so should only be used
when there is a problem.
For TRFC servers you also have the TRFC monitor (SM58). For QRFC you have the
SAP Queue monitor (transaction SMQ2) to monitor QRFC calls.
Just as the SAP client solution offers integrated Abap/4 debugging for .NET clients, you
can set a breakpoint in your RFC server code, call the function from the SAP system and
examine the values sent to you from the SAP system in debugging mode within Visual
Studio .NET.
To call our TRFC server, the SAP system uses the syntax: CALL FUNCTION xyz IN
BACKGROUND TASK DESTINATION dest and then issues a COMMIT WORK.
After the COMMIT WORK, the SAP system makes several additional calls related to
TRFC against our .NET component. The first call is CheckTID. This method is
responsible for checking whether we have already processed the TID. If we have
processed the function, nothing further is done. If not, the next step is to execute the
function itself (for example, function xyz) or queue the function for later execution. After
successful completion of this function, we let the SAP system know that the transaction
worked by calling OnCommit. Once the SAP system receives the commit from us it
knows that everything worked properly and lets us know that we can clear the TID record
from our database.
Although it is possible, we do not recommend writing a QRFC server with the connector.
To write a QRFC server, you have to implement the SAP queuing mechanism. For
purposes where you want queuing, we recommend to simply use Microsoft Message
Queue in a TRFC server.
SAP .NET Connector Installation
Implementation Considerations
The SAP .Net Connector is a standalone component that is installed in addition to the
SAP system. To access the installation files, see the SAP Service Marketplace at:
http://service.sap.com/connectors.
For the SAP .Net Connector, the following prerequisites apply:
Development system (System that is in use at the time of development):
Windows 2000 or Windows XP
Microsoft Visual Studio .Net
Java Runtime Environment (JRE). Download from http://java.sun.com
SAP.Net:Setup.msi
Application system (productive system that is in use at runtime):
1. Windows 2000 or Windows XP
2. Microsoft. Net Framework. Download from msdn.microsoft.com/netframework
3. LIBRFC32.dll, release 6.20 or higher
4. SAP.Net.Connector.dll
• Overview of Classes
• SAP Client Programming
• SAP RFC Server Programming
• Data Type Reference
• Samples
Overview of Classes
Class Explanation
SAPClient Base class for all SAP client projects
SAPServer RFC server class that allows you to make use
of .NET functionality inside of your SAP Abap/4
programs
SAPConnection Manages a connection to the SAP system. It is
used by the SAPClient classes
SAPConnectionPool Allows you to manage a pool of connection
objects. This is important for applications where
multiple users access your proxy
Destination Base class for Destination objects. Holds
login attributes as properties but does not
contain logic to retrieve these properties as
does SAPLogonDestination for example
SAPLogonDestination Derived from Destination. In addition to holding
login attributes this class can retrieve login
information from the SAPGUI
SAPLoginProvider User name/password login support via ASP
.NET forms authentication. Also provides an
alternative single sign-on capability
RfcException Base exception class for SAP .NET Connector
exceptions. Not raised by itself
RfcAbapException Exception representing an Abap/4 exception
raised by the SAP RFC Abap/4 code
RfcCommunicationException Exception representing a communication failure
of some type (for example, the SAP system is
unreachable)
RfcLogonException Exception representing a logon failure (for
example, incorrect user name or password)
RfcSystemException Exception representing a system error (for
example, an SAP short dump has occurred)
RfcQueueItem Used for QRFC calls to contain the SAP Queue
information
RfcTID Used for TRFC and QRFC calls. A TID is
similar to a system guid
SAPTable Very common data type used in RFC
programming. This class can be data bound to
most .NET data aware controls such as
datagrids and listboxes. A example of an
SAPTable might be a list of customers with
name and address data for each row.
SAPTable is a collection of SAPStructure
SAPStructure Very common data type used in RFC
programming. For example, a BAPI return code
is an SAPStructure. An individual row in a
table is a structure
SAPIDocSender A class for submitting SAP intermediate
documents (IDOCS) from text files
SAPIDocReceiver A class for receiving SAP IDOCS from SAP.
• SAPClient Class
1. • SAPClient Proxy Generation
2. • Customizing SAP Proxies
3. • SAPClient Methods
4. • SAPClient Exceptions
5. • Debugging of SAPClient Proxies
6. • Authentication
7. • SAPIDocSender Class
8. • Asynchronous Methods
9. • TRFC Client Programming
10. • QRFC Client Programming
11. • Connection Classes
12. • Data Binding with SAPClient
SAPClient Class
SAPClient is the base class for .NET applications wishing to use SAP functionality.
This class is maintained by the SAPConnectorGenerator custom tool and the
SAPProxy wsdl metadata file. It should not be necessary to manually update it. SAP
client proxies are instances of this class.
[C#]
Public class SAPClient:
System.Web.Services.Protocols.SoapHttpClientProtocol
Remarks
In the SAP client solution, SAP is the server and the .NET application is the client that
interacts with the RFC. When you generate an SAP client application, a WSDL file is
added to your Visual Studio .NET project. This SAPWSDL file in coordination with a
custom tool in Visual Studio creates several C# classes needed to communicate with the
SAP system via either RFC or SOAP. There is one class for the proxy itself, one for each
export parameter and two for each Table parameter in your RFC.
The SAP RFC is called as a method of the proxy object. There can be one or more RFC
per proxy. For example you could have a proxy with all customer related RFCs in one
library. The parameters for each RFC can be customized within the Visual Studio
designer so that optional parameters can be removed, parameters can be renamed and
default values provided. You can also customize SAP structures by renaming or removing
fields.
Visual Studio developers can work with the SAP proxies in their choice of programming
language. The proxies themselves are generated in C# so for projects written in other than
C# you have to add a new project of type SAP Connector class to the Visual
Studio solution.
To add the SAP Proxy to your Visual Studio project you have the following options:
Procedure
...
3. If you generate proxies from an SAP server, enter the following information in the
Enter Logon information screen:
Input Explanation
System SAP system name. If you have SAPGUI for
Windows installed, you can select an entry
from the drop down box
Host Application server host name
ID System ID (for example 0)
Client SAP client number (for example, 000 or 800)
User SAP user name
Password Password for that user
Object type (client proxy) The wizard creates all necessary code for a
SAPClient project. The .NET application
which uses SAP system functions is called a
client proxy
Object type (server stub) The wizard creates all necessary code for a
SAPServer project. The SAP system which
uses .NET functions is a server stub
Beautify name SAP function names are by default upper case.
This option makes the names more readable
Create asynchronous methods This option is only for client applications. It
allows you to make your SAP function call on a
dedicated thread so that your application
remains responsive should the call take some
time
4. Select the Remote Function Modules (RFM) you want to use in your proxy object.
You can use the following search filters to look for the function modules:
Option Explanation
Name-Filter A search string for finding the proper SAP
function(s) by name
Group-Filter SAP functions are organized by groups. If you
know the group name you may use it here
After the code has been generated, you can see an SAP proxy WSDL file added to your
project. This WSDL file in coordination with Visual Studio and the
SAPConnectorGenerator custom tool allows you to manage the SAP proxies
automatically.
If you choose to generate the proxy from the SAP IFR you will be asked for the URL of
the IFR Server.
If you choose to generate a proxy from a Standard WSDL file you will be asked for the
path or URL to that WSDL file.
The proxies should be customized from within Visual Studio designer. There is no need
to rerun the proxy generation wizard unless the RFC signature has changed.
These options may be set on the SAPProxy sapwsdl file in the designer. Based on
this input the SAP proxy C# classes will be updated automatically.
Method Customizing
SAPStructure Customizing
SAPTable Customizing
SAPClient Methods
Public Constructors
public SAPClient Initializes a new instance of the
(SAP.Connector.Destination SAPClient class with the connection
destination) information from a SAP Destination object
public SAPClient Initializes a new instance of the
(System.String SAPClient class with the connection
ConnectionString) information from a connection string. The
connection string can be created manually
or from one of the SAP logon controls. If
you want to create a connection string
manually, see the SAP Remote Function
Call API documentation (RFCOpenEX).
public SAPClient ( ) Initializes a new instance of the
SAPClient class without connection
information. The connection information
has to be set in a separate step before you
can use the proxy
Public Methods
Public void <RFC Name> (RFC Executes a normal RFC call for the
parameters) function specified in the SAP system.
Typically out parameters are passed by
reference
Public void TRFC<RFC Name> Executes the RFC specified as TRFC and
(RFC parameters, RFCTID) therefore requires an RFCTID parameter.
You must have selected Create TRFC for
this method to be available
Public void QRFC<RFC Name> Executes the RFC specified as QRFC and
(RFC parameters, therefore requires a RFCQueueItem
RFCQueueItem) parameter. You must have selected Create
QRFC for this method to be available
Public System.IAsynchResult Executes the RFC specified using a
Begin<RFC Name> (RFC Microsoft style asynchronous method
parameters, invocation
System.AsynchCallback, object
asynchState)
Public void End<RFC Used to reattach to the result from the
Name>(system.iasycresult Asynchronous method invocation
asyncresult, ref parameters)
public System.Boolean Used for stateful BAPI calls to commit the
CommitWork ( ) logical unit of work to the system
public void ConfirmTID When using TRFC or QRFC programming
(SAP.Connector.RfcTID tid) you can use this method to confirm the TID
after successfully passing the TRFC call to
the SAP system
public System.Boolean Used for stateful BAPI calls to commit the
RollbackWork ( ) logical unit of work to the system
Public Properties
public The connection object for connecting to the
SAP.Connector.SAPConnection SAP system. Can be either SOAP or RFC
Connection [ get, set ] connection. Should be created from one of
the SAP logon controls
public System.Int32 The execution time in milliseconds
RfcTotalMiliSeconds
Private Methods
protected System.IAsyncResult Used internally to start the asynchronous
BeginSAPInvoke (System.String method invocation
method , object[ ]
methodParamsIn ,
System.AsyncCallback callback
, System.Object asyncState)
protected object[ ] Used internally to receive the results of the
EndSAPInvoke asynchronous method invocation
(System.IAsyncResult ar)
protected object[ ] SAPInvoke Used to submit a normal RFC for execution
(System.String method ,
object[ ] methodParamsIn)
public void tRfcInvoke Used to submit a TRFC for execution
(System.String method ,
object[ ] methodParamsIn ,
SAP.Connector.RfcTID tid)
public void qRfcInvoke Used to submit a QRFC for execution
(System.String method ,
object[ ] methodParamsIn ,
SAP.Connector.RfcQueueItem
qItem)
public void ActivateQueue Used with QRFC processing
(System.String QueueName)
public void DeativateQueue Used with QRFC processing
(System.String QueueName)
SAPClient Exceptions
Errors in the .NET Connector are thrown as .NET exceptions. An exception is the
preferred method to handle errors because exceptions are harder to ignore than are return
codes. They also provide you detailed information to create more robust applications.
• RfcCommunicationException
• RfcLogonException
• RfcSystemException
• RfcAbapException
• RfcException
1. • RfcMarshalException
Coding Recommendations for RFC Exceptions
We recommend you to have at least two catch blocks. The first catch statement is for
SAP exceptions (specific) and the second for others (generic), for example errors from
the runtime or other resources.
We recommend you to close the proxy connection in the finally programming block.
Instead of providing a status of the SAP RFC connection, we recommend that you simply
invoke the method and deal with the exception. The SAP .NET Connector will maintain
the status of the connection internally.
The Proxy.Connection.Open() method causes an RFC ping. This allows you to
see if the system is up. Subsequent Proxy.Connection.open() methods will be
ignored until there is a Connection.Close().
Example
try
{
// Call methods here
proxy.Connection.Open();
proxy.Rfc_Function_Search(txtRFC.Text,"EN", ref tblRFC);
}
catch (RfcCommunicationException ex)
{
MessageBox.Show(ex.ToString());
return;
}
catch (RfcLogonException ex)
{
MessageBox.Show(ex.ToString());
return;
}
catch (RfcAbapException ex)
{
switch (ex.AbapException)
{
case (SAPProxy1.No_Function_Found):
MessageBox.Show("no function found");
break;
case(SAPProxy1.Nothing_Specified):
MessageBox.Show("Nothing specified");
break;
default:
MessageBox.Show("Some unknown abap error occurred");
break;
} //switch
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
finally {proxy.Connection.Close();}
Further Information
2. • RfcException
3. • RfcCommunicationException
4. • RfcLogonException
5. • RfcSystemException
6. • RfcAbapException
Debugging of SAPClient Proxies
With the SAP .NET Connector you can debug from your C# proxy directly into the SAP
function module by setting the ABAP_DEBUG flag in the connection string. The best way
to do this is to set the AbapDebug and Trace flags on the
SAPLogonDestination object. Debugging through to the SAP system is useful
when you are getting unexpected results back from the SAP system. To use the
ABAP_DEBUGoption you must have installed SAPGUI on your developer workstation.
You cannot use the integrated ABAP debug option with web applications because they
run under another Windows context that is invisible to the interactive user. For that
reason it is often useful to test your proxy first against a Windows form or Console
application in case integrated debugging is required.
It is often useful to run the SAP RFC function directly in the SAP system using
transaction SE37. It is easier to isolate the problem once you are sure that input values
are valid. In addition, you can use the SAP function module documentation. The SAP
data dictionary, which is integrated in the function editor, also gives you information on
valid input values.
In the SAP system, there are automatic formatting functions that are not available in the
connector, for example to add leading zeroes to a customer or invoice number. If the
function is working in the SAP system but not in your proxy, it could be that the SAP
system has applied one of these automatic formatting routines but you did not.
To see what values the SAP function module is using, proceed as follows:
...
You can turn on tracing in the SAP system by setting the environment variable
CPIC_TRACE and RFC_TRACE. For more information on RFC tracing, refer to SAP
Note 65325.
Authentication
The SAP Connector can support all SAP authentication mechanisms including:
And in addition the SAP login form uses standard ASP .NET forms authentication to
provide an alternative single sign-on capability.
The following logon controls are available to manage the SAP authentication in your
project.
A very good option for user name and password authentication is the SAP Login form. If
you are writing an ASP .NET application this provides you with a forms-based
authentication and the necessary plumbing for both session and cookie based single sign-
on after the first time visiting the form.
Single Sign-On
Single Sign-On (SSO) is a simplified method of logging on to the SAP system without
reducing security. When a system has been configured for Single Sign-On, an authorized
user who has logged on to the operating system can access the SAP system simply by
selecting it in the SAP logon window or clicking on the shortcut. The user is
authenticated by Windows or some other trusted authority so no SAP password is
required. All SAP supported single sign-on options are also supported by the connector.
Further Information
• X.509 Certificates
• Microsoft .Net Passport
• Kerberos and NTLM
• Destination Class
• SAPLogonDestination Class
• SAPLoginProvider Class
• SAP Login Form
SAPIDocSender Class
The SAPIDocSender class is a TRFC client used to submit SAP intermediate
documents to an SAP system for later processing. An example of an IDOC might be a
customer sales order or a material master record. IDOC records are typically used in EDI
scenarios. See the IdocSubmit sample for example code.
[C#]
public class SAPIDocSender : SAP.Connector.SAPClient
Public Constructors
public SAPIDocSender Creates a new instance of
(System.String SAPIDocSender with a connection
ConnectionString) string
public SAPIDocSender ( ) Creates a new instance of
SAPIDocSender and set the connection
in a later step
Public Methods
public void SubmitIDoc Submits an IDOC from an IDOC
(System.String iDocPath , stored as a file on the operating
SAP.Connector.RfcTID tid) system
public void SubmitIDoc Submits an IDOC from an IDOC as a
(System.IO.TextReader iDoc , textreader object. Perhaps from
SAP.Connector.RfcTID tid) another application or built
dynamically
public void Offers more granular control over the
TRfcIDocInBoundAsynchronous different pieces of the IDOC (EDIDC
(SAP.Connector.EDI_DC40_BLOCKList and EDIDD) for example when you
iDocControlRec40 , are creating an IDOC manually or
SAP.Connector.EDI_DD40_BLOCKList changing something in the header but
iDocDataRec40 , otherwise want to keep the body of
SAP.Connector.RfcTID tid) the IDOC
Remarks
An IDOC will consist of three segments, the header (EDIDC), the body (EDIDD) and the
status (EDIDS). The EDIDC record can contain two formats (EDIDC or EDIDC40)
depending on the version of the IDOC. The body of the IDOC will differ depending on
what IDOC type and release it is. The status record is only maintained inside of the SAP
system and is not relevant to submit an IDOC.
Example
When we use asynchronous methods from the SAP .NET Connector wizard, the proxy
contains two additional methods Begin<RFC name> and End<RFC Name>.
When Begin<RFC name> is called, CLR queues the request and returns immediately
to the caller. The target method will be on thread from the thread pool. The original
thread is free to continue executing in parallel to the target method. If a callback has been
specified on the Begin<RFC name>, it will be called when the target method returns.
In the callback, the End<RFC name> method is used to obtain the return value and the
in/outparameters. If the callback was not specified on the Begin<RFC name>, then
End<RFC name> can be used on the original thread that submitted a request.
When working with asynchronous calls, we need three additional variables compared to a
synchronous RFC call
When working with asynchronous calls, we need three additional variables compared to a
synchronous RFC call.
Example
The following Winform sample shows the code for asynchronous method call (SAPAsyncSearch
method).
} //SAPUpdateTRFC
Example
Connection Classes
• SAPConnection Class
• SAPConnectionPool Class
SAPConnection Class
TheSAPConnection class is used to manage the connection to the SAP system. Some
basis information about the system you are connected to can also be determined from this
class.
[C#]
public class SAPConnection : System.Object
Public Constructors
public SAPConnection Creates an SAP connection from a
(SAP.Connector.Destination destination class
dest)
public SAPConnection Creates an instance of the SAP connection
(System.String connString) from a connection string. For example from
the SAPlogonDestination or a
manually created connection string
Public Methods
Accept
Close The Close method should be called after
the RFC is completed
Dispose
Finalize
Open The Open method must be called before
the RFC can be executed
Public Properties
ApplicationServer Reads only property showing basis
information about the SAP system
CodePageEncoding Reads only property showing basis
information about the SAP system
ConnectionString Reads only property showing basis
information about the SAP system
KernelRelease Reads only property showing basis
information about the SAP system
OwnCodePage Reads only property showing basis
information about the SAP system
PartnerCodePage Reads only property showing basis
information about the SAP system
SystemID Reads only property showing basis
information about the SAP system
SystemNumber Reads only property showing basis
information about the SAP system
SystemRelease Reads only property showing basis
information about the SAP system
SAPConnectionPool Class
Connection pooling is a more sophisticated way of managing SAP Connections. In a two-
tier deployment we do not recommend to use this as each client has its own connection.
In an n-tier deployment where multiple users are using the same connection attributes
(for example a web site that is accessed by many users) it may make sense to use
connection pooling. Alternatively, consider using the SAPLogin Provider and
SAPLogin Form.
[C#]
public class SAPConnectionPool : System.Object
Public Constructor
public SAPConnectionPool ( ) Static object of the SAP .Connector
Public Methods
public static Gets a connection from the connection pool
SAP.Connector.SAPConnection by passing in the connection string
GetConnection (System.String
connectionString)
public static void Returns the connection to the connection
ReturnConnection pool
(SAP.Connector.SAPConnection
connection)
Example
using(proxy.Connection =
SAP.Connector.SAPConnectionPool.GetConnection(this.destination1.Connect
ionString))
dataGrid1.DataSource = BRFCKNA1Table1;
// create an SAP table but as it's an in parameter don't need to instantiate it for the rfc call
BRFCKNA1Table tblCust = new BRFCKNA1Table();
using(proxy.Connection =
SAP.Connector.SAPConnectionPool.GetConnection(this.destination1.ConnectionString))
{
Alternatively you can create an additional constructor with the parameters you want to fill.
For TABLES that are input parameters you have to populate the values yourself before
calling the SAP RFC. For TABLES that are output parameters the SAP marshalling code
populates the values for you automatically.
2. • Clearing Values From the Table
When an exception is returned, the TABLE object is not reinitialized. If you had made a
previously successful method call and the TABLE contains values, these will not be
reinitialized after an exception has occurred. In this case you can keep the last (good)
results. You can use the table’s clear() method to initialize the values yourself.
3. • Getting Runtime Information About the RFC TABLES
SAP Tables are built on the .NET CollectionBase class. Therefore they support
indexers and other array operations to allow for easy management of the members in the
array.
Field metadata information can be determined from the structure using the static method:
GetSAPFieldsSchema(System.Type t).
The type parameter is the data type of SAPStructure (in this case the type of
BAPICUSTOMER_IDRANGE).
SAPField[ ] myFields =
BAPICUSTOMER_IDRANGE.GetFieldsSchema(typeof(BAPICUSTOMER_IDRANGE));
You can get metadata information about each field either with a foreach statement or
using the length property of the SAPField array.
The following data types are mapped directly to .NET base data types in the main C#
proxy class.
• ABAP type N (numeric) data is mapped to a STRING data type in the C# proxy. It contains
numeric data such as invoice numbers. Some type N fields like invoice number or
customer number require you to enter the string with leading zeroes. If in your application
the customer number field is numeric, be sure to convert your entry back to the
appropriately formatted string before using it in the proxy.
• Date / Time fields are mapped to .NET STRING data types in the C# proxy. The format of
the string is the same as the SAP internal storage of the date and time. Specifically for date
this is YYYYMMDD and for time it is HHMMSS. The SAP .NET connector provides functions
specifically to help you convert from SAP Date/Time fields stored as string to a .NET date
or time field.
SAPTable Class
The SAPTable class represents a very common data type in the SAP system and is
frequently used to hold the results of the RFC call. It is occasionally used to pass in
selection variables to the RFC call. A SAPTable is made of SAPStructures of a
single type. For example a SAPTable called RFCFuncTable would be made up of
RFCFunc structures (rows).
[C#]
Public Constructors
protected SAPTable ( ) Creates a new instance of SAP Table. You should
use the SAP table control to reference SAP Tables
in your code. The SAP table will be created
automatically by the connector.
Public Methods
Add (SAPStructure) Adds a new row (SAPStructure) to the table
Contains(SAPStructure) Returns true if the SAPTable contains that row
CopyTo(SAPStructure[ ], Copies into a SAPStructure array up to the given
int) index
CreateNewRow() Creates a new blank row in the SAPTable
GetElementType() Returns the type of the particular
SAPStructure (for example, RFCFunc or
other SAP structure)
IndexOf(SAPStructure) Returns the current index ID
Insert(int, Inserts at the index given a SAP structure
SAPStructure)
Remove(SAPStructure) Removes the SAP structure specified from the
table
SortBy(string fieldname, The SAP table now supports sorting, for example
string direction) in a datagrid.
ToADODataTable Creates a new ADO .NET DataTable from the
SAP Table.
FromADODataTable Creates the SAP Table from an ADO .NET DataTable.
Note that the schemas must be IDENTICAL.
Public Properties
This[int] An indexer to get access to the current SAP
structure
Example
See the Winform sample for examples of using the SAPTable class.
SAPStructure Class
The SAPStructure class represents a very common data type in the SAP system and
is frequently used to hold the results of the RFC call as part of a SAPTableor as a BAPI
error return. A structure is made up of several simple data types and can be thought of as
a row of a table. The SAPStructure is generated for you by the SAP .NET Connector
and should not be modified outside of the SAPConnectorGenerator tool.
[C#]
public class SAPStructure : System.Object
Public Constructors
protected SAPStructure ( ) The SAPstructure is the base class for
a specific type of SAP Structure. For
example a structure containing customer
address data (customer, city, state, phone,
etc.)
Example
See the Winform sample application for example code dealing with SAP Structures.
• IMPORT
Always pass values from the calling program to the function module unless this is marked
as an optional parameter.
• CHANGING
These are passed to the function module from the calling program and are then passed
back to the program.
• EXPORT
These are passed from the function module to the calling program unless marked as an
optional parameter.
• TABLES
These represent an array of SAP structure instances. They can be IN or OUT parameters.
• IMPORT, EXPORT, CHANGING
These parameter types cannot be tables. They can be structures or other simple data
types.
• OPTIONAL
Parameters can also be defined as optional.
Samples
Several samples are provided with the connector to help you understand how the proxies
work and to illustrate the topics discussed in this reference. They are provided without
warranty or support.
The samples are designed to work against the Mini SAP Web Application Server 6.20 or
any system supporting RFC_CUSTOMER_GET and RFC_CUSTOMER_UPDATE. For the
IDOC samples you need a system than can accept IDOCs. An Exchange_rate01
IDOC type is provided as a sample that should work with the mini SAP system. All
samples are written in Microsoft C#, except for the Visual Basic windows form sample.
Before using the samples, be sure to verify the login parameters in the SAP destination
component. The samples are located in the folder Samples. To launch the samples in
Visual Studio .NET double-click on Samples.sln.
Further Information
Further information on the different programming samples you will find here:
• SAPClient programming
• Dealing with exceptions
• Asynchronous method calls
• Debugging and tracing
• Working with SAP Tables (sorting, converting to ADO .NET, data binding)
• Synchronous, transactional and Queued RFC updates
The Windows form sample uses the RFC_CUSTOMER_GET function module. It accepts
as input a customer name string (for example, A*) and returns in a datagrid all customers
that match that selection.
To use the sample, you have to enter an SAP customer search selection criteria. All
functions are available from the sample’s application menu.
To use the option Save Results to SQL Server you must set the SQL logon parameters in
the component SqlConnection1 on form1. To do this, click on the property
ConnectionString and use the drop down box. Let the Wizard construct the
connection string for you. You also need a table named cust in the Northwind database,
and a stored procedure called Insert_cust. The SQL script to create both of these
objects is located in the subfolder SQL.
Webform Samples
The web form sample is the simple ASP .NET web form shown in the guide and
illustrates the following:
• SAPClient programming
• Using ASP .NET with the connector
• Databinding in web form
• Use of the SAPlogin form
Before using this sample, you have to share the folder DNCWebApp.
This sample uses command line arguments to connect to the SAP gateway (for example,
–aMYPROGID –gLOCALHOST –xSAPGW00), where –a is the program ID used in
your TCP/IP destination, -g is the gateway host and –x is the gateway service.
You can set the command line arguments in the Visual Studio .NET debugger by right-
clicking on the project RFCServerConsole and selecting Properties →
Configuration properties → Debugging → Command Line Arguments.
Before calling this RFC server in the SAP system, you must have setup a TCP/IP
destination in your SAP system (type registration). You can call this sample RFC server
by running RFC_CUSTOMER_GET in single test from the RFC function builder
(transaction SE37) inside of the SAP system, with the destination of your TCP/IP
destination. Alternatively, you can write an Abap/4 program as described in Calling RFC
.Net Server from SAP Programs.
To create a TRFC destination for the SAP .NET server stub create a destination of type T
(TRFC) in transaction code SM59. The program ID in your server stub is case sensitive.
Example
*&---------------------------------------------------------------------
*& Report ZRFCSERVERCALL
*&
**&--------------------------------------------------------------------
*& This program can be used with the RFCServerConsole sample
*& Source is available in %\RFCServerConsole\ABAPProgram
*&---------------------------------------------------------------------
REPORT ZRFCSERVERCALL .
DATA: TBLCUST like BRFCKNA1 occurs 0 with header line.
PARAMETERS: P_CUSTNO like KNA1-KUNNR, P_CUSTNA like KNA1-NAME1,
P_DEST(15) TYPE C.
CASE SY-SUBRC.
WHEN 0.
LOOP AT TBLCUST.
WRITE: / SY-TABIX, TBLCUST-KUNNR, TBLCUST-NAME1, TBLCUST-ORT01.
ENDLOOP.
WHEN 1.
WRITE: / 'You need to specify a value ', SY-MSGV1.
WHEN 2.
WRITE: / '.NET component didnt find anything ', SY-MSGV1.
WHEN 3.
WRITE: / 'Some other error occurred ', SY-MSGV1.
WHEN OTHERS.
WRITE: / 'Something is wrong if we get here'.
ENDCASE.
The entry point in the C# method is the method with the function module name
being called from the SAP system (for example, RFC_CUSTOMER_GET). In Microsoft
Visual Studio, you can set a breakpoint here and examine the input values from the
SAP system. This provides a similar idea to the ABAP_DEBUG functionality that is
provided in the client proxy.
Before running this sample, you must install it using the Visual Studio utility
Installutil.exe.
Using the Visual Studio .NET command line, navigate to the folder containing
Installutil IdocReceiverService.exe (for example,
SAP .NET Connector\Samples\IdocReceiverService\bin\Debug).
You set the SAP connection string in this service’s Start parametersproperty. For
example if your TCP/IP destination used the program ID of myProgIDand your SAP
system ran on your local machine, then the start parameters would be:
Messages are logged to the Windows Application Event Viewer. When received, SAP
IDOCs are appended to the following file: C:\temp\idoc.txt.
To enable your system to send IDOCS you must have a TCP/IP destination (type
registration), a configured partner profile (WE20) and a configured TRFC Port (WE21).
The Mini SAP Web Application Server 6.20 supports the IDOC type
EXCHANGE_RATE01. For convenience, you can find a sample IDOC file in the IDOC
submitter sample’s SampleIdoc folder. If you have no IDOCs on your system you can
submit this IDOC using the IdocSubmit sample application. Then use the IDOC test
utility (WE19), change the IDOC header and submit it as an outbound IDOC to the TRFC
Port representing this IdocReceiver sample.
Note that you must run this sample in HTTPS to get the X.509 certificate from IIS.