private void btnConnect_Click(object sender, EventArgs e) { try { oCompany = new SAPbobsCOM.Company(); oCompany.Server = "192.168.1.233:30015"; oCompany.SLDServer = "192.168.1.233:40000"; oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_HANADB; oCompany.CompanyDB = "SBODEMOES"; oCompany.UserName = "******"; oCompany.Password = "******"; oCompany.DbUserName = "******"; oCompany.DbPassword = "******"; int ret = oCompany.Connect(); if (ret == 0) { MessageBox.Show("Connection ok"); } else { MessageBox.Show("Connection failed: " + oCompany.GetLastErrorCode().ToString() + " - " + oCompany.GetLastErrorDescription()); } } catch (Exception ex) { MessageBox.Show("Connection error: " + ex.Message); } }
static void Main(string[] args) { Console.WriteLine("Hello"); try { SAPbobsCOM.Company company = new SAPbobsCOM.Company(); company.CompanyDB = "SBODemoUS"; company.Server = "MIKISURFACE"; company.LicenseServer = "MIKISURFACE:30000"; company.SLDServer = "MIKISURFACE:40000"; company.DbUserName = "******"; company.DbPassword = "******"; company.UseTrusted = true; company.UserName = "******"; company.Password = "******"; company.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2016; int status = company.Connect(); string errorMsg = company.GetLastErrorDescription(); int errorCode = company.GetLastErrorCode(); System.Diagnostics.Debug.WriteLine($"Connection Status {status} msg {errorMsg} code {errorCode}"); SAPbobsCOM.RecordsetEx rs = company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordsetEx); rs.DoQuery("select * from OITM"); rs.MoveNext(); string ic = rs.GetColumnValue("ItemCode"); System.Diagnostics.Debug.WriteLine($"Item Code is {ic}"); company.Disconnect(); System.Diagnostics.Debug.WriteLine("Disconnected"); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } }
/// <summary> /// 连接B1账套 /// </summary> /// <author>WangPeng</author> private static SAPbobsCOM.Company ConnectB1Company() { if (_SAPCompany == null) { _SAPCompany = new SAPbobsCOM.Company(); } if (_SAPCompany.Connected == true) { return(_SAPCompany); } Logger.Writer("开始连接B1账套……"); _SAPCompany.DbServerType = (SAPbobsCOM.BoDataServerTypes)System.Enum.Parse(typeof(SAPbobsCOM.BoDataServerTypes), ConfigurationManager.AppSettings["SAPDBServerType"]); _SAPCompany.Server = ConfigurationManager.AppSettings["SAPServer"]; _SAPCompany.language = SAPbobsCOM.BoSuppLangs.ln_Chinese; _SAPCompany.UseTrusted = Convert.ToBoolean(ConfigurationManager.AppSettings["UseTrusted"]); _SAPCompany.DbUserName = ConfigurationManager.AppSettings["UserID"]; _SAPCompany.DbPassword = ConfigurationManager.AppSettings["Password"]; _SAPCompany.CompanyDB = ConfigurationManager.AppSettings["SAPDB"]; _SAPCompany.UserName = ConfigurationManager.AppSettings["SAPUser"]; _SAPCompany.Password = ConfigurationManager.AppSettings["SAPPassword"]; _SAPCompany.LicenseServer = ConfigurationManager.AppSettings["SAPLicenseServer"]; int RntCode = _SAPCompany.Connect(); if (RntCode != 0) { string errMsg = string.Format("ErrorCode:[{0}],ErrrMsg:[{1}];", _SAPCompany.GetLastErrorCode(), _SAPCompany.GetLastErrorDescription()); Logger.Writer(errMsg); throw new Exception(errMsg); } Logger.Writer("已连接 " + _SAPCompany.CompanyName); return(_SAPCompany); }
/// <summary> /// Builds a connection to SAP B1 via DI /// </summary> /// <returns></returns> public void Connect(ConnectionParams connectionParams) { this.connectionParams = connectionParams; if (this._company == null) { this._company = new SAPbobsCOM.Company(); } if (!this._company.Connected) { _company.CompanyDB = connectionParams.CompanyDB; _company.Server = connectionParams.Server; _company.LicenseServer = connectionParams.LicenseServer; _company.SLDServer = connectionParams.SLDServer; _company.DbUserName = connectionParams.DbUserName; _company.DbPassword = connectionParams.DbPassword; //UseTrusted must be false when DB User is defined, otherwise cannot connect to SBO-COMMON error is thrown on IIS _company.UseTrusted = string.IsNullOrEmpty(connectionParams.DbUserName) ? connectionParams.UseTrusted : false; _company.UserName = connectionParams.UserName; _company.Password = connectionParams.Password; _company.DbServerType = connectionParams.boDataServerType(); int status = _company.Connect(); _company.XMLAsString = true; //THIS IS TERRIBLY IMPORTANT for XML handling System.Diagnostics.Debug.WriteLine("SAP DI is connected"); } if (!this._company.Connected) { string errorMsg = _company.GetLastErrorDescription(); int errorCode = _company.GetLastErrorCode(); throw new Exception($"Connection was rejected msg { errorMsg } code { errorCode}"); } }
public static bool FailOperation(this SAPbobsCOM.Company oCompany, int lRetCode, out string sResultMsg) { bool error = false; sResultMsg = String.Empty; if (lRetCode != 0) // if the connection failed { error = true; //oCompany.GetLastError(out lErrCode, out sResultMsg); //sResultMsg = String.Format("{0} - {1}", lErrCode, sResultMsg); sResultMsg = String.Format("{0} | {1}", oCompany.GetLastErrorCode(), oCompany.GetLastErrorDescription()); } return(error); }
private void Button0_ClickBefore(object sboObject, SAPbouiCOM.SBOItemEventArg pVal, out bool BubbleEvent) { BubbleEvent = true; try { if (EditText1.Value == "") { Application.SBO_Application.MessageBox("Favor de capturar el Folio de la solicitud"); return; } SAPbobsCOM.StockTransfer lObjStockTrasnfer; string lStrFolio = EditText1.Value; SAPbobsCOM.SBObob lObjSBObob = (SAPbobsCOM.SBObob)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoBridge); SAPbobsCOM.Recordset lObjRecordSet = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset); lObjRecordSet = lObjSBObob.GetObjectKeyBySingleValue(SAPbobsCOM.BoObjectTypes.oInventoryTransferRequest, "DocNum", lStrFolio, SAPbobsCOM.BoQueryConditions.bqc_Equal); SAPbobsCOM.StockTransfer lObjInventory = (SAPbobsCOM.StockTransfer)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInventoryTransferRequest); if (lObjRecordSet.RecordCount == 1) { lObjInventory.GetByKey(int.Parse(lObjRecordSet.Fields.Item(0).Value.ToString())); } Memory.ReleaseComObject(lObjSBObob); Memory.ReleaseComObject(lObjRecordSet); SAPbobsCOM.Recordset lObjRecordSet2 = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset); lObjRecordSet2.DoQuery("select T0.U_CR_Batch, T0.DocEntry,T0.LineNum, T0.OpenQty, T0.WhsCode, T0.FromWhsCod, T0.U_CR_CardCode, T0.ItemCode from WTQ1 T0 inner join OWTQ T1 on T1.DocEntry = T0.DocEntry Inner join OCRD T3 on T3.cardcode = T0.U_CR_CardCode where T1.DocNum = '" + lStrFolio + "' and T0.InvntSttus = 'O'"); lLstExtraData = new List <object>(); for (int i = 0; i < lObjRecordSet2.RecordCount; i++) { lLstExtraData.Add(new { Lote = lObjRecordSet2.Fields.Item(0).Value.ToString(), DocEntry = lObjRecordSet2.Fields.Item(1).Value.ToString(), LineNum = lObjRecordSet2.Fields.Item(2).Value.ToString(), Quantity = lObjRecordSet2.Fields.Item(3).Value.ToString(), Whscode = lObjRecordSet2.Fields.Item(4).Value.ToString(), FromWhscode = lObjRecordSet2.Fields.Item(5).Value.ToString(), CardCode = lObjRecordSet2.Fields.Item(6).Value.ToString(), ItemCode = lObjRecordSet2.Fields.Item(7).Value.ToString() }); lObjRecordSet2.MoveNext(); } Memory.ReleaseComObject(lObjRecordSet2); lObjStockTrasnfer = (SAPbobsCOM.StockTransfer)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oStockTransfer); bool lBolIsSuccesss = false; for (int i = 1; i <= Matrix1.RowCount; i++) { SAPbouiCOM.CheckBox lObjChk = (SAPbouiCOM.CheckBox)Matrix1.Columns.Item(0).Cells.Item(i).Specific; if (lObjChk.Checked) { lObjStockTrasnfer.FromWarehouse = ((SAPbouiCOM.EditText)Matrix1.Columns.Item(3).Cells.Item(i).Specific).Value; lObjStockTrasnfer.ToWarehouse = ((dynamic)lLstExtraData[i - 1]).Whscode; string lStrCardCode = ((SAPbouiCOM.EditText)Matrix1.Columns.Item("Col_6").Cells.Item(i).Specific).Value; string lStrAlmacen = ((SAPbouiCOM.EditText)Matrix1.Columns.Item("Col_3").Cells.Item(i).Specific).Value; string lStrCantidad = ((SAPbouiCOM.EditText)Matrix1.Columns.Item("Col_4").Cells.Item(i).Specific).Value; string lStrTrans = ((SAPbouiCOM.EditText)Matrix1.Columns.Item("Col_5").Cells.Item(i).Specific).Value; string lStrItemCode = ((SAPbouiCOM.EditText)Matrix1.Columns.Item("Col_7").Cells.Item(i).Specific).Value; var lObjData = new { CardCode = lStrCardCode, Almacen = lStrAlmacen, Cantidad = lStrCantidad, Trans = lStrTrans, ItemCode = lStrItemCode }; if (lStrTrans.Trim() != "") { lObjStockTrasnfer = AddLines(lObjStockTrasnfer, lObjInventory, lObjData); lBolIsSuccesss = true; } else { Application.SBO_Application.StatusBar.SetText("Capturar cantidad", SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Error); } } } if (lBolIsSuccesss) { lObjStockTrasnfer.DocDate = DateTime.Now; if (lObjStockTrasnfer.Add() != 0) { int error = oCompany.GetLastErrorCode(); string strError = oCompany.GetLastErrorDescription(); Application.SBO_Application.MessageBox(strError); } else { EditText1.Value = ""; LoadMatrixPeticiones(); Application.SBO_Application.StatusBar.SetText("Traslado correctamente efectuado.", SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Success); } } else { Application.SBO_Application.StatusBar.SetText("No se ha seleccionado ningun almacen para el traslado.", SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Error); } } catch (Exception ex) { Application.SBO_Application.StatusBar.SetText(ex.Message, SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Error); } }
public void B1Connect(bool stopEvents) { SAPbouiCOM.SboGuiApi objGUIApi = null; SAPbobsCOM.Company objCompany = null; try { _Logger.Debug("Starting SAP Connection"); objGUIApi = new SAPbouiCOM.SboGuiApi(); _Logger.Debug("Retrieving connection string from Cache"); objGUIApi.Connect((string)T1.CacheManager.CacheManager.Instance.getFromCache(T1.CacheManager.Settings._Main.connStringCacheName)); _Logger.Debug("Connectong to current company"); objApplication = objGUIApi.GetApplication(-1); objApplication.EventLevel = SAPbouiCOM.BoEventLevelType.elf_Both; if (Settings._Main.useCompatibilityConnection) { _Logger.Info("Connecting to DI API using Compatibility mode (cookies)"); objCompany = new SAPbobsCOM.Company(); string strContextCookie = objCompany.GetContextCookie(); string strConnectionString = objApplication.Company.GetConnectionContext(strContextCookie); _Logger.Debug("Setting Login Context"); if (objCompany.SetSboLoginContext(strConnectionString) == 0) { if (objCompany.Connect() != 0) { string strError = objCompany.GetLastErrorCode() + ":" + objCompany.GetLastErrorDescription(); _Logger.Error(strError); } else { bool isHANA = objCompany.DbServerType == SAPbobsCOM.BoDataServerTypes.dst_HANADB ? true : false; T1.CacheManager.CacheManager.Instance.addToCache(T1.CacheManager.Settings._Main.isHANACacheName, isHANA, CacheManager.CacheManager.objCachePriority.NotRemovable); } } else { string strError = objCompany.GetLastErrorCode() + ":" + objCompany.GetLastErrorDescription(); _Logger.Error(strError); } } else { _Logger.Info("Connecting to DI API using shared memory library"); objCompany = new SAPbobsCOM.Company(); if (Settings._Main.useCompanyApplication) { objCompany.Application = objApplication; if (objCompany.Connect() != 0) { string strError = objCompany.GetLastErrorCode() + ":" + objCompany.GetLastErrorDescription(); _Logger.Error(strError); } else { bool isHANA = objCompany.DbServerType == SAPbobsCOM.BoDataServerTypes.dst_HANADB ? true : false; T1.CacheManager.CacheManager.Instance.addToCache(T1.CacheManager.Settings._Main.isHANACacheName, isHANA, CacheManager.CacheManager.objCachePriority.NotRemovable); } } else { objCompany = objApplication.Company.GetDICompany(); bool isHANA = objCompany.DbServerType == SAPbobsCOM.BoDataServerTypes.dst_HANADB ? true : false; T1.CacheManager.CacheManager.Instance.addToCache(T1.CacheManager.Settings._Main.isHANACacheName, isHANA, CacheManager.CacheManager.objCachePriority.NotRemovable); } } _Logger.Debug("Checking connection status"); blConnected = objCompany.Connected; if (blConnected) { _Logger.Debug("Connected to company " + objCompany.CompanyName); objCompany.XmlExportType = SAPbobsCOM.BoXmlExportTypes.xet_ExportImportMode; objCompany.XMLAsString = true; T1.B1.MainObject.Instance.B1Application = objApplication; T1.B1.MainObject.Instance.B1Company = objCompany; SAPbobsCOM.CompanyService objServ = objCompany.GetCompanyService(); SAPbobsCOM.AdminInfo objAdmInfo = objServ.GetAdminInfo(); T1.B1.InternalClasses.AdminInfo B1AdmInfo = new InternalClasses.AdminInfo(); B1AdmInfo.DecimalSeparator = objAdmInfo.DecimalSeparator; B1AdmInfo.ThousandsSeparator = objAdmInfo.ThousandsSeparator; B1AdmInfo.DateSeparator = objAdmInfo.DateSeparator; B1AdmInfo.SystemCurrency = objAdmInfo.SystemCurrency; B1AdmInfo.RateAccuracy = objAdmInfo.RateAccuracy; B1AdmInfo.QueryAccuracy = objAdmInfo.QueryAccuracy; B1AdmInfo.AccuracyofQuantities = objAdmInfo.AccuracyofQuantities; B1AdmInfo.PercentageAccuracy = objAdmInfo.PercentageAccuracy; B1AdmInfo.PriceAccuracy = objAdmInfo.PriceAccuracy; B1AdmInfo.TotalsAccuracy = objAdmInfo.TotalsAccuracy; B1AdmInfo.LocalCurrency = objAdmInfo.LocalCurrency; B1AdmInfo.DateTemplate = objAdmInfo.DateTemplate; B1AdmInfo.DisplayCurrencyontheRight = objAdmInfo.DisplayCurrencyontheRight == SAPbobsCOM.BoYesNoEnum.tYES ? true : false; B1AdmInfo.FederalTaxID = objAdmInfo.FederalTaxID; B1AdmInfo.MeasuringAccuracy = objAdmInfo.MeasuringAccuracy; T1.B1.MainObject.Instance.B1AdminInfo = B1AdmInfo; } if (stopEvents) { objHandler1 = new SAPbouiCOM._IApplicationEvents_ItemEventEventHandler(objApplication_ItemEvent); objHandler2 = new SAPbouiCOM._IApplicationEvents_MenuEventEventHandler(objApplication_MenuEvent); objApplication.ItemEvent += objHandler1; objApplication.MenuEvent += objHandler2; } } catch (COMException comEx) { //Exception er = new Exception(Convert.ToString(comEx.ErrorCode + "::" + comEx.Message + "::" + comEx.StackTrace)); _Logger.Error("", comEx); } catch (Exception er) { _Logger.Error("", er); } }
static void Main(string[] args) { try { DateTime fechaSap = DateTime.Now.AddDays(1); WebServiceTRMReference.TCRMServicesInterfaceClient ws = new WebServiceTRMReference.TCRMServicesInterfaceClient(); WebServiceTRMReference.tcrmResponse respuestaTRM = new WebServiceTRMReference.tcrmResponse(); respuestaTRM = ws.queryTCRM(fechaSap); SAPbobsCOM.Company oCompany = new SAPbobsCOM.Company(); oCompany.Server = ConfigurationManager.AppSettings.Get("Server"); oCompany.LicenseServer = ConfigurationManager.AppSettings.Get("LicenseServer"); oCompany.CompanyDB = ConfigurationManager.AppSettings.Get("CompanyDB"); oCompany.UserName = ConfigurationManager.AppSettings.Get("UserName"); oCompany.Password = ConfigurationManager.AppSettings.Get("Password"); switch (ConfigurationManager.AppSettings.Get("DbServerType")) { case "dst_HANADB": oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_HANADB; break; case "dst_MSSQL2005": oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2005; break; case "dst_MSSQL2008": oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2008; break; case "dst_MSSQL2012": oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2012; break; case "dst_MSSQL2014": oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2014; break; case "dst_MSSQL2016": oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2016; break; } int resultado = oCompany.Connect(); if (resultado == 0) { SAPbobsCOM.SBObob bo = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoBridge); bo.SetCurrencyRate("USD", fechaSap, Math.Round(respuestaTRM.value, 2), true); oCompany.Disconnect(); Console.WriteLine("TRM Actualizada!"); string asunto = "TRM SAP " + ConfigurationManager.AppSettings.Get("CompanyDB") + " Actualizada " + fechaSap.ToString().Substring(0, 10); string mensaje = "Se ha realizado correctamente la actualizacion de la tasa de cambio del dolar para el dia " + fechaSap.ToString().Substring(0, 10) + " - TRM: $" + respuestaTRM.value; //envia el correo solo en caso de existir error de actualizacion if (ConfigurationManager.AppSettings.Get("CorreoErrorActualiza") == "NO") { EnviarCorreo(asunto, mensaje); } Environment.Exit(1); } else { throw new Exception(oCompany.GetLastErrorCode() + ": " + oCompany.GetLastErrorDescription()); } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); string asunto = "TRM SAP " + ConfigurationManager.AppSettings.Get("CompanyDB") + " *ERROR* " + DateTime.Now.AddDays(1); string mensaje = "Error en la actualizacion: " + DateTime.Now.AddDays(1) + " **" + ex.Message; EnviarCorreo(asunto, mensaje); } }
public string InsertarRegistroInspeccion() { bool resultado = TransferirStock("DISP PRO", "CUART MP", "21019908", "MP117060263", 50); string numTrans; if (resultado == true) { numTrans = oCompany.GetNewObjectKey(); } else { return("Error " + oCompany.GetLastErrorCode() + "-" + oCompany.GetLastErrorDescription()); } SAPbobsCOM.GeneralService oGeneralService; SAPbobsCOM.GeneralData oGeneralData; SAPbobsCOM.GeneralData oChild; SAPbobsCOM.GeneralDataCollection oChildren; //SAPbobsCOM.GeneralDataParams oGeneralParams; SAPbobsCOM.CompanyService oCompService; oCompService = oCompany.GetCompanyService(); oCompany.StartTransaction(); oGeneralService = oCompService.GetGeneralService("VID_CONTROLCH"); oGeneralData = (SAPbobsCOM.GeneralData)oGeneralService.GetDataInterface(SAPbobsCOM.GeneralServiceDataInterfaces.gsGeneralData); //Setting Data to Master Data Table Fields oGeneralData.SetProperty("U_FecIngr", "2017-06-30"); oGeneralData.SetProperty("U_FecContr", "2017-07-03"); oGeneralData.SetProperty("U_FecIni", "2017-07-03"); oGeneralData.SetProperty("U_FecFin", "2017-07-03"); oGeneralData.SetProperty("DocNum", 1); oGeneralData.SetProperty("U_ItemCode", "73200004"); oGeneralData.SetProperty("U_NumTras", numTrans); oGeneralData.SetProperty("U_ItemName", "CAJA P/EMB Nº3 200X135X225 mm DULZERO 500ml"); oGeneralData.SetProperty("U_WhsCode", "CUART MP"); oGeneralData.SetProperty("U_WhsDest", "DISP PRO"); oGeneralData.SetProperty("U_NoLote", "MEC217060012"); oGeneralData.SetProperty("U_CorrLote", 0); oGeneralData.SetProperty("U_Cantidad", 3880); oGeneralData.SetProperty("U_Bultos", 10); oGeneralData.SetProperty("U_BultosMu", 4); oGeneralData.SetProperty("U_ContraMu", "Y"); oGeneralData.SetProperty("U_MuestDes", "Y"); oGeneralData.SetProperty("U_Traslado", "Y"); oGeneralData.SetProperty("U_Reanalis", "N"); oGeneralData.SetProperty("U_CorrAnal", 0); oGeneralData.SetProperty("U_FecUltIn", "2017-03-05"); oGeneralData.SetProperty("U_UM", "UNIDAD"); oGeneralData.SetProperty("U_CtaCalid", "6010301036"); oGeneralData.SetProperty("U_CCCode", "CC"); oGeneralData.SetProperty("U_Estado", "A"); oGeneralData.SetProperty("U_TipResul", "A100"); oGeneralData.SetProperty("U_PrjCode", ""); oGeneralData.SetProperty("U_Comment", "Cumple con todos analisis requeridos.admision:3.358"); oGeneralData.SetProperty("U_NumTras", numTrans); oChildren = oGeneralData.Child("VID_CONTROLCD"); oChild = oChildren.Add(); oChild.SetProperty("U_CodAtr", "The_Code"); oChild.SetProperty("U_NameAtr", "Attribute name"); oChild.SetProperty("U_Cualitat", "Y"); oChild.SetProperty("U_Critico", "Y"); oChild.SetProperty("U_TipoMues", "69"); oChild.SetProperty("U_CodEquip", "E"); oChild.SetProperty("U_Estado", "A"); oChild.SetProperty("U_TipoDef", "D"); oChild.SetProperty("U_AQL", "aql"); oChild.SetProperty("U_Rango", "1 - 1"); oChild.SetProperty("U_TiempoDu", "4"); //Agregar el registro oGeneralService.Add(oGeneralData); if (oCompany.InTransaction) { oCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit); } return("Record " + oCompany.GetNewObjectKey() + " added."); }
public bool Connect() { string licenseAddress = ConfigurationManager.AppSettings["LicenseServer"]; if (string.IsNullOrEmpty(licenseAddress)) { LogHelper.Error("GSCompany licenseAddress is Null"); return(false); } string companyDB = ConfigurationManager.AppSettings["CompanyDB"]; if (string.IsNullOrEmpty(licenseAddress)) { LogHelper.Error("GSCompany CompanyDB is Null"); return(false); } string dbUser = ConfigurationManager.AppSettings["DbUserName"]; if (string.IsNullOrEmpty(licenseAddress)) { LogHelper.Error("GSCompany DbUserName is Null"); return(false); } string dbPwd = ConfigurationManager.AppSettings["DbPassword"]; if (string.IsNullOrEmpty(licenseAddress)) { LogHelper.Error("GSCompany DbPassword is Null"); return(false); } string language = ConfigurationManager.AppSettings["Language"]; if (string.IsNullOrEmpty(licenseAddress)) { LogHelper.Error("GSCompany Language is Null"); return(false); } string b1User = ConfigurationManager.AppSettings["UserName"]; if (string.IsNullOrEmpty(licenseAddress)) { LogHelper.Error("GSCompany UserName is Null"); return(false); } string b1Pwd = ConfigurationManager.AppSettings["Password"]; if (string.IsNullOrEmpty(licenseAddress)) { LogHelper.Error("GSCompany Password is Null"); return(false); } string dbServerType = ConfigurationManager.AppSettings["DbServerType"]; if (string.IsNullOrEmpty(licenseAddress)) { LogHelper.Error("GSCompany DbServerType is Null"); return(false); } string serverAddress = ConfigurationManager.AppSettings["Server"]; if (string.IsNullOrEmpty(licenseAddress)) { LogHelper.Error("GSCompany Server is Null"); return(false); } CurrentCompany.CompanyDB = companyDB; CurrentCompany.DbServerType = (SAPbobsCOM.BoDataServerTypes) int.Parse(dbServerType); CurrentCompany.LicenseServer = licenseAddress; CurrentCompany.DbUserName = dbUser; CurrentCompany.DbPassword = dbPwd; CurrentCompany.language = (SAPbobsCOM.BoSuppLangs) int.Parse(language); CurrentCompany.UserName = b1User; CurrentCompany.Password = b1Pwd; CurrentCompany.Server = serverAddress; if (CurrentCompany.Connect() == 0) { return(true); } LogHelper.Error(string.Format("Error Code:{0}----Error Descride:{1}", _Company.GetLastErrorCode().ToString(), _Company.GetLastErrorDescription())); return(false); }
private void ConnectDi() { try { Logger.Info("Initializing DI API for SAP Business One Addon - {0}", Name); if (Company == null) { Company = new Company(); } string cookie = Company.GetContextCookie(); ConnectionString = Application.Company.GetConnectionContext(cookie); // ////////////////My Code int ret = Company.SetSboLoginContext(ConnectionString); int result = 0;//; oCompany.Connect(); Company = (SAPbobsCOM.Company)Application.Company.GetDICompany(); ///////////// /// oldCode ///////////// //if (Company.Connected) // Company.Disconnect(); //int result = Company.SetSboLoginContext(ConnectionString); //if (result != 0) // throw new Exception(string.Format("Error setting login context: {0} - {1} - {2}", result, Company.GetLastErrorCode(), Company.GetLastErrorDescription())); //Logger.Info("Connecting to company database (type: {0}, server: {1}, licenseserver: {2}, database: {3})", Company.DbServerType, Company.Server, Company.LicenseServer, Company.CompanyDB); //result = Company.Connect(); //// end of old code if (result != 0 && !Company.Connected) { throw new Exception(string.Format("Could not connect to company: {0} - {1} - {2}", result, Company.GetLastErrorCode(), Company.GetLastErrorDescription())); } else { Application.SetStatusBarMessage("Connected!", BoMessageTime.bmt_Short, false); } Logger.Info("Addon {0} (version {1}) initialized and connected to SAP Business One DI API version {2}.", Name, Version, Company.Version); } catch (Exception e) { throw new Exception("Error connecting to DI API", e); } }
public void Add(string strKey, SAPbobsCOM.Company oCompany_S, SAPbobsCOM.Company oCompany_D, string strLogger, string strFromWare, string strToWare, string[] strValues) { DataTable oHeader = null; DataTable oDetails = null; int intTStatus = 0; int intExitStatus = 0; int intEntryStatus = 0; SAPbobsCOM.StockTransfer oStockTransfer = (SAPbobsCOM.StockTransfer)oCompany_S.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oStockTransfer); SAPbobsCOM.Documents oInventoryExit = (SAPbobsCOM.Documents)oCompany_S.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInventoryGenExit); SAPbobsCOM.Documents oInventoryEntry = (SAPbobsCOM.Documents)oCompany_D.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInventoryGenEntry); try { string str_S_OWTR = "Exec Armada_Service_S_OWTR_s '" + strKey + "'"; oDataSet = Singleton.objSqlDataAccess.ExecuteDataSet(str_S_OWTR, strLogger); if (oDataSet == null && oDataSet.Tables.Count == 0) { return; } else { Singleton.traceService("Has Record"); oHeader = oDataSet.Tables[0]; oDetails = oDataSet.Tables[1]; if (oHeader != null && oHeader.Rows.Count > 0) { if (oCompany_S.CompanyDB == oCompany_D.CompanyDB) { Singleton.traceService("Same Company...So Transfer"); oStockTransfer.DocDate = Convert.ToDateTime(oHeader.Rows[0]["TrnDate"].ToString()); oStockTransfer.TaxDate = Convert.ToDateTime(oHeader.Rows[0]["TrnDate"].ToString()); oStockTransfer.FromWarehouse = strFromWare; oStockTransfer.Comments = oHeader.Rows[0]["Remarks"].ToString(); oStockTransfer.UserFields.Fields.Item("U_Z_TrnNum").Value = oHeader.Rows[0]["TrnNum"].ToString(); Singleton.traceService("Set Header"); Singleton.traceService(strFromWare); Singleton.traceService(strToWare); if (oDetails.Rows.Count > 0) { foreach (DataRow dr in oDetails.Rows) { oStockTransfer.Lines.ItemCode = dr["ItemCode"].ToString().Trim(); oStockTransfer.Lines.Quantity = Convert.ToDouble(dr["Qty"].ToString()); //oStockTransfer.Lines.FromWarehouseCode = strFromWare; oStockTransfer.Lines.WarehouseCode = strToWare; oStockTransfer.Lines.Add(); } Singleton.traceService("Set Details"); } Singleton.traceService("Adding"); intTStatus = oStockTransfer.Add(); Singleton.traceService(intTStatus.ToString()); if (intTStatus != 0) { Singleton.objSqlDataAccess.UpdateLog(strKey, TransScenerio.InventoryTransfer.ToString(), "0", "0", 0, oCompany_S.GetLastErrorCode().ToString(), oCompany_S.GetLastErrorDescription().Replace("'", ""), strLogger); } else { string strDkey; int intDocNum = 0; oCompany_S.GetNewObjectCode(out strDkey); if (oStockTransfer.GetByKey(Convert.ToInt32(strDkey))) { intDocNum = oStockTransfer.DocNum; } Singleton.objSqlDataAccess.UpdateLog(strKey, TransScenerio.InventoryTransfer.ToString(), strDkey, intDocNum.ToString(), 1, "", "Armada_Sync Completed Sucessfully", strLogger); } } else { //Singleton.traceService("Inventory Exit Started" + oCompany_S.CompanyDB.ToString()); //Singleton.traceService(strFromWare); //Singleton.traceService(strToWare); oInventoryExit.DocDate = Convert.ToDateTime(oHeader.Rows[0]["TrnDate"].ToString()); oInventoryExit.DocDueDate = Convert.ToDateTime(oHeader.Rows[0]["TrnDate"].ToString()); oInventoryExit.Comments = oHeader.Rows[0]["Remarks"].ToString(); oInventoryExit.UserFields.Fields.Item("U_Z_TrnNum").Value = oHeader.Rows[0]["TrnNum"].ToString(); //oInventoryExit.Reference2 = oHeader.Rows[0]["Ref2"].ToString(); //Singleton.traceService("Set Header"); if (oDetails.Rows.Count > 0) { foreach (DataRow dr in oDetails.Rows) { oInventoryExit.Lines.ItemCode = dr["ItemCode"].ToString(); oInventoryExit.Lines.ItemDescription = dr["ItemDsc"].ToString(); oInventoryExit.Lines.Quantity = Convert.ToDouble(dr["Qty"].ToString()); //oInventoryExit.Lines.ShipDate = Convert.ToDateTime(dr["ShipDate"].ToString()); //oInventoryExit.Lines.UnitPrice = 0; oInventoryExit.Lines.WarehouseCode = strFromWare; oInventoryExit.Lines.AccountCode = strValues[1]; oInventoryExit.Lines.Add(); } } //Singleton.traceService("Set Details"); oCompany_S.StartTransaction(); //Singleton.traceService("Adding"); intExitStatus = oInventoryExit.Add(); //Singleton.traceService("Added"); if (intExitStatus != 0) { //Singleton.traceService(intExitStatus.ToString()); Singleton.objSqlDataAccess.UpdateLog(strKey, TransScenerio.InventoryTransfer.ToString(), "0", "0", 0, intExitStatus.ToString(), oCompany_S.GetLastErrorDescription().Replace("'", ""), strLogger); if (oCompany_S.InTransaction) { oCompany_S.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack); } } else { string strDkey; int intDocNum = 0; oCompany_S.GetNewObjectCode(out strDkey); if (oInventoryExit.GetByKey(Convert.ToInt32(strDkey))) { intDocNum = oInventoryExit.DocNum; } //Singleton.traceService("Exit Success"); //Singleton.traceService(intDocNum.ToString()); //Singleton.traceService("Setting Entry Header"); oInventoryEntry.DocDate = Convert.ToDateTime(oHeader.Rows[0]["TrnDate"].ToString()); oInventoryEntry.DocDueDate = Convert.ToDateTime(oHeader.Rows[0]["TrnDate"].ToString()); oInventoryEntry.Comments = oHeader.Rows[0]["Remarks"].ToString(); //oInventoryEntry.PaymentGroupCode = Convert.ToInt16(strValues[0]); // oInventoryEntry.Reference2 = oHeader.Rows[0]["Ref2"].ToString(); oInventoryEntry.UserFields.Fields.Item("U_Z_TrnNum").Value = oHeader.Rows[0]["TrnNum"].ToString(); if (oDetails.Rows.Count > 0) { //Singleton.traceService("Setting Entry Detials"); foreach (DataRow dr in oDetails.Rows) { oInventoryEntry.Lines.ItemCode = dr["ItemCode"].ToString(); oInventoryEntry.Lines.ItemDescription = dr["ItemDsc"].ToString(); oInventoryEntry.Lines.Quantity = Convert.ToDouble(dr["Qty"].ToString()); // oInventoryEntry.Lines.ShipDate = Convert.ToDateTime(dr["ShipDate"].ToString()); oInventoryEntry.Lines.UnitPrice = Convert.ToDouble(dr["LCPrice"].ToString());; oInventoryEntry.Lines.WarehouseCode = strToWare; oInventoryEntry.Lines.AccountCode = strValues[2]; oInventoryEntry.Lines.Add(); } } oCompany_D.StartTransaction(); //Singleton.traceService("Adding Entry"); intEntryStatus = oInventoryEntry.Add(); if (intEntryStatus != 0) { //Singleton.traceService(intEntryStatus.ToString()); Singleton.objSqlDataAccess.UpdateLog(strKey, TransScenerio.InventoryTransfer.ToString(), "0", "0", 0, intEntryStatus.ToString(), oCompany_D.GetLastErrorDescription().Replace("'", ""), strLogger); if (oCompany_S.InTransaction) { oCompany_S.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack); } if (oCompany_D.InTransaction) { oCompany_D.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack); } } else { if (oCompany_S.InTransaction) { oCompany_S.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit); } if (oCompany_D.InTransaction) { oCompany_D.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit); } Singleton.objSqlDataAccess.UpdateLog(strKey, TransScenerio.InventoryTransfer.ToString(), strDkey, intDocNum.ToString(), 1, "", "Armada_Sync Completed Sucessfully", strLogger); } } } } } } catch (Exception ex) { if (oCompany_S.InTransaction) { oCompany_S.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack); } if (oCompany_D.InTransaction) { oCompany_D.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack); } //Singleton.objSqlDataAccess.UpdateLog(strKey, TransScenerio.InventoryTransfer.ToString(), "0", "0", 0, "0", ex.Message.ToString(), strLogger); throw ex; } finally { System.Runtime.InteropServices.Marshal.ReleaseComObject(oStockTransfer); System.Runtime.InteropServices.Marshal.ReleaseComObject(oInventoryExit); System.Runtime.InteropServices.Marshal.ReleaseComObject(oInventoryEntry); } }
void IArmada_Sync.Add(string sKey, SAPbobsCOM.Company oCompany, string strLogger, string strWareHouse, string[] strValues, Hashtable htCCdet) { DataSet oDS_S_OCRD = null; SAPbobsCOM.BusinessPartners oPartner = (SAPbobsCOM.BusinessPartners)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oBusinessPartners); string str_S_OCRD = "Exec Armada_Service_S_OCRD_s '" + sKey + "'"; oDS_S_OCRD = Armada_Sync.Singleton.objSqlDataAccess.ExecuteDataSet(str_S_OCRD, strLogger); try { if (oDS_S_OCRD == null && oDS_S_OCRD.Tables.Count == 0) { return; } else { if ((oDS_S_OCRD.Tables[0] != null) && (oDS_S_OCRD.Tables[0].Rows.Count > 0)) { int retVal; if (!oPartner.GetByKey(oDS_S_OCRD.Tables[0].Rows[0]["Code"].ToString().Trim())) { oPartner.CardCode = oDS_S_OCRD.Tables[0].Rows[0]["Code"].ToString().Trim(); oPartner.CardName = oDS_S_OCRD.Tables[0].Rows[0]["Name"].ToString().Trim(); oPartner.CardType = SAPbobsCOM.BoCardTypes.cCustomer; oPartner.Cellular = oDS_S_OCRD.Tables[0].Rows[0]["Phone"].ToString().Trim(); oPartner.Currency = "##"; oPartner.EmailAddress = oDS_S_OCRD.Tables[0].Rows[0]["Email"].ToString().Trim(); oPartner.Fax = oDS_S_OCRD.Tables[0].Rows[0]["Fax"].ToString().Trim(); int intLine = 0; oPartner.Addresses.SetCurrentLine(intLine); oPartner.Addresses.AddressType = SAPbobsCOM.BoAddressType.bo_BillTo; oPartner.Addresses.AddressName = oDS_S_OCRD.Tables[0].Rows[0]["Name"].ToString().Trim(); oPartner.Addresses.Street = oDS_S_OCRD.Tables[0].Rows[0]["Address"].ToString().Trim(); oPartner.Addresses.Block = oDS_S_OCRD.Tables[0].Rows[0]["Area"].ToString().Trim(); oPartner.Addresses.ZipCode = oDS_S_OCRD.Tables[0].Rows[0]["ZipCode"].ToString().Trim(); oPartner.Addresses.City = oDS_S_OCRD.Tables[0].Rows[0]["City"].ToString().Trim(); oPartner.Addresses.Country = oDS_S_OCRD.Tables[0].Rows[0]["Country"].ToString(); //oPartner.Addresses.State = oDS_S_OCRD.Tables[0].Rows[0]["Name"].ToString(); oPartner.Addresses.Add(); retVal = oPartner.Add(); if (retVal != 0) { Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.Customer.ToString(), "0", "0", 0, oCompany.GetLastErrorCode().ToString(), oCompany.GetLastErrorDescription().Replace("'", ""), strLogger); } else { string strDkey; oCompany.GetNewObjectCode(out strDkey); Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.Customer.ToString(), strDkey, strDkey, 1, "", "Armada_Sync Completed Sucessfully", strLogger); } } else { Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.Customer.ToString(), "", "", 1, "", "Armada_Sync Completed Sucessfully(Customer Already Exist)", strLogger); } } } } catch (Exception ex) { //Singleton.objSqlDataAccess.UpdateLog(sKey, TransScenerio.Customer.ToString(), "0", "0", 0, "0", ex.Message.ToString(), strLogger); throw ex; } finally { oDS_S_OCRD = null; System.Runtime.InteropServices.Marshal.ReleaseComObject(oPartner); } }