public static string Save_sap_settings(SharedSettings.Settings settings) { SAP_CNX conexion = new SAP_CNX(); string mensajeconn = ""; try { //Establecemos conexion con SAP RfcConfigParameters rfc = GetParameters(conexion, settings); RfcDestination rfcDest = null; rfcDest = RfcDestinationManager.GetDestination(rfc); //Creamos repositorio para la función RfcRepository repo = rfcDest.Repository; IRfcFunction save_settings = repo.CreateFunction("Z_MAIL_SYNC_SETTINGS"); //save_settings.SetValue("BUKRS", settings.company_code); save_settings.SetValue("FOLDER_FILE", ""); string DELETE_ATTACH = ""; //if (settings.delete_files_at_attach) DELETE_ATTACH = ""; save_settings.SetValue("DELETE_ATTACH", DELETE_ATTACH); //Ejecutamos la consulta save_settings.Invoke(rfcDest); IRfcStructure bapiret = save_settings.GetStructure("RETURN"); string type = bapiret.GetString("TYPE"); if (type == "E") { return(mensajeconn); } else { return(mensajeconn); } } catch (RfcCommunicationException e) { //throw e; return(e.Message); } catch (RfcLogonException e) { // user could not logon... return(e.Message); //throw e; } catch (RfcAbapRuntimeException e) { // serious problem on ABAP system side... //throw e; return(e.Message); } catch (RfcAbapBaseException e) { // The function module returned an ABAP exception, an ABAP message // or an ABAP class-based exception... //throw e; return(e.Message); } catch (Exception e) { //throw e; return(e.Message); } }
private static void processSingleIdoc(IRfcStructure tControl, IRfcTable datarows) { Idoc idoc = new Idoc { TABNAM = tControl["TABNAM"].GetValue().ToString().Trim(), MANDT = tControl["MANDT"].GetValue().ToString().Trim(), DOCNUM = tControl["DOCNUM"].GetValue().ToString().Trim(), DOCREL = tControl["DOCREL"].GetValue().ToString().Trim(), STATUS = tControl["STATUS"].GetValue().ToString().Trim(), DIRECT = tControl["DIRECT"].GetValue().ToString().Trim(), OUTMOD = tControl["OUTMOD"].GetValue().ToString().Trim(), EXPRSS = tControl["EXPRSS"].ToString().Trim(), IDOCTYP = tControl["IDOCTYP"].GetValue().ToString().Trim(), CIMTYP = tControl["CIMTYP"].GetValue().ToString().Trim(), MESTYP = tControl["MESTYP"].GetValue().ToString().Trim(), MESCOD = tControl["MESCOD"].GetValue().ToString().Trim(), MESFCT = tControl["MESFCT"].GetValue().ToString().Trim(), STD = tControl["STD"].GetValue().ToString().Trim(), STDVRS = tControl["STDVRS"].GetValue().ToString().Trim(), STDMES = tControl["STDMES"].GetValue().ToString().Trim(), SNDPOR = tControl["SNDPOR"].GetValue().ToString().Trim(), SNDPRT = tControl["SNDPRT"].GetValue().ToString().Trim(), SNDPFC = tControl["SNDPFC"].GetValue().ToString().Trim(), SNDPRN = tControl["SNDPRN"].GetValue().ToString().Trim(), SNDSAD = tControl["SNDSAD"].GetValue().ToString().Trim(), SNDLAD = tControl["SNDLAD"].GetValue().ToString().Trim(), RCVPOR = tControl["RCVPOR"].GetValue().ToString().Trim(), RCVPRT = tControl["RCVPRT"].GetValue().ToString().Trim(), RCVPFC = tControl["RCVPFC"].GetValue().ToString().Trim(), RCVPRN = tControl["RCVPRN"].GetValue().ToString().Trim(), RCVSAD = tControl["RCVSAD"].GetValue().ToString().Trim(), RCVLAD = tControl["RCVLAD"].GetValue().ToString().Trim(), CREDAT = tControl["CREDAT"].GetValue().ToString().Trim(), CRETIM = tControl["CRETIM"].GetValue().ToString().Trim(), REFINT = tControl["REFINT"].GetValue().ToString().Trim(), REFGRP = tControl["REFGRP"].GetValue().ToString().Trim(), REFMES = tControl["REFMES"].GetValue().ToString().Trim(), ARCKEY = tControl["ARCKEY"].GetValue().ToString().Trim(), SERIAL = tControl["SERIAL"].GetValue().ToString().Trim() }; Hashtable hashtable = new Hashtable(); for (int i = 0; i < datarows.RowCount; i++) { IRfcStructure structure = datarows[i]; if (structure["DOCNUM"].GetValue().ToString().Trim().Equals(tControl["DOCNUM"].GetValue().ToString().Trim())) { IdocSegment newSegment = new IdocSegment(); if (structure["PSGNUM"].GetValue().ToString() == "000000") { idoc.Segments.Add(newSegment); } else { IdocSegment segment2 = (IdocSegment)hashtable[structure["PSGNUM"].GetValue().ToString()]; if (segment2 != null) { segment2.ChildSegments.Add(newSegment); } else { idoc.Segments.Add(newSegment); } } newSegment.SegmentName = structure["SEGNAM"].GetValue().ToString(); string content = structure["SDATA"].GetValue().ToString(); newSegment.WriteDataBuffer(content, 0, 0x3e8); if (!hashtable.ContainsKey(structure["SEGNUM"].GetValue().ToString())) { hashtable.Add(structure["SEGNUM"].GetValue().ToString(), newSegment); } } } // IdocMeta idocMeta = new IdocMeta(ConfigFileTool.SAPGlobalSettings.GetDefaultSapCient(), idoc); // idocMeta.getIdocTypeDefinition(); // idocMeta.deCompileIdoc(); idoc.SavePlainData(@"d:/test.txt"); //idocsegment e1maram = idoc.segments["E2MARAM006", 0]; //// loop through segments and find the right ones //for (int i = 0; i < e1maram.childsegments.count; i++) // if (e1maram.childsegments[i].segmentname == "e2maktm001") // console.writeline("materialtext found: " + // e1maram.childsegments[i].readdatabuffer(4, 40)); }
public SAPRfcReturn PostWWPOToSAP(List <WWPO> wwpoList) { try { NcoFunction ncoClient = new NcoFunction(); string[] rfcArray = ConfigHelper.LoadRFCConfig(ConfigHelper.strDestinationName); ncoClient.Connect(rfcArray[0], "", rfcArray[3], rfcArray[4], "ZH", rfcArray[5], rfcArray[8], 2, 10, "", rfcArray[9]); ncoClient.FunctionName = MES2SAPRfcFunctionName.WWPO; Dictionary <string, object> importParameters = new Dictionary <string, object>(); DataTable dtDetail = new DataTable(); dtDetail.Columns.Add("EBELN", typeof(string)); dtDetail.Columns.Add("EBELP", typeof(int)); dtDetail.Columns.Add("LIFNR", typeof(string)); dtDetail.Columns.Add("MATNR", typeof(string)); dtDetail.Columns.Add("BWART", typeof(string)); dtDetail.Columns.Add("MENGE", typeof(decimal)); dtDetail.Columns.Add("MEINS", typeof(string)); dtDetail.Columns.Add("WERKS", typeof(string)); dtDetail.Columns.Add("LGORT", typeof(string)); dtDetail.Columns.Add("ZNUMBER", typeof(string)); dtDetail.Columns.Add("DATUM", typeof(int)); dtDetail.Columns.Add("SGTXT", typeof(string)); foreach (var wwpo in wwpoList) { DataRow row = dtDetail.NewRow(); row["EBELN"] = wwpo.PONO; row["EBELP"] = wwpo.POLine; row["LIFNR"] = wwpo.VendorCode; row["MATNR"] = wwpo.MCode; row["BWART"] = wwpo.InOutFlag; row["MENGE"] = wwpo.Qty; row["MEINS"] = wwpo.Unit; row["WERKS"] = wwpo.FacCode; row["LGORT"] = wwpo.StorageCode; row["ZNUMBER"] = wwpo.MesTransNO; row["DATUM"] = wwpo.MesTransDate; row["SGTXT"] = wwpo.Remark; dtDetail.Rows.Add(row); } IRfcTable rfcTable = ncoClient.ConvertDataTabletoRFCTable(dtDetail, MES2SAPRfcInTableName.WWPO); importParameters.Add(MES2SAPRfcInTableName.WWPO, rfcTable); ncoClient.ImportParameters = importParameters; Dictionary <string, object> exportParameters = new Dictionary <string, object>(); ncoClient.Execute(ref exportParameters); object parameter = null; SAPRfcReturn re = new SAPRfcReturn(); if (exportParameters != null) { if (exportParameters.TryGetValue("ES_RESULT", out parameter)) { IRfcStructure ROFStrcture = parameter as IRfcStructure; re.Result = ROFStrcture["RETUN"].GetValue().ToString(); re.MaterialDocument = ROFStrcture["MBLNR"].GetValue().ToString(); re.Message = ROFStrcture["MESSG"].GetValue().ToString(); } } return(re); } catch (Exception ex) { throw ex; } }
public ISapStructure FromSapObject(IRfcStructure s) { this.MANU_MAT = s.GetString("MANU_MAT"); this.MFR_NO = s.GetString("MFR_NO"); return(this); }
public static string SAPDualExecute(Hashtable[] arrht, Hashtable ImportStr, Hashtable ImportData, string Function_Name, string RfcStructure_Name, string RfcStructure_Name2, string SetTable_Name) { RfcConfigParameters configParam = GetConfigParam(); RfcDestination destination = RfcDestinationManager.GetDestination(configParam); IRfcFunction function = destination.Repository.CreateFunction(Function_Name); IRfcTable rfcTable = function.GetTable(SetTable_Name); RfcStructureMetadata strMeta2 = destination.Repository.GetStructureMetadata(RfcStructure_Name2); IRfcStructure rfcStructure2 = strMeta2.CreateStructure(); for (int i = 0; i < arrht.Length; i++) { RfcStructureMetadata strMeta = destination.Repository.GetStructureMetadata(RfcStructure_Name); IRfcStructure rfcStructure = strMeta.CreateStructure(); IDictionaryEnumerator ie = arrht[i].GetEnumerator(); while (ie.MoveNext()) { if (ie.Value.ToString().Length <= 4000) { rfcStructure.SetValue(ie.Key.ToString(), ie.Value); } } rfcTable.Append(rfcStructure); } if (ImportStr.Count > 0) { IDictionaryEnumerator ie = ImportStr.GetEnumerator(); while (ie.MoveNext()) { if (ie.Value.ToString().Length <= 4000) { rfcStructure2.SetValue(ie.Key.ToString(), ie.Value); } } } if (ImportData.Count > 0) { IDictionaryEnumerator ie = ImportData.GetEnumerator(); while (ie.MoveNext()) { if (ie.Value.ToString().Length <= 4000) { function.SetValue(ie.Key.ToString(), ie.Value); } } } function.SetValue("IV_HEADER", rfcStructure2); function.Invoke(destination); string returnCode = function.GetString("EV_E_TYPE"); return(returnCode); }
internal virtual T ConvertRow(IRfcStructure row) { string[] data = row.GetString("WA").Split(_separator); return(ConvertDataArray(data)); }
public void Run() { try { SendMessage("Run开始"); IRfcFunction function; IRfcTable table2; this._LastPrimaryKey = ""; this._FetchedRows = 0; if ((this._RowCount == 0) && (this._PackageSize > 0)) { this._RowCount = 0x11d260c0; } this.anzahlaufrufe = 0; if (this._FunctionName.Equals("")) { bool isUnicode = this._des.Repository.UnicodeEnabled; if (this._UsePrimaryKeyPackaging) { throw new SAPException(Messages.Donotuseprimaykeypackagingwithoutacustomfunctionmodule); //throw new Exception("Donot use primaykey packaging without a custom function module"); } function = _des.Repository.CreateFunction("RFC_READ_TABLE"); } else { try { SendMessage("读取函数元数据" + _FunctionName); function = this._des.Repository.CreateFunction(this._FunctionName); SendMessage("读取函数元数据完成" + _FunctionName); } catch (RfcAbapException ee) { throw new SAPException(ee.Key + ee.Message); } IRfcTable table3 = function.GetTable("OPTIONS"); table2 = function.GetTable("FIELDS"); IRfcTable table = function.GetTable("DATA"); } if (this._UsePrimaryKeyPackaging) { this._PrimaryKeys.Clear(); IRfcFunction function2 = _des.Repository.CreateFunction("DDIF_FIELDINFO_GET");//.GenerateFunctionObjectForDDIF_FIELDINFO_GET(this.con.IsUnicode); //function2.Connection = this.con; function2["TABNAME"].SetValue(this.TableName); function2.Invoke(_des); foreach (IRfcStructure structure in function2.GetTable("DFIES_TAB").ToList()) { if (structure["KEYFLAG"].GetValue().ToString().Equals("X")) { ReadTableField newParameter = new ReadTableField(structure["FIELDNAME"].GetValue().ToString(), Convert.ToInt32(structure["OUTPUTLEN"].GetValue()), "C", "", 0); this._PrimaryKeys.Add(newParameter); // this.con.Log("Primary key Add " + newParameter); } } } if (this.UsePrimaryKeyPackaging) { for (int j = 0; j < this._PrimaryKeys.Count; j++) { // table2.AddRow()["FIELDNAME"] = this._PrimaryKeys[j].FieldName; table2 = function.GetTable("FIELDS"); table2.Append(); table2.CurrentRow["FIELDNAME"].SetValue(this._PrimaryKeys[j].FieldName); } if (this.fields.Count == 0) { this.GetAllFieldsOfTable(); for (int k = 0; k < this._Fields.Count; k++) { this.AddField(this._Fields[k].FieldName); } } } for (int i = 0; i < this.fields.Count; i++) { table2 = function.GetTable("FIELDS"); table2.Append(); table2.CurrentRow["FIELDNAME"].SetValue(this.fields[i].ToString()); } function["QUERY_TABLE"].SetValue(this.TableName); if ((this._PackageSize > 0) && ((this._RowCount > this._PackageSize) || (this._RowCount == 0))) { function["ROWCOUNT"].SetValue(this._PackageSize); function["ROWSKIPS"].SetValue(0); } else { function["ROWCOUNT"].SetValue(this._RowCount); function["ROWSKIPS"].SetValue(this._RowSkip); } if (this.OHSExtraction) { function["ROWCOUNT"].SetValue(0); function["ROWSKIPS"].SetValue(0); this.OHSLastPackageNr = 1; function["REQUESTID"].SetValue(this.OHSRequestID); function["PACKETID"].SetValue(this.OHSLastPackageNr); } this.ExecuteRFC_READ_TABLE(ref function); this.fields.Clear(); this.t = new DataTable(); SendMessage("初始化DATATABLE开始"); this.t.BeginInit(); table2 = function.GetTable("FIELDS"); if (this.UsePrimaryKeyPackaging) { this._Fields.Clear(); for (int m = this._PrimaryKeys.Count; m < table2.RowCount; m++) { IRfcStructure structure4 = table2[m]; this.t.Columns.Add(table2[m][0].GetValue().ToString().Trim(), Type.GetType("System.String")); this._Fields.Add(new ReadTableField(structure4["FIELDNAME"].GetValue().ToString(), Convert.ToInt32(structure4["LENGTH"].GetValue()), structure4["TYPE"].GetValue().ToString(), structure4["FIELDTEXT"].GetValue().ToString(), 0)); } } else { this._Fields.Clear(); for (int n = 0; n < table2.RowCount; n++) { IRfcStructure structure5 = table2[n]; this.t.Columns.Add(table2[n][0].GetValue().ToString().Trim(), Type.GetType("System.String")); this._Fields.Add(new ReadTableField(structure5["FIELDNAME"].GetValue().ToString(), Convert.ToInt32(structure5["LENGTH"].GetValue()), structure5["TYPE"].GetValue().ToString(), structure5["FIELDTEXT"].GetValue().ToString(), 0)); } } this.t.EndInit(); SendMessage("初始化DATATABLE结束"); this.ProcessRetrievdData(ref this.t, function); bool flag2 = false; if ((this._PackageSize > 0) && (this._FetchedRows < this._RowCount)) { flag2 = true; } while (flag2) { if (this.OHSExtraction) { function["ROWCOUNT"].SetValue(0); function["ROWSKIPS"].SetValue(0); this.OHSLastPackageNr++; function["REQUESTID"].SetValue(this.OHSRequestID); function["PACKETID"].SetValue(this.OHSLastPackageNr); } else { function["ROWCOUNT"].SetValue(this.PackageSize); function["ROWSKIPS"].SetValue(this._FetchedRows); if ((this.RowCount > 0) && ((this._FetchedRows + this.PackageSize) > this.RowCount)) { function["ROWCOUNT"].SetValue(this.RowCount - this._FetchedRows); } } function.GetTable("DATA").Clear(); this.ExecuteRFC_READ_TABLE(ref function); this.ProcessRetrievdData(ref this.t, function); if ((this._FetchedRows >= this._RowCount) && (this._RowCount > 0)) { flag2 = false; } if (function.GetTable("DATA").RowCount < this.PackageSize) { flag2 = false; } if (this.OHSExtraction && (function.GetTable("DATA").RowCount > 0)) { flag2 = true; } } SendMessage("Run结束"); } catch (Exception e) { if (this.EventMessage != null) { this.EventMessage(e.Message); } else { throw; } } //function.Tables["DATA"].Dispose(); }
/// <summary> /// 1. if no parameter :IV_DOCOMMIT then no effect /// 2. RUN_ID:if not same number then no effect /// 3. IT_BP_GENERAL-OBJECT_TASK: insert mode I /// </summary> /// <returns></returns> public string CreateBP() { if (rfcDestination == null) { rfcDestination = RfcDestinationManager.GetDestination(WebApiApplication.destinationConfigName); } RfcRepository repo = rfcDestination.Repository; IRfcFunction _CUSTOMER = repo.CreateFunction("RFC_CVI_EI_INBOUND_MAIN"); _CUSTOMER.SetValue("IV_DOCOMMIT", "X"); //required //IRfcFunction _Commit = repo.CreateFunction("BAPI_TRANSACTION_COMMIT"); IRfcTable _IT_BP_GENERAL = _CUSTOMER.GetTable("IT_BP_GENERAL"); IRfcStructure _IT_BP_GENERALStruct = _IT_BP_GENERAL.Metadata.LineType.CreateStructure(); _IT_BP_GENERALStruct.SetValue("RUN_ID", "1"); _IT_BP_GENERALStruct.SetValue("OBJECT_TASK", "I"); _IT_BP_GENERALStruct.SetValue("BPARTNER", ""); _IT_BP_GENERALStruct.SetValue("NAME1", "LLLLL"); _IT_BP_GENERALStruct.SetValue("CATEGORY", 2);//required _IT_BP_GENERALStruct.SetValue("GROUPING", "1000"); _IT_BP_GENERALStruct.SetValue("SEARCHTERM1", "國度"); _IT_BP_GENERALStruct.SetValue("SEARCHTERM2", "資料"); _IT_BP_GENERALStruct.SetValue("FOUNDATIONDATE", DateTime.Now.ToString("yyyyMMdd")); _IT_BP_GENERALStruct.SetValue("TITLE_KEY", ""); _IT_BP_GENERALStruct.SetValue("AUTHORIZATIONGROUP", ""); _IT_BP_GENERALStruct.SetValue("PARTNEREXTERNAL", ""); _IT_BP_GENERAL.Append(_IT_BP_GENERALStruct); IRfcTable _IT_BP_ROLE = _CUSTOMER.GetTable("IT_BP_ROLE"); IRfcStructure _IT_BP_ROLEStruct = _IT_BP_ROLE.Metadata.LineType.CreateStructure(); IRfcStructure _IT_BP_ROLEStruct2 = _IT_BP_ROLE.Metadata.LineType.CreateStructure(); _IT_BP_ROLEStruct.SetValue("RUN_ID", "1"); //required _IT_BP_ROLEStruct.SetValue("DATA_KEY", "FLCU00"); _IT_BP_ROLEStruct.SetValue("ROLECATEGORY", "2"); _IT_BP_ROLE.Append(_IT_BP_ROLEStruct); _IT_BP_ROLEStruct2.SetValue("RUN_ID", "1");//required _IT_BP_ROLEStruct2.SetValue("DATA_KEY", "1000"); _IT_BP_ROLEStruct2.SetValue("ROLECATEGORY", "2"); _IT_BP_ROLE.Append(_IT_BP_ROLEStruct2); IRfcTable _IT_BP_ADDRESS = _CUSTOMER.GetTable("IT_BP_ADDRESS"); IRfcStructure _IT_BP_ADDRESStruct = _IT_BP_ADDRESS.Metadata.LineType.CreateStructure(); _IT_BP_ADDRESStruct.SetValue("RUN_ID", "1");//required _IT_BP_ADDRESStruct.SetValue("STANDARDADDRESS", "X"); _IT_BP_ADDRESStruct.SetValue("COUNTRY", "US"); _IT_BP_ADDRESStruct.SetValue("LANGUISO", "EN"); _IT_BP_ADDRESStruct.SetValue("LANGU", "E"); _IT_BP_ADDRESS.Append(_IT_BP_ADDRESStruct); RfcSessionManager.BeginContext(rfcDestination); _CUSTOMER.Invoke(rfcDestination); //_Commit.Invoke(rfcDestination); RfcSessionManager.EndContext(rfcDestination); DataTable dtReturn = ConvertToDotNetTable(_CUSTOMER.GetTable("CT_RETURN")); List <ErrorLog> _ErrorList = new List <ErrorLog>(); string _Number = ""; if (dtReturn.Rows.Count > 0) { _Number = dtReturn.Rows[0]["OBJECT_KEY"].ToString() == "" ? "" : dtReturn.Rows[0]["OBJECT_KEY"].ToString(); _ErrorList = SetErrorLog(dtReturn, "RFC_CVI_EI_INBOUND_MAIN", _Number, ""); } List <string> _Error = this._errorLogService.MiltiCreate(_ErrorList); //test //RfcRepository repo2 = rfcDestination.Repository; //IRfcFunction _CUSTOMER2 = repo2.CreateFunction("RFC_CVI_EI_INBOUND_MAIN"); //_CUSTOMER2.SetValue("IV_DOCOMMIT", "X"); //IRfcFunction _Commit2 = repo.CreateFunction("BAPI_TRANSACTION_COMMIT"); //IRfcTable _IT_BP_GENERAL2 = _CUSTOMER2.GetTable("IT_BP_GENERAL"); //IRfcStructure _IT_BP_GENERAL2Struct = _IT_BP_GENERAL2.Metadata.LineType.CreateStructure(); //_IT_BP_GENERAL2Struct.SetValue("RUN_ID", "1"); //_IT_BP_GENERAL2Struct.SetValue("OBJECT_TASK", "U"); //_IT_BP_GENERAL2Struct.SetValue("BPARTNER", "0010002183"); //_IT_BP_GENERAL2Struct.SetValue("SEARCHTERM1", "國度1234"); //_IT_BP_GENERAL2.Append(_IT_BP_GENERAL2Struct); //RfcSessionManager.BeginContext(rfcDestination); //_CUSTOMER2.Invoke(rfcDestination); //_Commit2.Invoke(rfcDestination); //RfcSessionManager.EndContext(rfcDestination); //DataTable dtReturn2 = ConvertToDotNetTable(_CUSTOMER2.GetTable("CT_RETURN")); return(_Number); }
/// <summary> /// 调用RFC,返回一个内表参数 /// </summary> /// <param name="conn"></param> /// <param name="param"></param> /// <param name="rfcName"></param> /// <param name="irfcStructureName"></param> /// <param name="irfcStru"></param> /// <param name="irfcTableName"></param> /// <param name="irfcTab"></param> /// <param name="outStringName"></param> /// <returns></returns> public DataTable GetRfcOutTable(string conn, string[] param, string rfcName, string irfcStructureName, IRfcStructure irfcStru, string irfcTableName, IRfcTable irfcTab, string outTableName) { //1.登录SAP RfcConfigParameters parameters = GetRfcLoginParameters(conn);//获取登录参数 RfcDestination rd = RfcDestinationManager.GetDestination(parameters); RfcRepository repo = rd.Repository; IRfcFunction f = repo.CreateFunction(rfcName); //调用函数名 //传入字符参数 foreach (string value in param) { string[] keyvalue = value.Split('|'); f.SetValue(keyvalue[0], keyvalue[1].Trim());//传递入参数 } //传入 sap结构 参数 f.SetValue(irfcStructureName, irfcStru); //传入内表参数 f.SetValue(irfcTableName, irfcTab); f.Invoke(rd); //执行函数 rd = null; return(ConvertToTable(f.GetTable(outTableName))); }
private void InitWhereClause(ref IRfcTable toptions) { toptions.Clear(); if (this._WhereClause.Equals("")) { for (int i = 0; i < this.options.Count; i++) { toptions.Append(); toptions.CurrentRow.SetValue("TEXT", this.options[i].ToString()); //toptions.AddRow()["TEXT"] = this.options[i].ToString(); } } else { for (int j = 0; j < this._WhereClause.Length; j += 0x48) { if ((this._WhereClause.Length - j) > 0x48) { IRfcStructure structure2 = toptions.Metadata.LineType.CreateStructure(); bool flag = false; for (int k = 0; k < 0x47; k++) { if (this._WhereClause.Substring((j + 0x47) - k, 1).Equals(" ")) { structure2["TEXT"].SetValue(this._WhereClause.Substring(j, 0x48 - k)); toptions.Append(structure2); j -= k; flag = true; k = 0x48; } } if (!flag) { structure2["TEXT"].SetValue(this._WhereClause.Substring(j, 0x48)); toptions.Append(structure2); } } else { // toptions.AddRow()["TEXT"] = this._WhereClause.Substring(j); toptions.Append(); toptions.CurrentRow["TEXT"].SetValue(this._WhereClause.Substring(j)); } } string str = ""; foreach (IRfcStructure structure4 in toptions.ToList()) { str = str + structure4["TEXT"].ToString() + "\r\n"; } } if (this._UsePrimaryKeyPackaging) { if (toptions.ToList().Count == 0) { this.AddWhereLine(toptions, "("); } else { this.AddWhereLine(toptions, "AND ("); } for (int m = 0; m < this._PrimaryKeys.Count; m++) { string whereline = this._PrimaryKeys[m].FieldName + " >= '" + this._PrimaryKeys[m].LastKeyValue + "'"; if (m == 0) { whereline = "( " + whereline; } else { whereline = "AND " + whereline; } if (m == (this._PrimaryKeys.Count - 1)) { whereline = whereline + " )"; } this.AddWhereLine(toptions, whereline); } for (int n = 0; n < this._PrimaryKeys.Count; n++) { for (int num6 = n; num6 >= 0; num6--) { string str3; if (num6 == n) { str3 = "OR ( " + this._PrimaryKeys[num6].FieldName + " > '" + this._PrimaryKeys[num6].LastKeyValue + "'"; } else { str3 = "AND " + this._PrimaryKeys[num6].FieldName + " >= '" + this._PrimaryKeys[num6].LastKeyValue + "'"; } if (num6 == 0) { str3 = str3 + " )"; } this.AddWhereLine(toptions, str3); } } //toptions.AddRow()["TEXT"] = ")"; toptions.Append(); toptions.CurrentRow.SetValue("TEXT", ")"); } //if (!this.con.LogDir.Equals("")) //{ // this.con.Log("Building where: "); // foreach (RFCStructure structure6 in toptions.Rows) // { // this.con.Log(structure6["TEXT"].ToString()); // } //} }
/// <summary> /// 直接调用RFC,不返回任何东西 /// </summary> /// <param name="conn"></param> /// <param name="param">需要传入的字符串参数 例:{"P1|value1","P2|value2"}</param> /// <param name="rfcName"></param> /// <param name="irfcStructureName"></param> /// <param name="irfcStru"></param> public void ExecuteRFC(string conn, string[] param, string rfcName, string irfcStructureName, IRfcStructure irfcStru) { //1.登录SAP RfcConfigParameters parameters = GetRfcLoginParameters(conn);//获取登录参数 RfcDestination rd = RfcDestinationManager.GetDestination(parameters); RfcRepository repo = rd.Repository; IRfcFunction f = repo.CreateFunction(rfcName); //调用函数名 //传入字符参数 foreach (string value in param) { string[] keyvalue = value.Split('|'); f.SetValue(keyvalue[0], keyvalue[1].Trim());//传递入参数 } //传入 sap结构 参数 f.SetValue(irfcStructureName, irfcStru); f.Invoke(rd); //执行函数 rd = null; }
/// <summary> /// you need excute(se38) ABLM_MODIFY_ITEMS in sap system and set relavant parameter /// previous when you use BAPI_SALESORDER_CREATEFROMDAT2 this RFC module /// </summary> /// <param name="destinationName"></param> /// <returns></returns> public string CreateOrder(SapSalesOrder salesOrder) { if (rfcDestination == null) { rfcDestination = RfcDestinationManager.GetDestination(WebApiApplication.destinationConfigName); } RfcRepository repo = rfcDestination.Repository; IRfcFunction _SalesDoc = repo.CreateFunction("BAPI_SALESORDER_CREATEFROMDAT2"); IRfcFunction _SalesDocCommit = repo.CreateFunction("BAPI_TRANSACTION_COMMIT"); IRfcStructure _SalesHeader = _SalesDoc.GetStructure("ORDER_HEADER_IN"); IRfcTable _SalesItems = _SalesDoc.GetTable("ORDER_ITEMS_IN"); IRfcTable _SalesPartners = _SalesDoc.GetTable("ORDER_PARTNERS"); IRfcTable _SalesSchedule = _SalesDoc.GetTable("ORDER_SCHEDULES_IN"); _SalesHeader.SetValue("DOC_TYPE", salesOrder.Header.DOC_TYPE); _SalesHeader.SetValue("SALES_ORG", salesOrder.Header.SALES_ORG); _SalesHeader.SetValue("DISTR_CHAN", salesOrder.Header.DISTR_CHAN); _SalesHeader.SetValue("DIVISION", salesOrder.Header.DIVISION); _SalesHeader.SetValue("PURCH_NO_C", salesOrder.Header.PURCH_NO_C); //test 採購日期 _SalesHeader.SetValue("PURCH_DATE", salesOrder.Header.PURCH_DATE); foreach (SalesItem si in salesOrder.ItemList) { IRfcStructure _SalesItemsStruct = _SalesItems.Metadata.LineType.CreateStructure(); _SalesItemsStruct.SetValue("ITM_NUMBER", si.ITM_NUMBER); //_SalesItemsStruct.SetValue("MATERIAL", si.MATERIAL); _SalesItemsStruct.SetValue("MATERIAL_LONG", si.MATERIAL); _SalesItemsStruct.SetValue("TARGET_QTY", si.TARGET_QTY); //test 客戶物料號碼 _SalesItemsStruct.SetValue("CUST_MAT35", si.CUST_MAT35); _SalesItems.Append(_SalesItemsStruct); } foreach (SalesPartner sp in salesOrder.PartnerList) { IRfcStructure _SalesPartnersStruct = _SalesPartners.Metadata.LineType.CreateStructure(); _SalesPartnersStruct.SetValue("PARTN_ROLE", sp.PARTN_ROLE); _SalesPartnersStruct.SetValue("PARTN_NUMB", sp.PARTN_NUMB); _SalesPartners.Append(_SalesPartnersStruct); } foreach (SalesSchedule ss in salesOrder.ScheduleList) { IRfcStructure _SalesScheduleStruct = _SalesSchedule.Metadata.LineType.CreateStructure(); _SalesScheduleStruct.SetValue("REQ_QTY", ss.REQ_QTY); _SalesScheduleStruct.SetValue("ITM_NUMBER", ss.ITM_NUMBER); _SalesScheduleStruct.SetValue("SCHED_LINE", ss.SCHED_LINE); _SalesScheduleStruct.SetValue("REQ_DATE", ss.REQ_DATE); _SalesSchedule.Append(_SalesScheduleStruct); } ////salesPartnersStruct.SetValue("PARTN_ROLE", "RE"); ////salesPartnersStruct.SetValue("PARTN_NUMB", "0010000650"); ////salesPartners.Append(salesPartnersStruct); RfcSessionManager.BeginContext(rfcDestination); _SalesDoc.Invoke(rfcDestination); _SalesDocCommit.Invoke(rfcDestination); RfcSessionManager.EndContext(rfcDestination); string _SalesCocument = _SalesDoc.GetString("SALESDOCUMENT"); DataTable dtReturn = ConvertToDotNetTable(_SalesDoc.GetTable("RETURN")); List <ErrorLog> _ErrorList = SetErrorLog(dtReturn, "BAPI_SALESORDER_CREATEFROMDAT2", _SalesCocument, salesOrder.Header.PURCH_NO_C); List <string> _Error = this._errorLogService.MiltiCreate(_ErrorList); return(_SalesCocument); }
public string CreateSalesArea(string number) { if (rfcDestination == null) { rfcDestination = RfcDestinationManager.GetDestination(WebApiApplication.destinationConfigName); } RfcRepository repo = rfcDestination.Repository; IRfcFunction _CUSTOMER = repo.CreateFunction("RFC_CVI_EI_INBOUND_MAIN"); _CUSTOMER.SetValue("IV_DOCOMMIT", "X");// required //IRfcFunction _Commit = repo.CreateFunction("BAPI_TRANSACTION_COMMIT"); IRfcTable _IT_CUST_GENERAL = _CUSTOMER.GetTable("IT_CUST_GENERAL"); IRfcStructure _IT_CUST_GENERALStruct = _IT_CUST_GENERAL.Metadata.LineType.CreateStructure(); _IT_CUST_GENERALStruct.SetValue("RUN_ID", "2"); _IT_CUST_GENERALStruct.SetValue("KUNNR", number); _IT_CUST_GENERALStruct.SetValue("OBJECT_TASK", "I"); _IT_CUST_GENERALStruct.SetValue("BAHNE", "25"); _IT_CUST_GENERAL.Append(_IT_CUST_GENERALStruct); IRfcTable _IT_CUST_SALES = _CUSTOMER.GetTable("IT_CUST_SALES"); IRfcStructure _IT_CUST_SALESStruct = _IT_CUST_SALES.Metadata.LineType.CreateStructure(); _IT_CUST_SALESStruct.SetValue("RUN_ID", "2"); _IT_CUST_SALESStruct.SetValue("VKORG", "1000"); _IT_CUST_SALESStruct.SetValue("VTWEG", "00"); _IT_CUST_SALESStruct.SetValue("SPART", "00"); _IT_CUST_SALESStruct.SetValue("KALKS", "1"); _IT_CUST_SALESStruct.SetValue("VSBED", "01"); _IT_CUST_SALESStruct.SetValue("WAERS", "USD"); _IT_CUST_SALESStruct.SetValue("KDGRP", "02"); _IT_CUST_SALESStruct.SetValue("KURST", "E"); _IT_CUST_SALESStruct.SetValue("KONDA", "02"); _IT_CUST_SALESStruct.SetValue("BZIRK", "US"); _IT_CUST_SALESStruct.SetValue("INCO1", "EXW"); _IT_CUST_SALESStruct.SetValue("INCO2_L", "EXW"); _IT_CUST_SALES.Append(_IT_CUST_SALESStruct); IRfcTable _IT_CUST_TAX_INDICATOR = _CUSTOMER.GetTable("IT_CUST_TAX_INDICATOR"); IRfcStructure _IT_CUST_TAX_INDICATORStruct = _IT_CUST_TAX_INDICATOR.Metadata.LineType.CreateStructure(); _IT_CUST_TAX_INDICATORStruct.SetValue("RUN_ID", "2"); _IT_CUST_TAX_INDICATORStruct.SetValue("ALAND", "CN"); _IT_CUST_TAX_INDICATORStruct.SetValue("TATYP", "MWST"); _IT_CUST_TAX_INDICATORStruct.SetValue("TAXKD", "A"); _IT_CUST_TAX_INDICATOR.Append(_IT_CUST_TAX_INDICATORStruct); IRfcStructure _IT_CUST_TAX_INDICATORStruct2 = _IT_CUST_TAX_INDICATOR.Metadata.LineType.CreateStructure(); _IT_CUST_TAX_INDICATORStruct2.SetValue("RUN_ID", "2"); _IT_CUST_TAX_INDICATORStruct2.SetValue("ALAND", "TW"); _IT_CUST_TAX_INDICATORStruct2.SetValue("TATYP", "MWST"); _IT_CUST_TAX_INDICATORStruct2.SetValue("TAXKD", "6"); _IT_CUST_TAX_INDICATOR.Append(_IT_CUST_TAX_INDICATORStruct2); IRfcTable _IT_CUST_SALES_FUNCTIONS = _CUSTOMER.GetTable("IT_CUST_SALES_FUNCTIONS"); IRfcStructure _IT_CUST_SALES_FUNCTIONSStruct = _IT_CUST_SALES_FUNCTIONS.Metadata.LineType.CreateStructure(); _IT_CUST_SALES_FUNCTIONSStruct.SetValue("RUN_ID", "2"); _IT_CUST_SALES_FUNCTIONSStruct.SetValue("VKORG", "1000"); _IT_CUST_SALES_FUNCTIONSStruct.SetValue("VTWEG", "00"); _IT_CUST_SALES_FUNCTIONSStruct.SetValue("SPART", "00"); _IT_CUST_SALES_FUNCTIONSStruct.SetValue("PARVW", "SE"); _IT_CUST_SALES_FUNCTIONSStruct.SetValue("KNREF", "22"); _IT_CUST_SALES_FUNCTIONS.Append(_IT_CUST_SALES_FUNCTIONSStruct); RfcSessionManager.BeginContext(rfcDestination); _CUSTOMER.Invoke(rfcDestination); // _Commit.Invoke(rfcDestination); RfcSessionManager.EndContext(rfcDestination); DataTable dtReturn = ConvertToDotNetTable(_CUSTOMER.GetTable("CT_RETURN")); List <ErrorLog> _ErrorList = new List <ErrorLog>(); string _Number = ""; if (dtReturn.Rows.Count > 0) { _Number = dtReturn.Rows[0]["OBJECT_KEY"].ToString() == "" ? "" : dtReturn.Rows[0]["OBJECT_KEY"].ToString(); _ErrorList = SetErrorLog(dtReturn, "RFC_CVI_EI_INBOUND_MAIN", _Number, ""); } return(""); }
static void Main(string[] args) { string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); Appconfig.Initialize(path, ConfigurationManager.AppSettings, null); #region Logger log4net.GlobalContext.Properties["LOG4NET_ERROR"] = Appconfig.LOG4NET_ERROR; //log file path log4net.GlobalContext.Properties["LOG4NET_DEBUG"] = Appconfig.LOG4NET_DEBUG; //log file path log4net.Config.XmlConfigurator.Configure(); #endregion var currencyRatioDict = Appconfig.CurrencyRatioDict; DateTime programDatetime = DateTime.Now; DateTime runningDate; if (programDatetime.Hour > Appconfig.BOTHourUpdate) { runningDate = new DateTime(programDatetime.Year, programDatetime.Month, programDatetime.Day); } else { var programDatetimeYesterday = programDatetime.AddDays(-1); runningDate = new DateTime(programDatetimeYesterday.Year, programDatetimeYesterday.Month, programDatetimeYesterday.Day); } if (args != null && args.Count() > 0) { DateTime tryResult; if (DateTime.TryParseExact(args.First(), "d/MM/yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out tryResult)) { runningDate = tryResult; } } log.Debug("*******************************************************************"); log.Debug("PROGRAM RUNS ON " + programDatetime.ToString("dd/MM/yyyy HH:mm:ss")); log.Debug("*******************************************************************"); JsonLogService db = new JsonLogService(Appconfig.JsonLog); var dateToRun = new List <DateTime>(); if (!Appconfig.RecoveryMode) { dateToRun.Add(runningDate); // we could check last date run is yesterday|| today ? if not we cound add lost day in between var lastDataDate = db.GetLastRunningDate(); if (lastDataDate != default(DateTime) && lastDataDate.CompareTo(runningDate) < 0) // 0 means run second time for the day, 1 is not possible (if we do not force them to run future's day) { log.Debug("-----------------------------------------------------------------"); log.Debug("CHECKING LAST RUNING DATE FOR SPECIFY DATES TO RUN (IF THERE IS MISSING RUNNING ON SOME DAYS)"); log.Debug("-----------------------------------------------------------------"); var timeSpanDiff = runningDate.Subtract(lastDataDate); if (timeSpanDiff.TotalDays > 1) { int dayToRecover = Convert.ToInt32(timeSpanDiff.TotalDays) - 1; for (int i = 1; i <= dayToRecover; i++) { dateToRun.Add(runningDate.AddDays(-i)); } } } } else { foreach (var recoveryDate in Appconfig.RecoveryDate) { DateTime tryResult; if (DateTime.TryParseExact(recoveryDate, "d/M/yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out tryResult)) { dateToRun.Add(tryResult); } } } foreach (var transactionDate in dateToRun) { #region BOT API log.Debug("-----------------------------------------------------------------"); log.Debug("API Call Start"); log.Debug("-----------------------------------------------------------------"); //var todayLog = db.GetDailyLog(transactionDate);//?? List <Task> taskList = new List <Task>(); foreach (var currencyPair in Appconfig.SyncCurrency) { var currencyInDb = db.GetOrCreateCurrency(transactionDate, currencyPair); //if sap is sync we will not call api again if (currencyInDb.isSyncSAP == false) { if (currencyInDb.isAPIComplete) { log.Debug(String.Format(@"NOTE : THERE WAS FINISHED API CALL BUT SAP ERROR --> RECALL API AGAIN {0} {1}", currencyInDb.Currency, currencyInDb.Date.ToShortDateString())); } taskList.Add(APIExecute(currencyInDb, transactionDate)); } } var unfinishedAPI = db.GetUnfinishedBOTSync().Where(x => x.Date != transactionDate && Appconfig.SyncCurrency.Contains(x.Currency) && x.isSyncSAP == false); foreach (var currencyPair in unfinishedAPI) { taskList.Add(APIExecute(currencyPair, currencyPair.Date)); } Task.WhenAll(taskList).Wait(); log.Debug("-----------------------------------------------------------------"); log.Debug("API Call Successfully"); log.Debug("-----------------------------------------------------------------"); if (!db.SaveChange()) { log.Debug("-----------------------------------------------------------------"); log.Debug("Log Update Error"); log.Debug("-----------------------------------------------------------------"); } else { log.Debug("-----------------------------------------------------------------"); log.Debug("Log Update Successful"); log.Debug("-----------------------------------------------------------------"); } #endregion } #region API Patch for non-value date log.Debug("=============================================================================="); log.Debug("CHECK PATCHING START"); log.Debug("=============================================================================="); try { var patchingNeededDates = db.GetAllLog().Where(x => x.CurrenciesRate.Any(c => Appconfig.SyncCurrency.Contains(c.Currency) && c.isAPIComplete == true && c.isSyncSAP == false && c.Sell_SAP == (decimal)0 && c.Buy_SAP == (decimal)0)).ToList();//REVIEW if (patchingNeededDates.Count > 0) { log.Debug("PATCHING FOUND"); Patching(Appconfig.SyncCurrency, patchingNeededDates); log.Debug("PATCHING END"); } } catch (Exception ex) { log.Debug("=============================================================================="); log.Debug("CHECK PATCHING ERROR : CHECK THE EXCEPTION BELOW"); log.Debug("=============================================================================="); ExceptionHandling.LogException(ex); } #endregion #region SAP Part /// we will send sap only isAPIcomplete and if none of Buy and Sell we will use the last known value before that day to be value sent to SAP /// send only currency config, only isAPIComplete = true, only isSAPComplete = false log.Debug("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); log.Debug("SAP START"); log.Debug("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); bool isSAPCompleted = true; string SAPErrorMsg = string.Empty; try { var sapSent = db.GetAllLog().Where(x => x.CurrenciesRate.Any(c => Appconfig.SyncCurrency.Contains(c.Currency) && c.isAPIComplete == true && c.isSyncSAP == false && c.Sell_SAP != (decimal)0 && c.Buy_SAP != (decimal)0)).ToList(); #region SAP Connection DestinationRegister.RegistrationDestination(new SAPDestinationSetting { AppServerHost = Appconfig.SAPServerHost, Client = Appconfig.SAPClient, User = Appconfig.SAPUser, Password = Appconfig.SAPPassword, SystemNumber = Appconfig.SAPSystemNumber, SystemID = Appconfig.SAPSystemID, }); var des = RfcDestinationManager.GetDestination(DestinationRegister.Destination()); IRfcFunction function = des.Repository.CreateFunction("ZBAPI_EXCHANGERATE_UPDATE"); #endregion #region example for input structure as input bapi /* * TABLE :I_EXCHANGE * STRUCTURE BAPI1093_0 * RATE_TYPE Exchange Rate Type , B = buy // M = sell * FROM_CURR From currency * TO_CURRNCY To-currency * VALID_FROM Date from Which Entry Is Valid (yyyy-MM-dd) * EXCH_RATE Direct Quoted Exchange Rate * FROM_FACTOR Ratio for the "From" Currency Units, 1 // if JPY this is 100 * TO_FACTOR Ratio for the "To" Currency Units, 1 * EXCH_RATE_V Indirect Quoted Exchange Rate ****No input * FROM_FACTOR_V Ratio for the "From" Currency Units ****No input * TO_FACTOR_V Ratio for the "To" Currency Units ****No input */ IRfcTable table = function["I_EXCHANGE"].GetTable();//table List <CurrencyRate> sentSAP = new List <CurrencyRate>(); foreach (var dailyLog in sapSent) { foreach (var cur in dailyLog.CurrenciesRate.Where(c => Appconfig.SyncCurrency.Contains(c.Currency) && c.isAPIComplete == true && c.isSyncSAP == false && c.Sell_SAP != (decimal)0 && c.Buy_SAP != (decimal)0)) { table.Append(); //create new row IRfcStructure Buy = table.CurrentRow; //current structure ,row string structure_name = Buy.Metadata.Name; //Buy Buy.SetValue("RATE_TYPE", "B"); Buy.SetValue("FROM_CURR", cur.Currency); Buy.SetValue("TO_CURRNCY", "THB"); Buy.SetValue("VALID_FROM", dailyLog.Date.ToString("yyyy-MM-dd", new CultureInfo("en-US"))); Buy.SetValue("EXCH_RATE", cur.Buy_SAP.ToString("0.#####")); if (currencyRatioDict.ContainsKey(cur.Currency)) { Buy.SetValue("FROM_FACTOR", currencyRatioDict[cur.Currency]); } else { Buy.SetValue("FROM_FACTOR", 1); } Buy.SetValue("TO_FACTOR", 1); log.Debug(String.Format("{0} {1} {2} {3} {4}", "B", cur.Currency, "THB", dailyLog.Date.ToString("ddMMyyyy", new CultureInfo("en-US")), cur.Buy_SAP.ToString("0.#####"))); table.Append(); //create new row IRfcStructure Sell = table.CurrentRow; //current structure ,row //Sell Sell.SetValue("RATE_TYPE", "M"); Sell.SetValue("FROM_CURR", cur.Currency); Sell.SetValue("TO_CURRNCY", "THB"); Sell.SetValue("VALID_FROM", dailyLog.Date.ToString("yyyy-MM-dd", new CultureInfo("en-US"))); Sell.SetValue("EXCH_RATE", cur.Sell_SAP.ToString("0.#####")); if (currencyRatioDict.ContainsKey(cur.Currency)) { Sell.SetValue("FROM_FACTOR", currencyRatioDict[cur.Currency]); } else { Sell.SetValue("FROM_FACTOR", 1); } Sell.SetValue("TO_FACTOR", 1); log.Debug(String.Format("{0} {1} {2} {3} {4}", "M", cur.Currency, "THB", dailyLog.Date.ToString("ddMMyyyy", new CultureInfo("en-US")), cur.Sell_SAP.ToString("0.#####"))); sentSAP.Add(cur); } } var count = table.Count; #endregion if (count > 0) { try { function.Invoke(des); sentSAP.ForEach(x => { x.isSyncSAP = true; }); } catch (SAP.Middleware.Connector.RfcAbapClassicException ex) { if (ex.Key == "SAPSQL_ARRAY_INSERT_DUPREC") { //dublicate record found log.Debug("-----------------------------------------------------------------"); log.Debug("SAP BAPI CALL Error : DUBLICATED RECORD FOUND IN SAP."); log.Debug("-----------------------------------------------------------------"); } ExceptionHandling.LogException(ex); } catch (Exception ex) { isSAPCompleted = false; SAPErrorMsg += Environment.NewLine + ex.Message; log.Debug("-----------------------------------------------------------------"); log.Debug("SAP BAPI CALL Error : READ THE EXCEPTION DETAIL."); log.Debug("-----------------------------------------------------------------"); ExceptionHandling.LogException(ex); } } //Call bapi #region example for fetch structure as object /* * IRfcParameter export = function["PRHEADER"]; * IRfcStructure structure = export.GetStructure(); * var setting = new PropertiesList<DataContainer> * { * { "PREQ_NO", x=>x.PREQ_NO}, * { "PREQ_NO", x=>x.PREQ_NO}, * { "PR_TYPE", x=>x.PR_TYPE}, * { "CTRL_IND", x=>x.CTRL_IND}, * }; * DataContainer output = structure.ToObject(setting);*/ #endregion IRfcParameter returnTable = function["I_EXCHANGE"]; IRfcTable table1 = returnTable.GetTable(); //foreach (IRfcStructure record in table1) //{ // Console.WriteLine(String.Format("{0}:{1}", record.GetInt("PREQ_ITEM"), record.GetValue("PREQ_ITEM").ToString())); //} if (!db.SaveChange()) { log.Debug("-----------------------------------------------------------------"); log.Debug("Log Update Error"); log.Debug("-----------------------------------------------------------------"); } else { log.Debug("-----------------------------------------------------------------"); log.Debug("Log Update Successful"); log.Debug("-----------------------------------------------------------------"); } } catch (Exception ex) { isSAPCompleted = false; SAPErrorMsg += Environment.NewLine + ex.Message; log.Debug("-----------------------------------------------------------------"); log.Debug("SAP PART Error : READ THE EXCEPTION DETAIL."); log.Debug("-----------------------------------------------------------------"); ExceptionHandling.LogException(ex); } #endregion #region AlertMsg try { if (!Appconfig.RecoveryMode && db.GetOrCreateDailyLog(runningDate).CurrenciesRate.Any(x => Appconfig.SyncCurrency.Contains(x.Currency) && x.isSyncSAP == false && x.Sell != (decimal)0 && x.Buy != (decimal)0) && programDatetime.Date.AddDays(-1) == runningDate.Date && programDatetime.Hour < Appconfig.BOTHourUpdate && programDatetime.Hour > Appconfig.AlertCutOffTime) { //recovery mode is off //there is some sync currency which cannot sent to SAP found and it is not dayoff (sell && buy !=0) //program is running on not today for sure (not after 18.00 of the day) (not before 7.00 of the program date) MailService mailService = new MailService(Appconfig.MailServer, Appconfig.MailServerPort); //send email to user Email userMail = new Email(); userMail.Cc = Appconfig.AlertAdminEmail; userMail.From = Appconfig.MailAdminAddress; userMail.To = Appconfig.AlertUserEmail; userMail.Subject = @"[BOTExchangeRate] ERROR UPDATE TO SAP NOTIFICATION"; userMail.SenderName = @"BOTExchange Automatic Email Alert"; userMail.BodyMessage = MailTemplateUser(runningDate, Appconfig.SyncCurrency); mailService.SendMail(userMail); //send email to admin if exception found if (!isSAPCompleted) { Email adminMail = new Email(); adminMail.From = Appconfig.MailAdminAddress; adminMail.To = Appconfig.AlertAdminEmail; adminMail.Subject = @"[BOTExchangeRate] ERROR UPDATE TO SAP NOTIFICATION [DEBUG]"; adminMail.SenderName = @"BOTExchange Automatic Email Alert"; adminMail.BodyMessage = MailTemplateAdmin(runningDate, Appconfig.SyncCurrency, SAPErrorMsg); mailService.SendMail(adminMail); } } } catch (Exception ex) { log.Debug("-----------------------------------------------------------------"); log.Debug("EMAIL ALERT ERROR"); log.Debug("-----------------------------------------------------------------"); ExceptionHandling.LogException(ex); } #endregion log.Debug("*******************************************************************"); log.Debug("PROGRAM RUNS COMPLETED " + programDatetime.ToString("dd/MM/yyyy HH:mm:ss")); log.Debug("*******************************************************************"); }
/// <summary> /// Devuelve el numero de Meters distintos en una unica fila /// </summary> /// <param name="row"></param> /// <returns></returns> private static int getNumberOfCountersInThisRow(IRfcStructure row) { int result = 0; if (((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT1_ID)).Trim() != string.Empty) result++; if (((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT2_ID)).Trim() != string.Empty) result++; return result; }
/// <summary> /// Transforma a 1 o 2 Meters (ver caso OLMFW01) una fila de la tabla de resultados /// </summary> /// <param name="row"></param> /// <returns></returns> private static IEnumerable<Meter> getRowMeterList(IRfcStructure row) { IList<Meter> result = new List<Meter>(); int numberOfCounters = getNumberOfCountersInThisRow(row); if (numberOfCounters == 0) return result; double num = (double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT1_POWER))); double den=double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_POWER)); DateTime startDate = DateTime.ParseExact((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_START_DATE), FORMAT_DATE_SAP, new CultureInfo("es-ES", true)); DateTime endDate = DateTime.ParseExact((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_END_DATE), FORMAT_DATE_SAP, new CultureInfo("es-ES", true)); Meter firstMeter = new Meter() { //IdMeter = (string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT1_ID), //IdPlant = (string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_UF), //LosingRate = double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT1_PERD)), //Power = (double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_POWER)) / numberOfCounters), //PowerPercentage = (double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_POWER)) // / double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT1_POWER))) IdMeter = (string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT1_ID), IdPlant = (string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_UF), startDate=DateTime.ParseExact((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_START_DATE), FORMAT_DATE_SAP, new CultureInfo("es-ES", true)), endDate=DateTime.ParseExact((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_END_DATE), FORMAT_DATE_SAP, new CultureInfo("es-ES", true)), LosingRate = double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT1_PERD)), Power = (double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT1_POWER))), PowerPercentage = (double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT1_POWER)) / double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_POWER))) }; result.Add(firstMeter); if (numberOfCounters == 1) return result; Meter secondMeter = new Meter() { //IdMeter = (string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT2_ID), //IdPlant = (string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_UF), //LosingRate = double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT2_PERD)), //Power = (double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_POWER)) / numberOfCounters), //PowerPercentage = (double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_POWER)) // / double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT1_POWER))) IdMeter = (string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT2_ID), IdPlant = (string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_UF), startDate = DateTime.ParseExact((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_START_DATE), FORMAT_DATE_SAP, new CultureInfo("es-ES", true)), endDate = DateTime.ParseExact((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_END_DATE), FORMAT_DATE_SAP, new CultureInfo("es-ES", true)), LosingRate = double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT2_PERD)), Power = (double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT1_POWER)) / numberOfCounters), PowerPercentage = (double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_CONT1_POWER)) / double.Parse((string)row.GetValue(RFC_FUNCTION_RETURN_TABLE_FIELD_POWER))) }; result.Add(secondMeter); return result; }
public static IRfcTable SAPExecuteTableData2(Hashtable[] arrht, Hashtable[] arrht2, Hashtable ImportData, string Function_Name, string RfcStructure_Name, string RfcStructure_Name2, string GetTable_Name, string SetTable_Name, string SetTable_Name2) { RfcConfigParameters configParam = GetConfigParam(); RfcDestination destination = RfcDestinationManager.GetDestination(configParam); IRfcFunction function = destination.Repository.CreateFunction(Function_Name); IRfcTable rfcTable = function.GetTable(SetTable_Name); IRfcTable rfcTable2 = function.GetTable(SetTable_Name2); for (int i = 0; i < arrht.Length; i++) { RfcStructureMetadata strMeta = destination.Repository.GetStructureMetadata(RfcStructure_Name); IRfcStructure rfcStructure = strMeta.CreateStructure(); if (arrht[i] == null) { continue; } IDictionaryEnumerator ie = arrht[i].GetEnumerator(); while (ie.MoveNext()) { if (ie.Value.ToString().Length <= 4000) { rfcStructure.SetValue(ie.Key.ToString(), ie.Value); } } rfcTable.Append(rfcStructure); } for (int i = 0; i < arrht2.Length; i++) { RfcStructureMetadata strMeta = destination.Repository.GetStructureMetadata(RfcStructure_Name2); IRfcStructure rfcStructure = strMeta.CreateStructure(); if (arrht2[i] == null) { continue; } IDictionaryEnumerator ie = arrht2[i].GetEnumerator(); while (ie.MoveNext()) { if (ie.Value.ToString().Length <= 4000) { rfcStructure.SetValue(ie.Key.ToString(), ie.Value); } } rfcTable2.Append(rfcStructure); } if (ImportData.Count > 0) { IDictionaryEnumerator ie = ImportData.GetEnumerator(); while (ie.MoveNext()) { if (ie.Value.ToString().Length <= 4000) { function.SetValue(ie.Key.ToString(), ie.Value); } } } function.Invoke(destination); IRfcTable rfcTable3 = function.GetTable(GetTable_Name); return(rfcTable3); }
public bool InstallAndRun() { IRfcFunction function = null; this._result.Clear(); try { if (this._des == null) { throw new SAPException(Messages.Connectionisnotvalid); } this._LastError = ""; if (!String.IsNullOrEmpty(CustomFunction)) { function = _des.Repository.CreateFunction(CustomFunction); } else { bool hasFunction = SAPFunction.CheckFunction(_sysName, "ZVI_RFC_ABAP_INSTALL_AND_RUN"); if (hasFunction) { function = _des.Repository.CreateFunction("ZVI_RFC_ABAP_INSTALL_AND_RUN"); } //else //{ // hasFunction = SAPFunction.CheckFunction(_sysName, "RFC_ABAP_INSTALL_AND_RUN"); // if (hasFunction) // { // function = _des.Repository.CreateFunction("RFC_ABAP_INSTALL_AND_RUN"); // } //} } if (function == null) { throw new SAPException("无法找到运行程序"); } IRfcTable table = function.GetTable("PROGRAM"); if (this._code.Count <= 1) { throw new Exception(Messages.Thegivencodeisnotvalid); } foreach (string str in this._code) { table.Append(); IRfcStructure row = table.CurrentRow; row.SetValue("ZEILE", str); } function.Invoke(_des); } catch (RfcCommunicationException e) { throw new SAPException(e.Message); } catch (RfcAbapException e) { throw new SAPException(e.Key + e.Message); } this._LastError = function.GetString("ERRORMESSAGE"); if (this._LastError != "") { return(false); } IRfcTable table2 = function.GetTable("WRITES"); for (int i = 0; i < table2.RowCount; i++) { this._result.Add(table2[i].GetString("ZEILE")); } return(true); }
/// <summary> /// Func原始格式,包含所有參數 /// </summary> /// <param name="MATERIAL"></param> /// <param name="PLANT"></param> /// <param name="MPR_AREA"></param> /// <param name="PLAN_SCENARIO"></param> /// <param name="SELECTION_RULE"></param> /// <param name="DISPLAY_FILTER"></param> /// <param name="MATERIAL_EVG_MATERIAL_EXT"></param> /// <param name="MATERIAL_EVG_MATERIAL_VERS"></param> /// <param name="MATERIAL_EVG_MATERIAL_GUID"></param> /// <param name="PERIOD_INDICATOR"></param> /// <param name="IGNORE_BUFFER"></param> /// <param name="GET_ITEM_DETAILS"></param> /// <param name="GET_TOTAL_LINES"></param> /// <param name="GET_IND_LINES"></param> /// <returns>DataSet</returns> public DataSet Send( string MATERIAL, string PLANT, string MRP_AREA, string PLAN_SCENARIO, string SELECTION_RULE, string DISPLAY_FILTER, string MATERIAL_EVG_MATERIAL_EXT, string MATERIAL_EVG_MATERIAL_VERS, string MATERIAL_EVG_MATERIAL_GUID, bool PERIOD_INDICATOR, bool GET_ITEM_DETAILS, bool GET_IND_LINES, bool GET_TOTAL_LINES, bool IGNORE_BUFFER) { DataSet ds = new DataSet(); IRfcFunction rfcFunction = GetRfcFunction(FunName); #region Import parameters const string flagX = "X"; rfcFunction.SetValue("MATERIAL", MaterialProcess(MATERIAL)); rfcFunction.SetValue("PLANT", PLANT); rfcFunction.SetValue("MRP_AREA", MRP_AREA); rfcFunction.SetValue("PLAN_SCENARIO", PLAN_SCENARIO); rfcFunction.SetValue("SELECTION_RULE", SELECTION_RULE); rfcFunction.SetValue("DISPLAY_FILTER", DISPLAY_FILTER); rfcFunction.SetValue("PERIOD_INDICATOR", PERIOD_INDICATOR ? flagX : string.Empty); rfcFunction.SetValue("GET_ITEM_DETAILS", GET_ITEM_DETAILS ? flagX : string.Empty); rfcFunction.SetValue("GET_IND_LINES", GET_IND_LINES ? flagX : string.Empty); rfcFunction.SetValue("GET_TOTAL_LINES", GET_TOTAL_LINES ? flagX : string.Empty); rfcFunction.SetValue("IGNORE_BUFFER", IGNORE_BUFFER ? flagX : string.Empty); IRfcStructure MATERIAL_EVG = rfcFunction.GetStructure("MATERIAL_EVG"); MATERIAL_EVG.SetValue("MATERIAL_EXT", MATERIAL_EVG_MATERIAL_EXT); MATERIAL_EVG.SetValue("MATERIAL_VERS", MATERIAL_EVG_MATERIAL_VERS); MATERIAL_EVG.SetValue("MATERIAL_GUID", MATERIAL_EVG_MATERIAL_GUID); #endregion rfcFunction.Invoke(Destination); #region Export parpmeters #region MRP_LIST { string tableName = "MRP_LIST"; IRfcFunction iRfcFunction = rfcFunction; DataSet dataSet = ds; DataTable dataTable = GetFunctionStructureToDataTable(ref iRfcFunction, tableName); dataSet.Tables.Add(dataTable); } #endregion #region MRP_CONTROL_PARAM { string tableName = "MRP_CONTROL_PARAM"; IRfcFunction iRfcFunction = rfcFunction; DataSet dataSet = ds; DataTable dataTable = GetFunctionStructureToDataTable(ref iRfcFunction, tableName); dataSet.Tables.Add(dataTable); } #endregion #region MRP_STOCK_DETAIL { string tableName = "MRP_STOCK_DETAIL"; IRfcFunction iRfcFunction = rfcFunction; DataSet dataSet = ds; DataTable dataTable = GetFunctionStructureToDataTable(ref iRfcFunction, tableName); dataSet.Tables.Add(dataTable); } #endregion #region RETURN { string tableName = "RETURN"; IRfcFunction iRfcFunction = rfcFunction; DataSet dataSet = ds; DataTable dataTable = GetFunctionStructureToDataTable(ref iRfcFunction, tableName); dataSet.Tables.Add(dataTable); } #endregion #endregion #region Tables #region MRP_ITEMS { string tableName = MRP_ITEMS; IRfcFunction iRfcFunction = rfcFunction; DataSet dataSet = ds; DataTable dataTable = GetFunctionTableToDataTable(ref iRfcFunction, tableName); dataSet.Tables.Add(dataTable); } #endregion #region MRP_IND_LINES { string tableName = MRP_IND_LINES; IRfcFunction iRfcFunction = rfcFunction; DataSet dataSet = ds; DataTable dataTable = GetFunctionTableToDataTable(ref iRfcFunction, tableName); dataSet.Tables.Add(dataTable); } #endregion #region MRP_TOTAL_LINES { string tableName = "MRP_TOTAL_LINES"; IRfcFunction iRfcFunction = rfcFunction; DataSet dataSet = ds; DataTable dataTable = GetFunctionTableToDataTable(ref iRfcFunction, tableName); dataSet.Tables.Add(dataTable); } #endregion #region EXTENSIONOUT { string tableName = "EXTENSIONOUT"; IRfcFunction iRfcFunction = rfcFunction; DataSet dataSet = ds; DataTable dataTable = GetFunctionTableToDataTable(ref iRfcFunction, tableName); dataSet.Tables.Add(dataTable); } #endregion #endregion return(ds); }
public bool getSapFunctionToTablePara(string funName, Dictionary <string, string> lstParameters, Dictionary <string, Dictionary <string, object> > lstStructures , IRfcTable rtbIput, string tableindex , List <string> ParameterNamesForOut, out Dictionary <string, string> ParametersOutput , List <string> StructureNamesForOut, out Dictionary <string, IRfcStructure> StructureOutputs , List <string> tableNamesForOut, out Dictionary <string, IRfcTable> rtbsOutput, ref string strErrMsg) { try { RfcRepository repo = rfcrep; IRfcFunction Z_RFC_ZCOX = repo.CreateFunction(funName); RfcSessionManager.BeginContext(dest); if (lstParameters != null && lstParameters.Count > 0) { foreach (KeyValuePair <string, string> item in lstParameters) { Z_RFC_ZCOX.SetValue(item.Key, item.Value); } } if (lstStructures != null && lstStructures.Count > 0) { foreach (string item in lstStructures.Keys) { IRfcStructure _stru = Z_RFC_ZCOX.GetStructure(item); foreach (KeyValuePair <string, object> _kv in lstStructures[item]) { _stru.SetValue(_kv.Key, _kv.Value); } } } if (rtbIput != null) { Z_RFC_ZCOX.SetValue(tableindex, rtbIput); } Z_RFC_ZCOX.Invoke(dest); RfcSessionManager.EndContext(dest); //取出返回的表 if (tableNamesForOut != null && tableNamesForOut.Count > 0) { rtbsOutput = new Dictionary <string, IRfcTable>(); foreach (string item in tableNamesForOut) { IRfcTable rtb = Z_RFC_ZCOX.GetTable(item); rtbsOutput.Add(item, rtb); } } else { rtbsOutput = null; } //取出返回参数 if (ParameterNamesForOut != null && ParameterNamesForOut.Count > 0) { ParametersOutput = new Dictionary <string, string>(); foreach (string item in ParameterNamesForOut) { string retPara = Z_RFC_ZCOX.GetString(item); ParametersOutput.Add(item, retPara); } } else { ParametersOutput = null; } //取出返回的结构 if (StructureNamesForOut != null && StructureNamesForOut.Count > 0) { StructureOutputs = new Dictionary <string, IRfcStructure>(); foreach (string item in StructureNamesForOut) { IRfcStructure retStru = Z_RFC_ZCOX.GetStructure(item); StructureOutputs.Add(item, retStru); } } else { StructureOutputs = null; } char statue = Z_RFC_ZCOX.GetChar("EX_TYPE"); if ("E".Contains(statue)) { strErrMsg = Z_RFC_ZCOX.GetString("EX_MSG"); } return("S".Contains(statue)); } catch (RfcAbapRuntimeException ex) { ParametersOutput = null; rtbsOutput = null; StructureOutputs = null; throw ex; } }
public List <string> WHS_MOVE_Z_RFC_AUFNR_MIGO(Z_RFC_AUFNR_MIGO RFCAufnrMigo, string TestFlag) { List <string> LsMsg = new List <string>(); try { #region GM_CODE是和SAP的T-code相关 /*01 MB01 * 02 MB31 * 03 MB1A * 04 MB1B * 05 MB1C * 06 MB11*/ #endregion RfcDestination destination = RfcDestinationManager.GetDestination(this.GetCfgParameters()); IRfcFunction rfcFunction = destination.Repository.CreateFunction("Z_RFC_AUFNR_MIGO"); IRfcStructure IS_HEAD = rfcFunction.GetStructure("IS_HEAD"); IS_HEAD.SetValue("GM_CODE", "04"); IS_HEAD.SetValue("PSTNG_DATE", string.IsNullOrEmpty(RFCAufnrMigo.PSTNG_DATE) ? DateTime.Now.ToString("yyyyMMdd") : RFCAufnrMigo.PSTNG_DATE); IS_HEAD.SetValue("DOC_DATE", string.IsNullOrEmpty(RFCAufnrMigo.DOC_DATE) ? DateTime.Now.ToString("yyyyMMdd") : RFCAufnrMigo.DOC_DATE); IS_HEAD.SetValue("HEADER_TXT", RFCAufnrMigo.EMP_NO + RFCAufnrMigo.EMP_NAME); //人员权限 rfcFunction.SetValue("IS_HEAD", IS_HEAD); //设置参数 IRfcStructure IS_ITEM = rfcFunction.GetStructure("IS_ITEM"); IS_ITEM.SetValue("MATERIAL", RFCAufnrMigo.PartNumber); IS_ITEM.SetValue("PLANT", "2100"); IS_ITEM.SetValue("STGE_LOC", RFCAufnrMigo.STGE_LOC); //转出仓 IS_ITEM.SetValue("MOVE_TYPE", "311"); //仓库之间转移 IS_ITEM.SetValue("ENTRY_QNT", RFCAufnrMigo.QTY); IS_ITEM.SetValue("MOVE_PLANT", "2100"); IS_ITEM.SetValue("MOVE_STLOC", RFCAufnrMigo.MOVE_STLOC); rfcFunction.SetValue("IS_ITEM", IS_ITEM); //设置参数 rfcFunction.SetValue("I_TYPE", "3"); //1成品入库 2出库 03 移库 if (!string.IsNullOrEmpty(TestFlag)) { rfcFunction.SetValue("TESTRUN", "X"); //检查入库,不过账 } rfcFunction.Invoke(destination); string SAP_STOCKNO = rfcFunction.GetValue("E_MBLNR").ToString().TrimStart('0'); //物料凭证号码 IRfcStructure ES_RETURN = rfcFunction.GetStructure("ES_RETURN"); string SAP_TYPE = ES_RETURN.GetValue("TYPE").ToString(); //是否成功 S 表示成功 string SAP_E_ID = ES_RETURN.GetValue("ID").ToString(); string SAP_E_NUM = ES_RETURN.GetValue("NUMBER").ToString(); string SAP_MSG = ES_RETURN.GetValue("MESSAGE").ToString(); LsMsg.Add(SAP_STOCKNO); LsMsg.Add(SAP_TYPE); LsMsg.Add(SAP_E_ID); LsMsg.Add(SAP_E_NUM); LsMsg.Add(SAP_MSG); return(LsMsg); } catch (Exception ex) { LsMsg.Add(ex.Message); return(LsMsg); } }
public bool PostSapFunctionFromListTable(string funName, Dictionary <string, string> lstParameters , Dictionary <string, Dictionary <string, object> > lstStructures , ref Dictionary <string, string> ParametersOutputs , ref Dictionary <string, IRfcStructure> StructureOutputs , ref Dictionary <string, IRfcTable> rtbsOutputs , Dictionary <string, IRfcTable> lstTable, ref string strErrMsg) { try { RfcRepository repo = rfcrep; IRfcFunction Z_RFC_ZCOX = repo.CreateFunction(funName); RfcSessionManager.BeginContext(dest); if (lstParameters != null && lstParameters.Count > 0) { foreach (KeyValuePair <string, string> item in lstParameters) { Z_RFC_ZCOX.SetValue(item.Key, item.Value); } } if (lstStructures != null && lstStructures.Count > 0) { foreach (string item in lstStructures.Keys) { IRfcStructure _stru = Z_RFC_ZCOX.GetStructure(item); foreach (KeyValuePair <string, object> _kv in lstStructures[item]) { _stru.SetValue(_kv.Key, _kv.Value); } } } if (lstTable != null && lstTable.Count > 0) { foreach (KeyValuePair <string, IRfcTable> item in lstTable) { Z_RFC_ZCOX.SetValue(item.Key, item.Value); } } //if (rfcTable != null && rfcTable.Count > 0) //{ // Z_RFC_ZCOX.SetValue(rfcTableName, rfcTable); //} Z_RFC_ZCOX.Invoke(dest); RfcSessionManager.EndContext(dest); //取出返回的表 if (rtbsOutputs != null && rtbsOutputs.Count > 0) { for (int i = 0; i < rtbsOutputs.Count; i++) { var _item = rtbsOutputs.ElementAt(i); IRfcTable rtb = Z_RFC_ZCOX.GetTable(_item.Key); rtbsOutputs[_item.Key] = rtb; } } else { rtbsOutputs = null; } //取出返回的结构 if (StructureOutputs != null && StructureOutputs.Count > 0) { for (int i = 0; i < StructureOutputs.Count; i++) { var _item = StructureOutputs.ElementAt(i); IRfcStructure retStru = Z_RFC_ZCOX.GetStructure(_item.Key); StructureOutputs[_item.Key] = retStru; } } else { StructureOutputs = null; } return(CreateReturn(rtbsOutputs["RETURN"], ref strErrMsg)); } catch (RfcAbapRuntimeException ex) { throw ex; } }
public WWPOComponentResult GetWWPOList(List <WWPOComponentPara> list) { try { NcoFunction ncoClient = new NcoFunction(); string[] rfcArray = ConfigHelper.LoadRFCConfig(ConfigHelper.strDestinationName); ncoClient.Connect(rfcArray[0], "", rfcArray[3], rfcArray[4], "ZH", rfcArray[5], rfcArray[8], 2, 10, "", rfcArray[9]); ncoClient.FunctionName = MES2SAPRfcFunctionName.WWPOComponent; Dictionary <string, object> importParameters = new Dictionary <string, object>(); DataTable dt = new DataTable(); dt.Columns.Add("EBELN", typeof(string)); dt.Columns.Add("EBELP", typeof(int)); foreach (var item in list) { DataRow row = dt.NewRow(); row["EBELN"] = item.PONO; //row["EBELP"] = item.POLine; dt.Rows.Add(row); } IRfcTable rfcTable = ncoClient.ConvertDataTabletoRFCTable(dt, MES2SAPRfcInTableName.WWPOComponent); importParameters.Add(MES2SAPRfcInTableName.WWPOComponent, rfcTable); ncoClient.ImportParameters = importParameters; Dictionary <string, object> exportParameters = new Dictionary <string, object>(); DataSet ds = ncoClient.Execute(ref exportParameters); WWPOComponentResult result = new WWPOComponentResult(); List <WWPOComponent> componentList = new List <WWPOComponent>(); if (ds != null && ds.Tables[MES2SAPRfcOutTableName.WWPOComponent] != null && ds.Tables[MES2SAPRfcOutTableName.WWPOComponent].Rows.Count > 0) { foreach (DataRow row in ds.Tables[MES2SAPRfcOutTableName.WWPOComponent].Rows) { WWPOComponent co = new WWPOComponent(); co.PONO = Convert.ToString(row["EBELN"]); co.POLine = Convert.ToInt32(row["EBELP"]); co.SubLine = Convert.ToInt32(row["RSPOS"]); co.MCode = Convert.ToString(row["MATNR"]); co.HWMCode = Convert.ToString(row["IDNLF"]); co.Qty = Convert.ToDecimal(row["BDMNG"]); co.Unit = Convert.ToString(row["MEINS"]); componentList.Add(co); } } result.WWPOComponentList = componentList; object parameter = null; SAPRfcReturn re = new SAPRfcReturn(); if (exportParameters != null) { if (exportParameters.TryGetValue("ES_RESULT", out parameter)) { IRfcStructure ROFStrcture = parameter as IRfcStructure; re.Result = ROFStrcture["RETUN"].GetValue().ToString(); re.MaterialDocument = null; re.Message = ROFStrcture["MESSG"].GetValue().ToString(); } } result.RfcResult = re; return(result); } catch (Exception ex) { throw ex; } }
public void SetValue(IRfcStructure structure) { this.Itemno_Acc = structure.GetInt("ITEMNO_ACC").ToString(); this.Fieldname = structure.GetString("FIELDNAME"); this.Character = structure.GetString("CHARACTER"); }
//public DataTable GetDataTableFromRFCTable(IRfcTable lrfcTable) //{ // //sapnco_util // DataTable loTable = new DataTable(); // //... Create ADO.Net table. // for (int liElement = 0; liElement < lrfcTable.ElementCount; liElement++) // { // RfcElementMetadata metadata = lrfcTable.GetElementMetadata(liElement); // loTable.Columns.Add(metadata.Name); // } // //... Transfer rows from lrfcTable to ADO.Net table. // foreach (IRfcStructure row in lrfcTable) // { // DataRow ldr = loTable.NewRow(); // for (int liElement = 0; liElement < lrfcTable.ElementCount; liElement++) // { // RfcElementMetadata metadata = lrfcTable.GetElementMetadata(liElement); // ldr[metadata.Name] = row.GetString(metadata.Name); // } // loTable.Rows.Add(ldr); // } // return loTable; //} public DataTable RfcStructureToDataTable(IRfcStructure myrefcTable) { DataTable rowTable = new DataTable(); for (int i = 0; i <= myrefcTable.ElementCount - 1; i++) { rowTable.Columns.Add(myrefcTable.GetElementMetadata(i).Name); } DataRow row = rowTable.NewRow(); for (int j = 0; j <= myrefcTable.ElementCount - 1; j++) { row[j] = myrefcTable.GetValue(j); } rowTable.Rows.Add(row); return rowTable; }
public static void CreateMaterial(Item materialPart, Item logItem) { IRfcFunction material = destination.Repository.CreateFunction("BAPI_MATERIAL_SAVEDATA"); IRfcStructure headDataStructure = material.GetStructure("HEADDATA"); string sapMaterialType = materialPart.getProperty("gag_sap_material_type"); string materialNumber = materialPart.getProperty("item_number"); string revision = materialPart.getProperty("major_rev"); string materialNum = materialNumber + "-" + revision; string standardDesignation = materialPart.getProperty("gag_standard_designation"); string dimensionStandard = materialPart.getProperty("gag_dimension_standard"); string basicMaterial = materialPart.getProperty("gag_material"); string gagtheoreticalWeight = materialPart.getProperty("gag_theoretical_weight"); string gagmeasuredWeight = materialPart.getProperty("gag_measured_weight"); decimal theoreticalWeight; if (string.IsNullOrEmpty(gagtheoreticalWeight)) { theoreticalWeight = 0; } else { theoreticalWeight = decimal.Parse(gagtheoreticalWeight); } decimal measuredWeight; if (string.IsNullOrEmpty(gagmeasuredWeight)) { measuredWeight = 0; } else { measuredWeight = decimal.Parse(gagmeasuredWeight); } string sapUOM = ""; string sapUOMX = ""; string arasUOM = materialPart.getProperty("gag_sap_unit_of_measure"); if (arasUOM == "Pc") { sapUOM = "ST"; sapUOMX = "PCE"; } else if (arasUOM == "kg") { sapUOM = "KG"; sapUOMX = "KGM"; } else if (arasUOM == "m2") { sapUOM = "M2"; sapUOMX = "MTK"; } else if (arasUOM == "lm") { sapUOM = "LM"; sapUOMX = "MTR"; } else if (arasUOM == "m") { sapUOM = "M"; sapUOMX = "MTR"; } decimal weight = (measuredWeight != 0) ? measuredWeight : theoreticalWeight; headDataStructure.SetValue("material", materialNum); headDataStructure.SetValue("ind_sector", "M"); headDataStructure.SetValue("matl_type", sapMaterialType); headDataStructure = material.GetStructure("CLIENTDATA"); headDataStructure.SetValue("base_uom", sapUOM); headDataStructure.SetValue("base_uom_iso", sapUOMX); headDataStructure.SetValue("NET_WEIGHT", weight); headDataStructure.SetValue("UNIT_OF_WT_ISO", "KGM"); headDataStructure.SetValue("UNIT_OF_WT", "KG"); headDataStructure.SetValue("CAD_ID", "X"); headDataStructure.SetValue("STD_DESCR", standardDesignation); headDataStructure.SetValue("SIZE_DIM", dimensionStandard); headDataStructure.SetValue("BASIC_MATL", basicMaterial); headDataStructure = material.GetStructure("CLIENTDATAX"); headDataStructure.SetValue("base_uom", "X"); headDataStructure.SetValue("base_uom_iso", "X"); headDataStructure.SetValue("NET_WEIGHT", "X"); headDataStructure.SetValue("UNIT_OF_WT_ISO", "X"); headDataStructure.SetValue("UNIT_OF_WT", "X"); headDataStructure.SetValue("CAD_ID", "X"); headDataStructure.SetValue("STD_DESCR", "X"); headDataStructure.SetValue("SIZE_DIM", "X"); headDataStructure.SetValue("BASIC_MATL", "X"); IRfcTable materialdescription = material.GetTable("MATERIALDESCRIPTION"); string englishDescription = materialPart.getProperty("name"); string germanDescription = materialPart.getProperty("gag_name_ge"); string italianDescription = materialPart.getProperty("gag_name_it"); string frenchDescription = materialPart.getProperty("gag_name_fr"); string portugueseDescription = materialPart.getProperty("gag_name_pt"); string turkishDescription = materialPart.getProperty("gag_name_tr"); string spanishDescription = materialPart.getProperty("gag_name_es"); IDictionary <string, string> descriptions = new Dictionary <string, string> { { "EN", englishDescription }, { "DE", germanDescription }, { "IT", italianDescription }, { "FR", frenchDescription }, { "S", spanishDescription }, { "PT", portugueseDescription }, { "TR", turkishDescription }, }; foreach (KeyValuePair <string, string> description in descriptions) { if (!string.IsNullOrEmpty(description.Value)) { materialdescription.Append(); materialdescription.SetValue("LANGU", description.Key); materialdescription.SetValue("MATL_DESC", description.Value); } } material.Invoke(destination); IRfcStructure returnMessage = material.GetStructure("RETURN"); string messageOutput = returnMessage.GetString("MESSAGE"); IRfcFunction materialCommitFunction = destination.Repository.CreateFunction("BAPI_TRANSACTION_COMMIT"); materialCommitFunction.Invoke(destination); if (messageOutput.Contains("created")) { CreateBOM(materialPart, logItem); } else { FillLogItem(logItem, $"Material NOT Created. {messageOutput}", "Failed"); } connection.Logout(); }
protected DataTable GetFunctionStructureToDataTable(ref IRfcFunction iRfcFunction, string name) { IRfcStructure iRfcStructure = iRfcFunction.GetStructure(name); return(RfcStructureToDataTable(iRfcStructure, name)); }
public static void CreateBOM(Item materialPart, Item logItem) { materialPart.fetchRelationships("Part BOM"); Item relationships = materialPart.getRelationships("Part BOM"); if (relationships.getItemCount() > 0) { string bomMaterialStatus = CheckMaterialsInBOM(materialPart); if (bomMaterialStatus == "Success") { string changeNumber = materialPart.getProperty("gag_change_num"); string materialNumber = materialPart.getProperty("item_number") + "-" + materialPart.getProperty("major_rev"); int count = relationships.getItemCount(); IRfcFunction CreateBOMBapi = destination.Repository.CreateFunction("CSAP_MAT_BOM_CREATE"); CreateBOMBapi.SetValue("MATERIAL", materialNumber); CreateBOMBapi.SetValue("BOM_USAGE", "2"); CreateBOMBapi.SetValue("CHANGE_NO", changeNumber); CreateBOMBapi.SetValue("FL_COMMIT_AND_WAIT", "X"); CreateBOMBapi.SetValue("FL_DEFAULT_VALUES", "X"); IRfcStructure headDataStruct = CreateBOMBapi.GetStructure("I_STKO"); headDataStruct.SetValue("BASE_QUAN", "1"); headDataStruct.SetValue("BOM_STATUS", "2"); headDataStruct.SetValue("BASE_UNIT", "PC"); for (int i = 0; i < count; i++) { Item partRelationship = relationships.getItemByIndex(i); Item part = partRelationship.getRelatedItem(); string partNo = part.getProperty("item_number"); string partRevision = part.getProperty("major_rev"); string partNumber = partNo + "-" + partRevision; string quantity = partRelationship.getProperty("quantity"); IRfcTable BOMItems = CreateBOMBapi.GetTable("T_STPO"); BOMItems.Append(); BOMItems.SetValue("ITEM_CATEG", "L"); BOMItems.SetValue("ITEM_NO", "00" + (i + 1) * 10); BOMItems.SetValue("COMPONENT", partNumber); BOMItems.SetValue("COMP_QTY", quantity); } CreateBOMBapi.Invoke(destination); string msgOutput = CreateBOMBapi.GetString("BOM_NO"); IRfcFunction rfcCommitFunction = destination.Repository.CreateFunction("BAPI_TRANSACTION_COMMIT"); rfcCommitFunction.Invoke(destination); if (string.IsNullOrEmpty(msgOutput)) { FillLogItem(logItem, "BOM not Created", "Failed"); } else { FillLogItem(logItem, string.Empty, "Completed"); } } else { FillLogItem(logItem, "Component Material does not exist in SAP", "Failed"); } } else { FillLogItem(logItem, string.Empty, "Completed"); } }
public string SAVE_MAIL_DATA(MAIL_DATA_BE mail_data, List <Attachment_BE> attachs, List <Relacionados> relacionados, SharedSettings.Settings settings) { byte[] pdf; try { //Establecemos conexion con SAP RfcConfigParameters rfc = SAP_Connection.GetParameters(settings); RfcDestination rfcDest = null; rfcDest = RfcDestinationManager.GetDestination(rfc); //Creamos repositorio para la función RfcRepository repo = rfcDest.Repository; IRfcFunction save_mail = repo.CreateFunction("Z_MAIL_SAVE"); IRfcStructure p_maildata = save_mail.GetStructure("P_MAILDATA"); IRfcTable p_attachments = save_mail.GetTable("P_ATTACHMENTS"); IRfcTable p_relacionados = save_mail.GetTable("P_RELACIONADOS"); get_maildata_sapstr(mail_data, ref p_maildata); get_mailattach_saptab(attachs, ref p_attachments); get_relacionados_saptab(relacionados, ref p_relacionados); //Ejecutamos la consulta save_mail.Invoke(rfcDest); pdf = save_mail.GetByteArray("FILEPDFGEN"); IRfcStructure bapiret = save_mail.GetStructure("BAPIRET"); //string res = save_mail.GetString("MSG"); //Revisamos que la consulta haya sido exitosa if (pdf.Length > 0 && String.IsNullOrEmpty(attachs[0].PATHFILEPDF) == false) { if (System.IO.File.Exists(attachs[0].PATHFILEPDF) == false) { System.IO.File.WriteAllBytes(attachs[0].PATHFILEPDF, pdf); } } if (bapiret.GetString("TYPE") == "E") { string mensajeError = bapiret.GetString("MESSAGE"); return(mensajeError); //Hubo un error } else { return(""); //Guardado exitoso } } catch (RfcCommunicationException e) { throw e; } catch (RfcLogonException e) { // user could not logon... throw e; } catch (RfcAbapRuntimeException e) { // serious problem on ABAP system side... throw e; } catch (RfcAbapBaseException e) { // The function module returned an ABAP exception, an ABAP message // or an ABAP class-based exception... throw e; } catch (Exception e) { throw e; } }
public void usuarioscaja(string P_UNAME, string P_PASSWORD, string P_IDSISTEMA, string P_INSTANCIA, string P_MANDANTE, string P_SAPROUTER , string P_SERVER, string P_IDIOMA, string P_TEMPORAL, string P_MONTO, List <USR_CAJA> P_USUARIOS, string P_EQUIPO) { ObjDatosUser.Clear(); LogApert.Clear(); Retorno.Clear(); errormessage = ""; Mensaje = ""; Sociedad = ""; status = ""; cajeroresp = ""; IRfcStructure lt_USER; IRfcStructure lt_retorno; IRfcStructure ls_logapert; USR_CAJA USER_resp; ESTADO retorno_resp; LOG_APERTURA log_apert_resp; //Conexion a SAP connectorSap.idioma = P_IDIOMA; connectorSap.idSistema = P_IDSISTEMA; connectorSap.instancia = P_INSTANCIA; connectorSap.mandante = P_MANDANTE; connectorSap.paswr = P_PASSWORD; connectorSap.sapRouter = P_SAPROUTER; connectorSap.user = P_UNAME; connectorSap.server = P_SERVER; string retval = connectorSap.connectionsSAP(); //Si el valor de retorno es nulo o vacio, hay conexion a SAP y la RFC trae datos if (string.IsNullOrEmpty(retval)) { RfcDestination SapRfcDestination = RfcDestinationManager.GetDestination(connectorSap.connectorConfig); RfcRepository SapRfcRepository = SapRfcDestination.Repository; IRfcFunction BapiGetUser = SapRfcRepository.CreateFunction("ZSCP_RFC_ACCESO_CAJA"); IRfcStructure GralDat = BapiGetUser.GetStructure("USR_CAJA"); for (var i = 0; i < P_USUARIOS.Count; i++) { //GralDat.Append(); GralDat.SetValue("LAND", P_USUARIOS[i].LAND); GralDat.SetValue("ID_CAJA", P_USUARIOS[i].ID_CAJA); GralDat.SetValue("USUARIO", P_USUARIOS[i].USUARIO); GralDat.SetValue("SOCIEDAD", P_USUARIOS[i].SOCIEDAD); GralDat.SetValue("NOM_CAJA", P_USUARIOS[i].NOM_CAJA); GralDat.SetValue("TIPO_USUARIO", P_USUARIOS[i].TIPO_USUARIO); GralDat.SetValue("USUARIO", P_USUARIOS[i].USUARIO); GralDat.SetValue("WAERS", P_USUARIOS[i].WAERS); } BapiGetUser.SetValue("USR_CAJA", GralDat); BapiGetUser.SetValue("TEMPORAL", P_TEMPORAL); BapiGetUser.SetValue("MONTO", P_MONTO); BapiGetUser.SetValue("EQUIPO", P_EQUIPO); // IRfcStructure GralDat = BapiGetUser.GetStructure("CONDICIONES"); // BapiGetUser.SetValue("T_GET_DOC", GralDat); BapiGetUser.Invoke(SapRfcDestination); cajeroresp = BapiGetUser.GetString("CAJERO_RESPONSABLE"); lt_retorno = BapiGetUser.GetStructure("ESTATUS"); ls_logapert = BapiGetUser.GetStructure("LOG_APERTURA"); lt_USER = BapiGetUser.GetStructure("USR_CAJA"); if (lt_retorno.Count > 0) { retorno_resp = new ESTADO(); for (int i = 0; i < lt_retorno.Count(); i++) { if (i == 0) { status = lt_retorno.GetString("TYPE"); } retorno_resp.TYPE = lt_retorno.GetString("TYPE"); retorno_resp.ID = lt_retorno.GetString("ID"); retorno_resp.NUMBER = lt_retorno.GetString("NUMBER"); retorno_resp.MESSAGE = lt_retorno.GetString("MESSAGE"); retorno_resp.LOG_NO = lt_retorno.GetString("LOG_NO"); retorno_resp.LOG_MSG_NO = lt_retorno.GetString("LOG_MSG_NO"); retorno_resp.MESSAGE = lt_retorno.GetString("MESSAGE"); retorno_resp.MESSAGE_V1 = lt_retorno.GetString("MESSAGE_V1"); if (i == 0) { Mensaje = Mensaje + " - " + lt_retorno.GetString("MESSAGE") + " " + lt_retorno.GetString("MESSAGE_V1"); id_apertura = lt_retorno.GetString("MESSAGE_V1"); } retorno_resp.MESSAGE_V2 = lt_retorno.GetString("MESSAGE_V2"); retorno_resp.MESSAGE_V3 = lt_retorno.GetString("MESSAGE_V3"); retorno_resp.MESSAGE_V4 = lt_retorno.GetString("MESSAGE_V4"); retorno_resp.PARAMETER = lt_retorno.GetString("PARAMETER"); retorno_resp.ROW = lt_retorno.GetString("ROW"); retorno_resp.FIELD = lt_retorno.GetString("FIELD"); retorno_resp.SYSTEM = lt_retorno.GetString("SYSTEM"); Retorno.Add(retorno_resp); } System.Windows.MessageBox.Show(Mensaje); } //lt_PART_ABIERTAS = BapiGetUser.GetTable("ZCLSP_TT_LISTA_DOCUMENTOS"); if (lt_USER.Count > 0) { //LLenamos la tabla de salida lt_DatGen for (int i = 0; i < lt_USER.Count(); i++) { USER_resp = new USR_CAJA(); USER_resp.LAND = lt_USER.GetString("LAND"); Sociedad = lt_USER.GetString("SOCIEDAD"); USER_resp.SOCIEDAD = lt_USER.GetString("SOCIEDAD"); USER_resp.USUARIO = lt_USER.GetString("USUARIO"); USER_resp.ID_CAJA = lt_USER.GetString("ID_CAJA"); USER_resp.NOM_CAJA = lt_USER.GetString("NOM_CAJA"); USER_resp.TIPO_USUARIO = lt_USER.GetString("TIPO_USUARIO"); USER_resp.WAERS = lt_USER.GetString("WAERS"); ObjDatosUser.Add(USER_resp); //ViasPagoTransaccion.Add(VIAS_PAGOS_resp.); } } if (ls_logapert.Count > 0) { //LLenamos la tabla de salida lt_DatGen for (int i = 0; i < ls_logapert.Count(); i++) { log_apert_resp = new LOG_APERTURA(); log_apert_resp.MANDT = ls_logapert.GetString("MANDT"); log_apert_resp.ID_REGISTRO = ls_logapert.GetString("ID_REGISTRO"); log_apert_resp.LAND = ls_logapert.GetString("LAND"); log_apert_resp.ID_CAJA = ls_logapert.GetString("ID_CAJA"); log_apert_resp.USUARIO = ls_logapert.GetString("USUARIO"); if (ls_logapert.GetString("FECHA") != "0000-00-00") { log_apert_resp.FECHA = Convert.ToDateTime(ls_logapert.GetString("FECHA")); } if (ls_logapert.GetString("HORA") != "00:00:00") { log_apert_resp.HORA = Convert.ToDateTime(ls_logapert.GetString("HORA")); } log_apert_resp.MONTO = ls_logapert.GetString("MONTO"); log_apert_resp.MONEDA = ls_logapert.GetString("MONEDA"); log_apert_resp.TIPO_REGISTRO = ls_logapert.GetString("TIPO_REGISTRO"); log_apert_resp.ID_APERTURA = id_apertura; log_apert_resp.TXT_CIERRE = ls_logapert.GetString("TXT_CIERRE"); log_apert_resp.BLOQUEO = ls_logapert.GetString("BLOQUEO"); log_apert_resp.USUARIO_BLOQ = ls_logapert.GetString("USUARIO_BLOQ"); if (i == 0) { LogApert.Add(log_apert_resp); } } } GC.Collect(); } else { errormessage = retval; } }
public string doAction() { try { SqlConnection sqlconn = new SqlConnection(__conn); string sqlstr = @"SELECT ObjectId FROM WF_Object WHERE BaseId='" + __flowId + "'"; SqlDataAdapter sda = new SqlDataAdapter(sqlstr, sqlconn); //获取 DataSet ds = new DataSet(); sda.Fill(ds); DataTable dt = new DataTable(); dt = ds.Tables[0]; // 链接 RfcConfigParameters rfcPar = new RfcConfigParameters(); rfcPar.Add(RfcConfigParameters.Name, "DEV"); rfcPar.Add(RfcConfigParameters.AppServerHost, "10.98.0.22"); rfcPar.Add(RfcConfigParameters.Client, "400"); rfcPar.Add(RfcConfigParameters.User, "USER01"); rfcPar.Add(RfcConfigParameters.Password, "1234567890"); rfcPar.Add(RfcConfigParameters.SystemNumber, "00");//SAP实例 rfcPar.Add(RfcConfigParameters.Language, "ZH"); RfcDestination dest = RfcDestinationManager.GetDestination(rfcPar); RfcRepository rfcrep = dest.Repository; IRfcFunction myfun = dest.Repository.CreateFunction("Z_RFC_PLM_SAP_BOM_CREATE"); IRfcStructure import = null; IRfcTable table = myfun.GetTable("ZT_PP0011"); IRfcTable retable; SqlDataAdapter sda2; DataTable dt2; DataTable dt3; bool wrong = true; string error = ""; DataRow dr; for (int i = 0; i < dt.Rows.Count; i++) { sqlstr = @"exec GETBOM_woo '" + dt.Rows[i][0] + "'"; sda2 = new SqlDataAdapter(sqlstr, sqlconn); dt2 = new DataTable(); sda2.Fill(dt2); for (int j = 0; j < dt2.Rows.Count; j++) { import = rfcrep.GetStructureMetadata("ZPP0011").CreateStructure(); import.SetValue("MATNR", dt2.Rows[j][0]); //物料编号 import.SetValue("DATUV", dt2.Rows[j][1]); //有效起始日期 import.SetValue("IDNRK", dt2.Rows[j][2]); //BOM 组件 import.SetValue("BMENG", dt2.Rows[j][3]); //基本数量 import.SetValue("STLST", dt2.Rows[j][4]); //BOM 状态 import.SetValue("MENGE", dt2.Rows[j][5]); //组件数量 import.SetValue("MEINS", dt2.Rows[j][6]); //组件计量单位 import.SetValue("DATUV_I", dt2.Rows[j][7]); //有效起始日期 import.SetValue("DATUB_I", dt2.Rows[j][8]); //有效截止日期 table.Append(import); } myfun.Invoke(dest); } dt3 = new DataTable(); dt3.Columns.Add("MATNR", typeof(string)); dt3.Columns.Add("POSNR", typeof(string)); dt3.Columns.Add("IDNRK", typeof(string)); dt3.Columns.Add("FLAG", typeof(string)); dt3.Columns.Add("ZRESULTS", typeof(string)); retable = myfun.GetTable("ZT_PP0011_RLT"); //re1 = re1 + " kmax=" + Convert.ToString(retable.RowCount) + " ; table= " + Convert.ToString(table.RowCount); for (int k = 0; k < retable.Count; k++) { retable.CurrentIndex = k; dr = dt3.NewRow(); dr["MATNR"] = retable[k].GetValue("MATNR").ToString(); dr["POSNR"] = retable[k].GetValue("POSNR").ToString(); dr["IDNRK"] = retable[k].GetValue("IDNRK").ToString(); dr["FLAG"] = retable[k].GetValue("FLAG").ToString(); dr["ZRESULTS"] = retable[k].GetValue("ZRESULTS").ToString(); if (Convert.ToString(dr["FLAG"]) == "E") { if (dr["ZRESULTS"].ToString() == "" || dr["ZRESULTS"].ToString().Contains("创建过程中")) { continue; } wrong = false; error = error + "第" + (k + 1) + "行子物料" + retable[k].GetValue("MATNR").ToString() + "<出错原因:" + dr["ZRESULTS"].ToString() + ">;"; } dt3.Rows.Add(dr); } if (wrong == false) { return(error); } else { return(""); } } catch (Exception ex) { return(ex.Message); } }
public static Hashtable SAPExecuteTableData_Common(Hashtable[] arrht, Hashtable ImportData, string Function_Name, string RfcStructure_Name, string Table_Name, string GetTable_Name, string GetTable_Name2) { RfcConfigParameters configParam = GetConfigParam(); RfcDestination destination = RfcDestinationManager.GetDestination(configParam); IRfcFunction function = destination.Repository.CreateFunction(Function_Name); IRfcTable rfcTable = function.GetTable(Table_Name); for (int i = 0; i < arrht.Length; i++) { RfcStructureMetadata strMeta = destination.Repository.GetStructureMetadata(RfcStructure_Name); IRfcStructure rfcStructure = strMeta.CreateStructure(); //if (arrht[i] == null) // continue; IDictionaryEnumerator ie = arrht[i].GetEnumerator(); while (ie.MoveNext()) { if (ie.Value.ToString().Length <= 4000) { rfcStructure.SetValue(ie.Key.ToString(), ie.Value); } } rfcTable.Append(rfcStructure); } if (ImportData.Count > 0) { IDictionaryEnumerator ie = ImportData.GetEnumerator(); while (ie.MoveNext()) { if (ie.Value.ToString().Length <= 4000) { function.SetValue(ie.Key.ToString(), ie.Value); } } } function.Invoke(destination); IRfcTable rfcTable2 = function.GetTable(GetTable_Name); IRfcTable rfcTable3 = null; if (GetTable_Name2 != null) { rfcTable3 = function.GetTable(GetTable_Name2); } Hashtable ht = new Hashtable(); switch (Function_Name) { case "ZMM_SKD_PO_AND_GR": ht.Add("I_EBELN", function.GetString("I_EBELN")); ht.Add("I_MBLNR", function.GetString("I_MBLNR")); ht.Add("FT_RETURN_PO", rfcTable2); ht.Add("FT_RETURN_GR", rfcTable3); break; case "ZMM_SKD_PO": ht.Add("I_EBELN", function.GetString("I_EBELN")); ht.Add("FT_RETURN_PO", rfcTable2); break; case "ZMM_SKD_BAPI_GOODSMVT_CREATE": ht.Add("I_MBLNR", function.GetString("I_MBLNR")); ht.Add("FT_RETURN_GR", rfcTable2); break; } return(ht); }
/// <summary> /// 转换RFC函数读取过来的IDOC. /// </summary> /// <param name="tControl"></param> /// <param name="datarows"></param> /// <returns></returns> private Idoc processSingleIdoc(IRfcStructure tControl, IRfcTable datarows) { Idoc idoc = new Idoc { TABNAM = tControl["TABNAM"].GetValue().ToString().Trim(), MANDT = tControl["MANDT"].GetValue().ToString().Trim(), DOCNUM = tControl["DOCNUM"].GetValue().ToString().Trim(), DOCREL = tControl["DOCREL"].GetValue().ToString().Trim(), STATUS = tControl["STATUS"].GetValue().ToString().Trim(), DIRECT = tControl["DIRECT"].GetValue().ToString().Trim(), OUTMOD = tControl["OUTMOD"].GetValue().ToString().Trim(), EXPRSS = tControl["EXPRSS"].ToString().Trim(), IDOCTYP = tControl["IDOCTYP"].GetValue().ToString().Trim(), CIMTYP = tControl["CIMTYP"].GetValue().ToString().Trim(), MESTYP = tControl["MESTYP"].GetValue().ToString().Trim(), MESCOD = tControl["MESCOD"].GetValue().ToString().Trim(), MESFCT = tControl["MESFCT"].GetValue().ToString().Trim(), STD = tControl["STD"].GetValue().ToString().Trim(), STDVRS = tControl["STDVRS"].GetValue().ToString().Trim(), STDMES = tControl["STDMES"].GetValue().ToString().Trim(), SNDPOR = tControl["SNDPOR"].GetValue().ToString().Trim(), SNDPRT = tControl["SNDPRT"].GetValue().ToString().Trim(), SNDPFC = tControl["SNDPFC"].GetValue().ToString().Trim(), SNDPRN = tControl["SNDPRN"].GetValue().ToString().Trim(), SNDSAD = tControl["SNDSAD"].GetValue().ToString().Trim(), SNDLAD = tControl["SNDLAD"].GetValue().ToString().Trim(), RCVPOR = tControl["RCVPOR"].GetValue().ToString().Trim(), RCVPRT = tControl["RCVPRT"].GetValue().ToString().Trim(), RCVPFC = tControl["RCVPFC"].GetValue().ToString().Trim(), RCVPRN = tControl["RCVPRN"].GetValue().ToString().Trim(), RCVSAD = tControl["RCVSAD"].GetValue().ToString().Trim(), RCVLAD = tControl["RCVLAD"].GetValue().ToString().Trim(), CREDAT = tControl["CREDAT"].GetValue().ToString().Trim(), CRETIM = tControl["CRETIM"].GetValue().ToString().Trim(), REFINT = tControl["REFINT"].GetValue().ToString().Trim(), REFGRP = tControl["REFGRP"].GetValue().ToString().Trim(), REFMES = tControl["REFMES"].GetValue().ToString().Trim(), ARCKEY = tControl["ARCKEY"].GetValue().ToString().Trim(), SERIAL = tControl["SERIAL"].GetValue().ToString().Trim() }; Hashtable hashtable = new Hashtable(); for (int i = 0; i < datarows.RowCount; i++) { IRfcStructure structure = datarows[i]; if (structure["DOCNUM"].GetValue().ToString().Trim().Equals(tControl["DOCNUM"].GetValue().ToString().Trim())) { IdocSegment newSegment = new IdocSegment(); if (structure["PSGNUM"].GetValue().ToString() == "000000") { idoc.Segments.Add(newSegment); } else { IdocSegment segment2 = (IdocSegment)hashtable[structure["PSGNUM"].GetValue().ToString()]; if (segment2 != null) { segment2.ChildSegments.Add(newSegment); } else { idoc.Segments.Add(newSegment); } } newSegment.SegmentName = structure["SEGNAM"].GetValue().ToString(); newSegment.SegmentNumber = structure["SEGNUM"].ToString(); segNameList.Add(newSegment.SegmentName); string content = structure["SDATA"].GetValue().ToString(); newSegment.WriteDataBuffer(content, 0, 0x3e8); if (!hashtable.ContainsKey(structure["SEGNUM"].GetValue().ToString())) { hashtable.Add(structure["SEGNUM"].GetValue().ToString(), newSegment); } } } return idoc; }
/// <summary> /// no use /// </summary> /// <param name="number"></param> /// <returns></returns> public string CreateCustomer(string number) { if (rfcDestination == null) { rfcDestination = RfcDestinationManager.GetDestination(WebApiApplication.destinationConfigName); } RfcRepository repo = rfcDestination.Repository; IRfcFunction _CUSTOMER = repo.CreateFunction("BAPI_CUSTOMER_CREATEFROMDATA1"); IRfcFunction _Commit = repo.CreateFunction("BAPI_TRANSACTION_COMMIT"); IRfcStructure _PI_COPYREFERENCE = _CUSTOMER.GetStructure("PI_COPYREFERENCE"); _PI_COPYREFERENCE.SetValue("SALESORG", "1000"); _PI_COPYREFERENCE.SetValue("DISTR_CHAN", "00"); _PI_COPYREFERENCE.SetValue("DIVISION", "00"); _PI_COPYREFERENCE.SetValue("REF_CUSTMR", "0010000003"); IRfcStructure _PI_PERSONALDATA = _CUSTOMER.GetStructure("PI_PERSONALDATA"); _PI_PERSONALDATA.SetValue("FIRSTNAME", "1234"); _PI_PERSONALDATA.SetValue("LASTNAME", "DDDD"); _PI_PERSONALDATA.SetValue("COUNTRY", "US"); _PI_PERSONALDATA.SetValue("REGION", "AK"); _PI_PERSONALDATA.SetValue("LANGU_P", "EN"); _PI_PERSONALDATA.SetValue("CURRENCY", "USD"); _PI_PERSONALDATA.SetValue("middlename", "john"); _PI_PERSONALDATA.SetValue("date_birth", "19780101"); _PI_PERSONALDATA.SetValue("langu_p", "EN"); _PI_PERSONALDATA.SetValue("district", "Hyd"); _PI_PERSONALDATA.SetValue("house_no", "11230"); _PI_PERSONALDATA.SetValue("building", "super"); _PI_PERSONALDATA.SetValue("room_no", "113"); _PI_PERSONALDATA.SetValue("title_p", "Mr.");//Invalid form of address text error you need set Mr. reference table TSAD3T _PI_PERSONALDATA.SetValue("city", "LOS_ANGELES"); //IRfcStructure _PI_OPT_PERSONALDATA = _CUSTOMER.GetStructure("PI_OPT_PERSONALDATA"); //_PI_OPT_PERSONALDATA.SetValue("SHIP_COND", "01"); //_PI_OPT_PERSONALDATA.SetValue("DELYG_PLNT", "1000"); //IRfcFunction _SdCustomer = repo.CreateFunction("SD_CUSTOMER_MAINTAIN_ALL"); //IRfcStructure _Knvv = _SdCustomer.GetStructure("I_KNVV"); //_Knvv.SetValue("KUNNR", number); //_Knvv.SetValue("VKORG", "1000"); //_Knvv.SetValue("VTWEG", "00"); //_Knvv.SetValue("SPART", "00"); //_Knvv.SetValue("KALKS", "1"); //_Knvv.SetValue("BZIRK", "US"); //_Knvv.SetValue("WAERS", "USD"); //_Knvv.SetValue("KURST", "E"); //_Knvv.SetValue("KONDA", "MSRP"); //_Knvv.SetValue("VSBED", "01"); //_Knvv.SetValue("INCO1", "DDP"); //_Knvv.SetValue("INCO2", "US"); RfcSessionManager.BeginContext(rfcDestination); _CUSTOMER.Invoke(rfcDestination); _Commit.Invoke(rfcDestination); RfcSessionManager.EndContext(rfcDestination); IRfcStructure structReturn = _CUSTOMER.GetStructure("RETURN"); string _CUSTOMERNO = _CUSTOMER.GetString("CUSTOMERNO"); string _TYPE = structReturn.GetString("TYPE"); string _MESSAGE = structReturn.GetString("MESSAGE"); DataTable dtReturn = setErrorTable(_TYPE, _MESSAGE, "PI_COPYREFERENCE"); List <ErrorLog> _ErrorList = SetErrorLog(dtReturn, "BAPI_CUSTOMER_CREATEFROMDATA1", "", ""); List <string> _Error = this._errorLogService.MiltiCreate(_ErrorList); return(""); }