在說怎么用C#調用RFC接口之前,先講講自己對SAP接口的理解。
1,SAP的常用接口
PI接口:即我們常用的webservice
RFC接口:即是這里要講的一種接口方式,至於定義嘛,有請百度百科
2,RFC接口的參數
input類型:即鍵值對,可以理解成webapi的key-value那樣的參數。
table類型:即對象數組,可以理解成List<object>對象,並且可以傳多個這樣的對象。
使用過程中,上面兩種類型可以同時傳,也只用其中一種類型,看接口需求而定。
3,RFC接口的返回值
跟傳參類似,返回值里面可以是key-value類型,也可以是多個List<object>。
4,C#怎么調用RFC函數
很簡單,使用現成的類庫。
網上可以找到很多版本的類庫,每個都有一定的差異,我使用的是nuget上下載的。nuget上搜NSAPConnector_x64就可以了。
(我使用的這個版本有一些小問題,但比起別的版本來說算好的了,當然可能有別的完善版本我沒發現)
下好后,會有下面3個dll引用
因為沒有文檔,建議大家直接用對象瀏覽器,直接看dll暴露出來的接口。根據方法名就可以大概猜出的知道每個方法的用途。
(這里可以用NSAPConnector封裝的方法,如果覺得封裝的方法不好用,也可以直接調用sapnco里面的方法,我是直接使用sapnco的方法的,因為那個好像有BUG)
DLL里面的接口方法就不截圖出來了,有需要的自己去看看,也可以反編譯去看源碼。
說了這么多,粘一點調用的示例出來吧:
1 public DataSet ExecuteDataSet(string cmdText, Dictionary<string, string> dic, Dictionary<string, List<string>> dic2 = null) 2 { 3 DataSet ds = new DataSet();//存放結果 4 RfcDestination des = GetRfcDestination();//創建連接 5 IRfcFunction fun = des.Repository.CreateFunction(cmdText);//傳入調用函數名 6 //input類型參數 7 if (dic != null) 8 foreach (var item in dic) 9 fun.SetValue(item.Key, item.Value); 10 11 //table類型,表結構參數 12 if (dic2 != null) 13 foreach (var item in dic2) 14 { 15 IRfcTable table = fun.GetTable(item.Key); 16 foreach (var itemval in item.Value) 17 { 18 table.Insert(); 19 Dictionary<string, string> dicobj = itemval.ToObject<Dictionary<string, string>>(); 20 foreach (var obj in dicobj) 21 { 22 table.CurrentRow.SetValue(obj.Key, obj.Value); 23 } 24 } 25 } 26 27 fun.Invoke(des);//調用 28 29 //處理返回結果 30 for (int i = 0; i < fun.Count; i++) 31 { 32 //IRfcTable轉datatable 33 try 34 { 35 object RfcResult = fun[i].GetObject(); 36 if (RfcResult == null || RfcResult.GetType().Name == "String") 37 { 38 RfcTableToDataTable(fun[i].GetValue().ToString(), fun[i].Metadata.Name, ds); 39 } 40 else if (RfcResult.GetType().Name == "RfcTable") 41 { 42 IRfcTable rfctable = fun[i].GetTable(); 43 ds.Tables.Add(RfcTableToDataTable(rfctable, fun[i].Metadata.Name)); 44 } 45 else if (RfcResult.GetType().Name == "RfcStructure") 46 { 47 IRfcStructure rfctable = fun[i].GetStructure(); 48 foreach (var item in rfctable) 49 { 50 RfcTableToDataTable(item.GetString(), item.Metadata.Name, ds); 51 } 52 } 53 } 54 catch (Exception ex) 55 { 56 continue; 57 } 58 59 } 60 return ds; 61 }
最后,還有一點要提醒的是,sapnco.dll要運行在Microsoft Visual C++ 2010 Redistributable Package (x64)以上版本的環境下,就是說要去下載安裝才能跑起來!!