Condividi tramite


Richiamare tRFCs in SAP usando il modello di servizio WCF

Le chiamate di funzione remota transazionale (tRFCs) garantiscono un'esecuzione one-time di un RFC in un sistema SAP. È possibile richiamare una qualsiasi delle schede di rete di rete distribuite dall'adattatore SAP come tRFC. Richiamare un TRFC nel modello di servizio WCF è simile a quello di richiamare un RFC con le differenze seguenti:

  • L'adattatore SAP superfici tRFCs in un nodo diverso (TRFC) rispetto alle schede RFC (RFC).

  • Le chiamate client tRFC non restituiscono valori per l'esportazione SAP e la modifica dei parametri.

  • Le operazioni tRFC includono un parametro GUID mappato all'ID transazione SAP (TID) per la scheda TRFC.

  • Dopo aver richiamato una tRFC, è necessario richiamare l'operazione RfcConfirmTransID per confermare (commit) il tRFC nel sistema SAP. Questa operazione viene eseguita direttamente sotto il nodo TRFC.

    Per altre informazioni sulle operazioni tRFC e sull'operazione RfcConfirmTransID, vedere Operazioni su tRFCs in SAP.

    Le sezioni seguenti illustrano come richiamare tRFCs nel sistema SAP usando l'adattatore SAP.

Classe client WCF

L'adattatore SAP esegue tutte le operazioni tRFC sotto un singolo contratto di servizio, "Trfc". Ciò significa che viene creata una singola classe client WCF, TrfcClient, per tutte le operazioni tRFC che si desidera richiamare. Ogni tRFC di destinazione è rappresentato come metodo di questa classe. Per ogni metodo:

  • I tipi SAP complessi, ad esempio le strutture, vengono visualizzati come classi .NET con proprietà corrispondenti ai campi del tipo SAP. Queste classi sono definite nello spazio dei nomi seguente: microsoft.lobservices.sap._2007._03.Types.Rfc.

    Il codice seguente mostra parte della classe TrfcClient e il metodo che richiama BAPI_SALESORDER_CREATEFROMDAT2 (come tRFC) nel sistema SAP. Il parametro TransactionalRfcOperationIdentifier contiene il GUID mappato a SAP TID. Non tutti i parametri del metodo vengono visualizzati.

[System.Diagnostics.DebuggerStepThroughAttribute()]  
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]  
public partial class TrfcClient : System.ServiceModel.ClientBase<Trfc>, Trfc {  
  
    ....  
  
    /// <summary>The Metadata for this RFC was generated using the RFC SDK.</summary>  
    public void BAPI_SALESORDER_CREATEFROMDAT2(  
                string BEHAVE_WHEN_ERROR,   
                string BINARY_RELATIONSHIPTYPE,   
                string CONVERT,   
                string INT_NUMBER_ASSIGNMENT,   
                microsoft.lobservices.sap._2007._03.Types.Rfc.BAPISDLS LOGIC_SWITCH,   
                microsoft.lobservices.sap._2007._03.Types.Rfc.BAPISDHD1 ORDER_HEADER_IN,   
  
                …  
  
               microsoft.lobservices.sap._2007._03.Types.Rfc.BAPIADDR1[] PARTNERADDRESSES,   
                microsoft.lobservices.sap._2007._03.Types.Rfc.BAPIRET2[] RETURN,   
                ref System.Guid TransactionalRfcOperationIdentifier) { ...  }  
}  

Il codice seguente mostra il metodo generato per l'operazione RfcConfirmTransID. È necessario assicurarsi che questo metodo venga generato come parte di TrfcClient. L'operazione RfcConfirmTransID viene eseguita direttamente sotto il nodo TRFC.

public void RfcConfirmTransID(System.Guid TransactionalRfcOperationIdentifier) {…}  

Come creare un'applicazione client tRFC

I passaggi per creare un'applicazione che richiama tRFCs sono simili ai passaggi seguiti per richiamare le schede di rete, con le eccezioni seguenti:

  • È necessario recuperare le operazioni di destinazione nel nodo TRFC.

  • È necessario recuperare l'operazione RfcConfirmTransID. Questa operazione viene eseguita direttamente sotto il nodo TRFC.

  • Per confermare (commit) un'operazione tRFC nel sistema SAP, è necessario richiamare l'operazione RfcConfirmTransID con il GUID restituito per tale operazione tRFC.

Per creare un'applicazione client tRFC

  1. Generare una classe TrfcClient . Usare il plug-in Add Adapter Service Reference Visual Studio o serviceModel Metadata Utility Tool (svcutil.exe) per generare una classe TrfcClient destinata alle schede di rete con cui si desidera lavorare. Per altre informazioni su come generare un client WCF, vedere Generare un client WCF o un contratto di servizio WCF per gli artefatti della soluzione SAP. Assicurarsi che l'operazione RfcConfirmTransID sia inclusa nella classe TrfcClient .

  2. Creare un'istanza della classe TrfcClient generata nel passaggio 1 e specificare un'associazione client. Se si specifica un'associazione client, è necessario specificare l'indirizzo dell'associazione e dell'endpoint usato da TrfcClient . È possibile eseguire questa operazione in modo imperativo nel codice o in modo dichiarativo nella configurazione. Per altre informazioni su come specificare un'associazione client, vedere Configurare un'associazione client per il sistema SAP. Il codice seguente inizializza TrfcClient dalla configurazione e imposta le credenziali per il sistema SAP.

    TrfcClient trfcClient = new TrfcClient("SAPBinding_Rfc");  
    
    trfcClient.ClientCredentials.UserName.UserName = "YourUserName";  
    trfcClient.ClientCredentials.UserName.Password = "YourPassword";  
    
  3. Aprire TrfcClient.

    trfcClient.Open();  
    
  4. Richiamare il metodo appropriato nel trfcClient creato nel passaggio 2 per richiamare il tRFC di destinazione nel sistema SAP. È possibile passare una variabile contenente un GUID o che contiene un GUID vuoto per il parametro TransactionalRrcOperationIdentifier . Se si passa un GUID vuoto, l'adapter SAP genera uno per l'utente. Il codice seguente richiama BAPI_SALESORDER_CREATEFROMDAT2 come tRFC nel sistema SAP (non tutti i parametri del metodo sono visualizzati). Viene specificato un GUID.

    transactionalRfcOperationIdentifier = Guid.NewGuid();  
    
    //invoke RFC_CUSTOMER_GET as a tRFC  
    trfcClient.BAPI_SALESORDER_CREATEFROMDAT2(  
                                    request.BEHAVE_WHEN_ERROR,  
                                    request.BINARY_RELATIONSHIPTYPE,  
                                    request.CONVERT,  
    
                                    ...  
    
                                    ref transactionalRfcOperationIdentifier);  
    
  5. Per confermare il TID associato al tRFC nel sistema SAP, richiamare il metodo RfcConfirmTransID nel TrfcClient. Specificare il GUID restituito nel passaggio 4 per il parametro TransactionRfcOperationIdentifier.

    trfcClient.RfcConfirmTransID(transactionalRfcOperationIdentifier);  
    
  6. Chiudere TrfcClient al termine dell'uso (dopo aver richiamato tutti i tRFC).

    trfcClient.Close();   
    

Esempio

Nell'esempio seguente viene illustrato come richiamare BAPI_SALESORDER_CREATE come tRFC.

using System;  
using System.Collections.Generic;  
using System.Text;  
  
// Add WCF, the WCF LOB Adapter SDK, and SAP adapter namepaces  
using System.ServiceModel;  
using Microsoft.Adapters.SAP;  
using Microsoft.ServiceModel.Channels;  
  
// Include this namespace for WCF LOB Adapter SDK and SAP exceptions  
using Microsoft.ServiceModel.Channels.Common;  
  
using microsoft.lobservices.sap._2007._03.Types.Rfc;  
  
// This example demonstrates sending BAPI_SALESORDER_CREATEFROMDAT2 as a tRFC. The client has   
// methods to:  
//      send the BAPI (BAPI_SALESORDER_CREATEFROMDAT2)and to  
//      Confirm the transaction (RfcConfirmTransID)  
// An instance of BAPI_SALESORDER_CREATEFROMDAT2Request (generated)   
// is used to format the BAPI before invoking BAPI_SALESORDER_CREATEFROMDAT2. This   
// is not necessary, but is done to make it easier to read the code.  
// tRFC invocations always includes a ref parameter that contains a GUID. You can optionally   
// set this parameter when you invoke the method; however, you must use the value returned by  
// the adapter when you call RfcConfirmTransID to confirm the transaction on the SAP system.   
// You can call the utility method, SAPAdapterUtilities.ConvertGuidToTid, to get the value  
// of the SAP transaction Id from the GUID that the adapter returns.  
namespace SapTrfcClientSM  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            TrfcClient sapTrfcClient = null;  
  
            try  
            {  
                Console.WriteLine("SAP TRFC client sample started");  
                Console.WriteLine("Creating the TRFC client");  
                // Create the SAP Trfc Client from configuration  
                sapTrfcClient = new TrfcClient("SAPBinding_Trfc");  
                sapTrfcClient.ClientCredentials.UserName.UserName = "YourUserName";  
                sapTrfcClient.ClientCredentials.UserName.Password = "YourPassword";  
  
                Console.WriteLine("Opening the TRFC client");  
                // Open the Trfc Client  
                sapTrfcClient.Open();  
  
                // Create a GUID -- note: this is optional. If you do not pass a GUID,  
                // for the TransactionalRfcOperationIdentifier parameter, the SAP adapter will   
                // generate one, associate it with the SAP TID, and set the   
                // TransactionalRfcOperationIdentifier parameter.  
                Guid tidGuid = Guid.NewGuid();  
  
                BAPI_SALESORDER_CREATEFROMDAT2Request request = new BAPI_SALESORDER_CREATEFROMDAT2Request();  
  
                request.ORDER_HEADER_IN = new BAPISDHD1();  
                request.ORDER_HEADER_IN.DOC_TYPE = "TA";  
                request.ORDER_HEADER_IN.SALES_ORG = "1000";  
                request.ORDER_HEADER_IN.DISTR_CHAN = "10";  
                request.ORDER_HEADER_IN.DIVISION = "00";  
                request.ORDER_HEADER_IN.SALES_OFF = "1000";  
                request.ORDER_HEADER_IN.REQ_DATE_H = DateTime.Now;  
                request.ORDER_HEADER_IN.PURCH_DATE = DateTime.Now;  
                request.ORDER_HEADER_IN.PURCH_NO_C = "Cust PO";  
                request.ORDER_HEADER_IN.CURRENCY = "EUR";  
  
                BAPISDITM[] orderItems = new BAPISDITM[1];  
                orderItems[0] = new BAPISDITM();  
                orderItems[0].MATERIAL = "P-109";  
                orderItems[0].PLANT = "1000";  
                orderItems[0].TARGET_QU = "ST";  
                request.ORDER_ITEMS_IN = orderItems;  
  
                BAPIPARNR[] orderPartners = new BAPIPARNR[1];  
                orderPartners[0] = new microsoft.lobservices.sap._2007._03.Types.Rfc.BAPIPARNR();  
                orderPartners[0].PARTN_ROLE = "AG";  
                orderPartners[0].PARTN_NUMB = "0000001390";  
                request.ORDER_PARTNERS = orderPartners;  
  
                // Create a GUID -- note: this is optional. If you do not pass a GUID,  
                // for the TransactionalRfcOperationIdentifier parameter, the SAP adapter will   
                // generate one, associate it with the SAP TID, and set the   
                // TransactionalRfcOperationIdentifier parameter.  
                request.TransactionalRfcOperationIdentifier = Guid.NewGuid();  
  
                Console.WriteLine("Invoking BAPI_SALESORDER_CREATEFROMDAT2 as a tRFC");  
  
                //invoke RFC_CUSTOMER_GET as a tRFC  
                sapTrfcClient.BAPI_SALESORDER_CREATEFROMDAT2(request.BEHAVE_WHEN_ERROR,  
                                                                request.BINARY_RELATIONSHIPTYPE,  
                                                                request.CONVERT,  
                                                                request.INT_NUMBER_ASSIGNMENT,  
                                                                request.LOGIC_SWITCH,  
                                                                request.ORDER_HEADER_IN,  
                                                                request.ORDER_HEADER_INX,  
                                                                request.SALESDOCUMENTIN,  
                                                                request.SENDER,  
                                                                request.TESTRUN,  
                                                                request.EXTENSIONIN,  
                                                                request.ORDER_CCARD,  
                                                                request.ORDER_CFGS_BLOB,  
                                                                request.ORDER_CFGS_INST,  
                                                                request.ORDER_CFGS_PART_OF,  
                                                                request.ORDER_CFGS_REF,  
                                                                request.ORDER_CFGS_REFINST,  
                                                                request.ORDER_CFGS_VALUE,  
                                                                request.ORDER_CFGS_VK,  
                                                                request.ORDER_CONDITIONS_IN,  
                                                                request.ORDER_CONDITIONS_INX,  
                                                                request.ORDER_ITEMS_IN,  
                                                                request.ORDER_ITEMS_INX,  
                                                                request.ORDER_KEYS,  
                                                                request.ORDER_PARTNERS,  
                                                                request.ORDER_SCHEDULES_IN,  
                                                                request.ORDER_SCHEDULES_INX,  
                                                                request.ORDER_TEXT,  
                                                                request.PARTNERADDRESSES,  
                                                                request.RETURN,  
                                                                ref request.TransactionalRfcOperationIdentifier);  
  
                string sapTxId = null;  
                sapTxId = SAPAdapterUtilities.ConvertGuidToTid(request.TransactionalRfcOperationIdentifier);  
  
                Console.WriteLine("BAPI_SALESORDER_CREATEFROMDAT2 Sent");  
                Console.WriteLine("The SAP Transaction Id is " + sapTxId);  
  
                // Invoke the RfcConfirmTransID method to confirm (commit) the transaction on  
                // the SAP system. This step is required to complete the transaction. The SAP  
                // adapter will always return a TranactionalRfcOperationIdentifier, whether   
                // one was supplied in the call or not.  
                sapTrfcClient.RfcConfirmTransID(request.TransactionalRfcOperationIdentifier);  
  
                Console.WriteLine("SAP Transaction {0} has been committed", sapTxId);  
  
                Console.WriteLine("\nHit <RETURN> to end");  
                Console.ReadLine();  
  
            }  
            catch (ConnectionException cex)  
            {  
                Console.WriteLine("Exception occurred connecting to the SAP system");  
                Console.WriteLine(cex.InnerException.Message);  
                throw;  
            }  
            catch (Exception ex)  
            {  
                Console.WriteLine("Exception is: " + ex.Message);  
                if (ex.InnerException != null)  
                {  
                    Console.WriteLine("Inner Exception is: " + ex.InnerException.Message);  
                }  
                throw;  
            }  
            finally  
            {  
                // Close the client  
                if (sapTrfcClient != null)  
                {  
                    if (sapTrfcClient.State == CommunicationState.Opened)  
                        sapTrfcClient.Close();  
                    else  
                        sapTrfcClient.Abort();  
                }  
            }  
  
        }  
    }  
}  

Vedere anche

Sviluppare applicazioni tramite il modello di servizio WCF
Operazioni sui tRFC in SAP