/// <summary> /// Initialises server settings, sets up connection credentials and attempts /// a new connection to SAP Business One server. /// </summary> /// <returns>Connection result as integer. Returns 0 if connection was successful</returns> public int Connect(string connection) { /* * All the server settings and user credentials used below are stored in App.config file. * ConfigurationManager is being used to read the App.config file. * You can store you own settings in App.config or use actual values directly in the code: * company.Server = "sapb1server"; * Example.App.config is included in this project, rename it to App.config and populate it with your own values. */ company.Server = ConfigurationManager.AppSettings["server"].ToString(); company.CompanyDB = ConfigurationManager.AppSettings[connection + "companydb"].ToString(); company.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2012; company.DbUserName = ConfigurationManager.AppSettings["dbuser"].ToString(); company.DbPassword = ConfigurationManager.AppSettings["dbpassword"].ToString(); company.UserName = ConfigurationManager.AppSettings[connection + "user"].ToString(); company.Password = ConfigurationManager.AppSettings[connection + "password"].ToString(); company.language = SAPbobsCOM.BoSuppLangs.ln_English_Gb; company.UseTrusted = false; company.LicenseServer = ConfigurationManager.AppSettings["licenseServer"].ToString(); connectionResult = company.Connect(); if (connectionResult != 0) { company.GetLastError(out errorCode, out errorMessage); } return(connectionResult); }
public void editPrice(string sItemCode, string sPriceListName, int iPrice) { try { SAPbobsCOM.Items oItm = (SAPbobsCOM.Items)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oItems); if (oItm.GetByKey(sItemCode)) { for (int i = 0; i < oItm.PriceList.Count - 1; i++) { oItm.PriceList.SetCurrentLine(i); if (oItm.PriceList.PriceListName == sPriceListName) //"基础价格" { oItm.PriceList.Price = iPrice; if (oItm.Update() != 0) { oCompany.GetLastError(out this.iRetCode, out sErrMsg); throw new Exception(iRetCode.ToString() + sErrMsg); } else { MessageBox("OK"); } return; } } } } catch (Exception ex) { MessageBox(ex.ToString()); DealError(ex.ToString()); } }
public void AddTableField(string tablename, string fieldname, int size, SAPbobsCOM.BoFieldTypes type = SAPbobsCOM.BoFieldTypes.db_Alpha) { try { SAPbobsCOM.UserFieldsMD oUserFieldsMD = null; oUserFieldsMD = ((SAPbobsCOM.UserFieldsMD)(oSetupCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oUserFields))); // ************************************ // Adding "Name" field // ************************************ // Setting the Field's properties oUserFieldsMD.TableName = "@" + tablename; oUserFieldsMD.Name = fieldname; oUserFieldsMD.Description = fieldname; oUserFieldsMD.Type = type; if (type == SAPbobsCOM.BoFieldTypes.db_Alpha) { oUserFieldsMD.EditSize = size; } // Adding the Field to the Table lRetCode = oUserFieldsMD.Add(); // Check for errors if (lRetCode != 0) { if (lRetCode == -1) { errorLog(fieldname + " already added"); } else { oSetupCompany.GetLastError(out lRetCode, out sErrMsg); errorLog("Add field error. Field: '" + oUserFieldsMD.Name + "', table: " + oUserFieldsMD.TableName + ", " + sErrMsg); } } else { errorLog("Field: '" + oUserFieldsMD.Name + "' was added successfuly to " + oUserFieldsMD.TableName + " Table"); } GC.Collect(); } catch (Exception ex) { string err = string.Format("Add Table field: {0}/{1}, Exception: {2}", tablename, fieldname, ex.Message); errorLog(err); if (ex.Message.IndexOf("Ref count") >= 0) { GC.Collect(); } } finally { GC.Collect(); // Release the handle to the User Fields } }
public static bool DIErrorHandler(int lRetCode, string Action, string MsgTitle) { string sErrMsg; int lErrCode; if (lRetCode != 0) { oCompany.GetLastError(out lErrCode, out sErrMsg); return(false); } else { return(true); } }
public void addUDF(string fldTable, string fldName, string fldDesc, SAPbobsCOM.BoFieldTypes sType, int sSize) { SAPbobsCOM.UserFieldsMD oUserFieldsMD = default(SAPbobsCOM.UserFieldsMD); try { oUserFieldsMD = (SAPbobsCOM.UserFieldsMD)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oUserFields); oUserFieldsMD.TableName = fldTable; oUserFieldsMD.Name = fldName; oUserFieldsMD.Description = fldDesc; oUserFieldsMD.Type = sType; oUserFieldsMD.EditSize = sSize; iRetCode = oUserFieldsMD.Add(); //// Check for errors if (iRetCode != 0) { oCompany.GetLastError(out iRetCode, out sErrMsg); } else { //log("Field: '" & oUserFieldsMD.Name & "' was added successfuly to " & oUserFieldsMD.TableName & " Table") } } catch (Exception ex) { throw (ex); } oUserFieldsMD = null; }
public bool UpdateContactName(string bpCardCode, string ctnPrevName, string CtnNewName) { bool bRetVal = false; string sErrMsg; int lErrCode; SAPbobsCOM.Company oCompany = new SAPbobsCOM.Company(); oCompany = SAPDIAPI.Connect(); //Check connection before updating if (oCompany.Connected) { //create the BP object SAPbobsCOM.BusinessPartners BP = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oBusinessPartners); SAPbobsCOM.ContactEmployees sboContacts = BP.ContactEmployees; try { if (BP.GetByKey(bpCardCode)) { sboContacts = BP.ContactEmployees; //check first for one contact (always gives 1 wether have contact or not) check for no contact to add or update if (sboContacts.Count > 0) { for (int i = 0; i < sboContacts.Count; i++) { sboContacts.SetCurrentLine(i); if (sboContacts.Name == ctnPrevName) { bRetVal = true; sboContacts.Name = CtnNewName; } } } if (bRetVal) { if (BP.Update() != 0) { bRetVal = false; oCompany.GetLastError(out lErrCode, out sErrMsg); } } } } catch (Exception ex) { log.Error("Error number: " + ex.HResult + " - " + ex.Message + " - " + ex.Data + " - " + ex.InnerException); } { bRetVal = false; } } oCompany.Disconnect(); return(bRetVal); }
public int Connect() { //pass the stored settings from app.config to a local variable company.Server = ConfigurationManager.AppSettings["server"].ToString(); company.CompanyDB = ConfigurationManager.AppSettings["companydb"].ToString(); company.DbUserName = ConfigurationManager.AppSettings["dbuser"].ToString(); company.DbUserName = ConfigurationManager.AppSettings["dbpass"].ToString(); //change this variable to your enviromen( sql 2012 - 2016) company.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2012; company.UserName = ConfigurationManager.AppSettings["user"].ToString(); company.Password = ConfigurationManager.AppSettings["password"].ToString(); //choose the languge of your sap install (this must match!) company.language = SAPbobsCOM.BoSuppLangs.ln_Dutch; //true = if ssl is enable and not self signed ! company.UseTrusted = false; company.LicenseServer = ConfigurationManager.AppSettings["licenseserver"].ToString(); connectionResult = company.Connect(); if (connectionResult != 0) { //connection has failed ! company.GetLastError(out errorCode, out errorMessage); } return(connectionResult); }
public static void InitializeCompany() { oCompany = new SAPbobsCOM.Company(); oCompany.Server = ConfigurationManager.AppSettings["Server"]; oCompany.language = SAPbobsCOM.BoSuppLangs.ln_English; oCompany.UseTrusted = false; oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_HANADB; oCompany.CompanyDB = ConfigurationManager.AppSettings["CompanyDB"]; oCompany.UserName = ConfigurationManager.AppSettings["UserName"]; oCompany.Password = ConfigurationManager.AppSettings["UserPass"]; oCompany.DbUserName = ConfigurationManager.AppSettings["DbUserName"]; oCompany.DbPassword = ConfigurationManager.AppSettings["DbPassword"]; if (oCompany.Connected == true) { oCompany.Disconnect(); } long lRetCode = oCompany.Connect(); if (lRetCode != 0) { int temp_int = 0; string temp_string = ""; oCompany.GetLastError(out temp_int, out temp_string); Log.WriteLog("InitializeCompany Error: " + temp_string); } }
private static void swProConectarSap() { try { objConexionSap = new SAPbobsCOM.Company() { Server = varServidorSap, DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2014, LicenseServer = varServidorLicencia, CompanyDB = varBaseDatosSap, UserName = varUsuarioSap, Password = varContraseñaSap, DbUserName = varUsuarioBD, DbPassword = varContraseñaBD, UseTrusted = false }; iError = objConexionSap.Connect(); if (iError != 0) { objConexionSap.GetLastError(out iError, out varMensaje); throw new Exception(varMensaje); } } catch (Exception) { throw; } }
//public static bool JEAllocation(string _Branch, string _PayrolPeriod) //{ // string sysDftDBCompany = "DESIHOFC"; // string sysDBUsername = ConfigurationManager.AppSettings["sysSAPUsername"]; // string sysDBPassword = ConfigurationManager.AppSettings["sysSAPPassword"]; // bool isConnected = false; // string _Msg = ""; // oCompany = SAPInitializeConnection(sysDftDBCompany, sysDBUsername, sysDBPassword, out isConnected, out _Msg ); // MessageBox.Show(_Msg); // if (isConnected == true) // { // string _sqlSelect; // DataTable _tblSelect; // _sqlSelect = @" // SELECT A.Account, A.Credit, A.Debit, A.AccountName, A.EmployeeName, A.DocDate // FROM [dbo].[fnSAPTransaction]('" + _Branch + @"','" + _PayrolPeriod + @"') A // "; // _tblSelect = clsSQLClientFunctions.DataList(clsDeclaration.sSystemConnection, _sqlSelect); // string _DocDate = clsSQLClientFunctions.GetData(_tblSelect, "DocDate", "0"); // SAPbobsCOM.JournalEntries _JournalEntries; // _JournalEntries = (SAPbobsCOM.JournalEntries)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oJournalEntries); // _JournalEntries.ReferenceDate = DateTime.Parse(_DocDate); // _JournalEntries.TaxDate = DateTime.Parse(_DocDate); // _JournalEntries.DueDate = DateTime.Parse(_DocDate); // _JournalEntries.Memo = "PAYROLL PERIOD " + _PayrolPeriod + @" FOR " + _Branch; // _JournalEntries.UserFields.Fields.Item("U_NSAPADVISENO").Value = _PayrolPeriod; // foreach (DataRow row in _tblSelect.Rows) // { // { // string _Account = row["Account"].ToString(); // string _Credit = row["Credit"].ToString(); // string _Debit = row["Debit"].ToString(); // string _AccountName = row["AccountName"].ToString(); // string _EmployeeName = row["EmployeeName"].ToString(); // if (_Account.Substring(0,1) == "V") // { // _JournalEntries.Lines.ShortName = _Account; // } // else // { // _JournalEntries.Lines.AccountCode = _Account; // } // _JournalEntries.Lines.LineMemo = _AccountName; // _JournalEntries.Lines.Credit = double.Parse(_Credit); // _JournalEntries.Lines.Debit = double.Parse(_Debit); // _JournalEntries.Lines.UserFields.Fields.Item("U_NSAPADVISENO").Value = _PayrolPeriod; // _JournalEntries.Lines.UserFields.Fields.Item("U_EMPLOYEE").Value = _EmployeeName; // _JournalEntries.Lines.Add(); // } // } // int lRetCode; // string sErrMsg; // int lErrCode; // Application.DoEvents(); // lRetCode = _JournalEntries.Add(); // if (lRetCode != 0) // { // oCompany.GetLastError(out lErrCode, out sErrMsg); // MessageBox.Show(lErrCode + " " + sErrMsg); // return false; // } // else // { // MessageBox.Show("Payroll Successfully Posted"); // return true; // } // oCompany.Disconnect(); // } // else // { // return false; // } //} public static void CreateIncomingPayment(string _Branch, string _PayrolPeriod, int _DocEntry , string _CardCode, string _CardName, string _CashAccount, double _Amount, DateTime _DocDate) { string sysDftDBCompany = "DESIHOFC"; string sysDBUsername = ConfigurationManager.AppSettings["sysSAPUsername"]; string sysDBPassword = ConfigurationManager.AppSettings["sysSAPPassword"]; bool isConnected = false; string _Msg = ""; oCompany = SAPInitializeConnection(sysDftDBCompany, sysDBUsername, sysDBPassword, out isConnected, out _Msg); //MessageBox.Show(_Msg); if (isConnected == true) { SAPbobsCOM.Payments _Payments; _Payments = (SAPbobsCOM.Payments)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oIncomingPayments); _Payments.CardCode = _CardCode; _Payments.CardName = _CardName; _Payments.CashAccount = _CashAccount; _Payments.CashSum = _Amount; _Payments.DocDate = _DocDate; _Payments.JournalRemarks = "Integra Console " + _PayrolPeriod + @" Branch : " + _Branch; _Payments.TaxDate = _DocDate; _Payments.Invoices.DocEntry = _DocEntry; _Payments.Invoices.DocLine = 0; _Payments.Invoices.InvoiceType = SAPbobsCOM.BoRcptInvTypes.it_Invoice; _Payments.Invoices.SumApplied = _Amount; int lRetCode; string sErrMsg; int lErrCode; Application.DoEvents(); lRetCode = _Payments.Add(); if (lRetCode != 0) { oCompany.GetLastError(out lErrCode, out sErrMsg); //MessageBox.Show(lErrCode + " " + sErrMsg); } else { //MessageBox.Show("Payroll Successfully Posted"); } oCompany.Disconnect(); } else { MessageBox.Show(_Msg); } }
private void ConnectSBO(ref int nErr, ref string sErr) { sErr = ""; nErr = 0; Llacolen_SBOService.Properties.Settings.Default.Reload(); // Set connection properties if (Llacolen_SBOService.Properties.Settings.Default.SQLType == 2005) { oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2005; } else if (Llacolen_SBOService.Properties.Settings.Default.SQLType == 2008) { oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2008; } else if (Llacolen_SBOService.Properties.Settings.Default.SQLType == 2012) { oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2012; } else if (Llacolen_SBOService.Properties.Settings.Default.SQLType == 2014) { oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2014; } else if (Llacolen_SBOService.Properties.Settings.Default.SQLType == 2016) { oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2016; } oCompany.Server = Llacolen_SBOService.Properties.Settings.Default.Server; oCompany.UseTrusted = false; oCompany.DbUserName = Llacolen_SBOService.Properties.Settings.Default.DBUserName; oCompany.DbPassword = Llacolen_SBOService.Properties.Settings.Default.DBPassword; oCompany.CompanyDB = Llacolen_SBOService.Properties.Settings.Default.CompanyDB; oCompany.UserName = Llacolen_SBOService.Properties.Settings.Default.UserName; oCompany.Password = Llacolen_SBOService.Properties.Settings.Default.Password; //Try to connect nErr = oCompany.Connect(); if (nErr != 0) // if the connection failed { oCompany.GetLastError(out nErr, out sErr); } else { sErr = "OK"; } oLog.LogMsg("Conexión SBO " + sErr, "F", "I"); }
public static SAPbobsCOM.Company InitializeCompany() { try { //Log.WriteLog("Inicializando conexão com o BD e SAP."); oCompany = new SAPbobsCOM.Company { Server = ConfigurationManager.AppSettings["Server"], language = SAPbobsCOM.BoSuppLangs.ln_English, UseTrusted = false, DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2016, CompanyDB = ConfigurationManager.AppSettings["DataBase"], UserName = ConfigurationManager.AppSettings["SapUser"], Password = ConfigurationManager.AppSettings["SapPassword"], DbUserName = ConfigurationManager.AppSettings["DbUser"], DbPassword = ConfigurationManager.AppSettings["DbPassword"], //LicenseServer = "sapsrv:30000" }; if (oCompany.Connected == true) { oCompany.Disconnect(); } long lRetCode = oCompany.Connect(); if (lRetCode != 0) { int temp_int = 0; string temp_string = ""; oCompany.GetLastError(out temp_int, out temp_string); //Log.WriteLog("InitializeCompany Error: " + temp_string); return(oCompany); } else { //Log.WriteLog("Conexão realizada com sucesso."); return(oCompany); //Inserir na tabela de log } } catch (System.Exception e) { //Log.WriteLog("InitializeCompany Exception: "+e.Message); throw e; } }
public bool manageError(int i, bool showError) { // if errCode is different than 0 an error could occur if (i != 0) { oCompany.GetLastError(out errCode, out errMsg); if (showError) { MessageBox.Show(errCode + " - " + errMsg); } return(false); } return(true); }
public bool connect() { try { oSetupCompany = new SAPbobsCOM.Company(); /* * txtServer.Text = @"SIMON-PC\MSSQL2014"; * txtUser.Text = "sa"; * txtPass.Text = "Hsyhmin1"; * txtSBOPass.Text = "Hsyhmin1"; */ // once the Server property of the Company is set // we may query for a list of companies to choos from // this method returns a Recordset object oSetupCompany.language = SAPbobsCOM.BoSuppLangs.ln_English; oSetupCompany.Server = txtServer; oSetupCompany.CompanyDB = txtDBName; oSetupCompany.DbUserName = txtDBUser; oSetupCompany.DbPassword = txtDBPass; oSetupCompany.UserName = txtSBOUser; oSetupCompany.Password = txtSBOPass; oSetupCompany.LicenseServer = txtLicenseServer; oSetupCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_HANADB; lRetCode = oSetupCompany.Connect(); if (lRetCode != 0) { oSetupCompany.GetLastError(out lErrCode, out sErrMsg); lastError = string.Format("Cannot connect to the company DB.\r\n\r\nLicense Server: {0}\r\nDB Server: {1}\r\nB1 User:{3}\r\nB1 User Pwd:{4}\r\nDB User:{5}\r\nDB User Pwd{6}\r\nError:{2}" , oSetupCompany.LicenseServer, oSetupCompany.Server, sErrMsg , txtSBOUser, txtSBOPass, txtDBUser, txtDBPass); errorLog(lastError); return(false); } else { errorLog("Connected to " + oSetupCompany.CompanyName); return(true); } }catch (Exception ex) { errorLog(ex); } return(false); }
public static SAPbobsCOM.Company SAPConnection(string dftDBName, string SAPUser, string SAPPass, out bool isConnected, out string _ErrorMsg) { int lRetCode; SAPbobsCOM.Company newCompany; newCompany = new SAPbobsCOM.Company(); newCompany.LicenseServer = ConfigurationManager.AppSettings["sysLicenseServer"]; newCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2012; newCompany.Server = ConfigurationManager.AppSettings["sysDBServer"]; newCompany.DbUserName = ConfigurationManager.AppSettings["sysDBUsername"]; newCompany.DbPassword = ConfigurationManager.AppSettings["sysDBPassword"]; //oCompany.CompanyDB = ConfigurationManager.AppSettings["sysDftDBCompany"]; //oCompany.UserName = ConfigurationManager.AppSettings["sysSAPUsername"]; //oCompany.Password = ConfigurationManager.AppSettings["sysSAPPassword"]; newCompany.CompanyDB = dftDBName; newCompany.UserName = SAPUser; newCompany.Password = SAPPass; newCompany.language = SAPbobsCOM.BoSuppLangs.ln_English; lRetCode = newCompany.Connect(); //DIErrorHandler(lRetCode, "Connecting To SAP", "SAP Connection"); string sErrMsg; int lErrCode; if (lRetCode != 0) { newCompany.GetLastError(out lErrCode, out sErrMsg); _ErrorMsg = lErrCode + " " + sErrMsg; isConnected = false; } else { _ErrorMsg = "Conneted To SAP"; isConnected = true; } return(newCompany); //return }
/// <summary> /// Connect only DI Api /// </summary> /// <param name="serverName">SQL Server Name</param> /// <param name="serverType">Server type</param> /// <param name="companyDb"></param> /// <param name="dbUsername"></param> /// <param name="dbPassword"></param> /// <param name="username">SBO Username</param> /// <param name="password">SBO Password</param> /// <param name="licenceServer">Licence Server</param> public static void DiConnect(string serverName, SAPbobsCOM.BoDataServerTypes serverType, string companyDb, string dbUsername = null, string dbPassword = null, string username = null, string password = null, string licenceServer = null) { _diCompany = new SAPbobsCOM.Company { Server = serverName, DbServerType = serverType, CompanyDB = companyDb }; if (licenceServer != null) { _diCompany.LicenseServer = licenceServer; } if (username == null) { _diCompany.UseTrusted = true; } else { _diCompany.UseTrusted = false; _diCompany.UserName = username; _diCompany.Password = password; _diCompany.DbUserName = dbUsername; _diCompany.DbPassword = dbPassword; } var connectResponse = _diCompany.Connect(); if (connectResponse != 0) { int errCode; string errMsg; _diCompany.GetLastError(out errCode, out errMsg); Logger.Debug($"Servername={serverName}, CompanyDb={companyDb}, ServerType={serverType}, " + $"DbUsername={dbUsername}, DbPassword={dbPassword}, " + $"SboUsername={username}, SboPassword={password}, " + $"LicenceServer={licenceServer}"); throw new Exception($"DI Connect Error: {errCode} {errMsg}"); } }
public int Connect() { company.Server = ConfigurationManager.AppSettings["server"].ToString(); company.CompanyDB = ConfigurationManager.AppSettings["companydb"].ToString(); company.DbUserName = ConfigurationManager.AppSettings["dbuser"].ToString(); company.DbPassword = ConfigurationManager.AppSettings["dbpass"].ToString(); company.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2017; company.UserName = ConfigurationManager.AppSettings["user"].ToString(); company.Password = ConfigurationManager.AppSettings["pass"].ToString(); company.language = SAPbobsCOM.BoSuppLangs.ln_Dutch; company.UseTrusted = false; company.LicenseServer = ConfigurationManager.AppSettings["licenseServer"].ToString(); connectionResult = company.Connect(); if (connectionResult != 0) { company.GetLastError(out errorCode, out errorMessage); } return(connectionResult); }
public static void Changer(SAPbobsCOM.Company pCompany, int key, int userID) { SAPbobsCOM.ServiceCalls oServiceCall = (SAPbobsCOM.ServiceCalls)pCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oServiceCalls); oServiceCall.GetByKey(key); oServiceCall.AssigneeCode = userID; int IretCode = oServiceCall.Update(); if (IretCode != 0) { string sErr = ""; pCompany.GetLastError(out IretCode, out sErr); MessageBox.Show(sErr); } }
/// <summary> /// Initialises server settings, sets up connection credentials and attempts /// a new connection to SAP Business One server. /// </summary> /// <returns>Connection result as integer. Returns 0 if connection was successful</returns> public int Connect() { /* * All the server settings and user credentials used below are stored in App.config file. * ConfigurationManager is being used to read the App.config file. * You can store you own settings in App.config or use actual values directly in the code: * company.Server = "sapb1server"; * Example.App.config is included in this project, rename it to App.config and populate it with your own values. */ //Helpers.LogInfo(ConfigurationManager.AppSettings["BusinessOneServer"] + ConfigurationManager.AppSettings["BusinessOneLicenseServer"] + ConfigurationManager.AppSettings["BusinessOneCompanyDb"]); company.Server = ConfigurationManager.AppSettings["BusinessOneServer"]; company.LicenseServer = ConfigurationManager.AppSettings["BusinessOneLicenseServer"]; company.CompanyDB = ConfigurationManager.AppSettings["BusinessOneCompanyDb"]; company.DbServerType = (SAPbobsCOM.BoDataServerTypes)Enum.Parse(typeof(SAPbobsCOM.BoDataServerTypes), ConfigurationManager.AppSettings["BusinessOneDbServerType"]); company.DbUserName = ConfigurationManager.AppSettings["BusinessOneDbUserName"]; company.DbPassword = Helpers.FromBase64(ConfigurationManager.AppSettings["BusinessOneDbPassword"]); company.UserName = ConfigurationManager.AppSettings["BusinessOneUserName"]; company.Password = Helpers.FromBase64(ConfigurationManager.AppSettings["BusinessOnePassword"]); company.language = SAPbobsCOM.BoSuppLangs.ln_English_Gb; company.UseTrusted = Convert.ToBoolean(ConfigurationManager.AppSettings["BusinessOneUseTrusted"]); connectionResult = company.Connect(); if (connectionResult != 0) { company.GetLastError(out errorCode, out errorMessage); //Console.WriteLine("There was an error in Sap connection", errorMessage); } else { Connected = true; //Console.WriteLine("SAP is connected"); } return(connectionResult); }
public static void DIErrHandler(string action) { try { string msg; if (lRetCode == 0) { msg = string.Format("{0} Succeeded", action); } else { oCompany.GetLastError(lErrCode, sErrMsg); msg = string.Format("{0} failed. ErrCode: {1}. ErrMsg: {2}", action, lErrCode, sErrMsg); } MsgBoxWrapper(msg); } catch (Exception ex) { MsgBoxWrapper(ex.Message); } }
public SAP() { string sErrMsg = string.Empty; int iErrCode = 0; try { oCompany = new SAPbobsCOM.Company(); DTsMsSQLInfo DTsSBOInfo = new DTsMsSQLInfo(); DTsSBOInfo.LoadDecryptFile(); DTsSBOInfo DTsSBOInfo2 = new DTsSBOInfo(); DTsSBOInfo2.LoadDecryptFile(); oCompany.Server = DTsSBOInfo.Server; oCompany.language = SAPbobsCOM.BoSuppLangs.ln_English; oCompany.CompanyDB = DTsSBOInfo.DataBase; oCompany.DbUserName = DTsSBOInfo.Sa; oCompany.DbPassword = DTsSBOInfo.Password; oCompany.UseTrusted = DTsSBOInfo2.UseTrusted; oCompany.DbServerType = (SAPbobsCOM.BoDataServerTypes)DTsSBOInfo2.DataBaseType; oCompany.UserName = DTsSBOInfo2.UserName; oCompany.Password = DTsSBOInfo2.Password; oCompany.LicenseServer = DTsSBOInfo2.LicenseServer + ":30000"; iErrCode = oCompany.Connect(); if (iErrCode != 0) { oCompany.GetLastError(out iErrCode, out sErrMsg); throw new Exception(sErrMsg); } } catch (Exception ex) { throw ex; } }
public static void Changer(SAPbobsCOM.Company pCompany, int key, int userID, int statusID, bool first) { SAPbobsCOM.ServiceCalls oServiceCall = (SAPbobsCOM.ServiceCalls)pCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oServiceCalls); oServiceCall.GetByKey(key); var data = new SqlData(); bool validation = false; foreach (var item in data.Requisitions(key)) { if (item.ReqisitionStatus > statusID) { validation = true; } } if (validation) { if (!first) { oServiceCall.UserFields.Fields.Item("U_FirstLocation").Value = oServiceCall.Status; oServiceCall.Status = statusID; } else { oServiceCall.Status = oServiceCall.UserFields.Fields.Item("U_FirstLocation").Value; } oServiceCall.AssigneeCode = userID; int IretCode = oServiceCall.Update(); if (IretCode != 0) { string sErr = ""; pCompany.GetLastError(out IretCode, out sErr); MessageBox.Show(sErr); } } }
public static void Changer(SAPbobsCOM.Company pCompany, int key, int userID, int statusID) { SAPbobsCOM.ServiceCalls oServiceCall = (SAPbobsCOM.ServiceCalls)pCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oServiceCalls); oServiceCall.GetByKey(key); //oServiceCall.Lines.ItemCode = ".001MX1000BF"; //oServiceCall.Lines.Quantity = 1; //oServiceCall.Lines.WarehouseCode = "02"; oServiceCall.Status = statusID; oServiceCall.AssigneeCode = userID; int IretCode = oServiceCall.Update(); if (IretCode != 0) { string sErr = ""; pCompany.GetLastError(out IretCode, out sErr); MessageBox.Show(sErr); } }
private void Form_DataAddAfter(ref SAPbouiCOM.BusinessObjectInfo pVal) { if (((SAPbouiCOM.BusinessObjectInfo)pVal).ActionSuccess) { SAPbobsCOM.Company oCom = ((SAPbobsCOM.Company)(Application.SBO_Application.Company.GetDICompany())); SAPbobsCOM.Recordset oR_RecordSet = (SAPbobsCOM.Recordset)oCom.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset); oR_RecordSet.DoQuery("Select * from [@ADDONCFG]"); string uid = oR_RecordSet.Fields.Item("Code").Value.ToString(); string pwd = oR_RecordSet.Fields.Item("Name").Value.ToString(); //Get ObjectKey has created XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(((SAPbouiCOM.BusinessObjectInfo)pVal).ObjectKey); XmlNodeList nodeList = xmldoc.GetElementsByTagName("DocEntry"); string Object_Key = string.Empty; if (nodeList.Count > 0) { Object_Key = nodeList.Item(0).InnerText; } SqlCommand cmd = null; SqlConnection conn = new SqlConnection(string.Format("Data Source={0}; Initial Catalog={1}; User id={2}; Password={3};", oCom.Server, oCom.CompanyDB, uid, pwd)); //Delete JournalEntry GoodsReceipt PO try { cmd = new SqlCommand("DeleteJournalEntry_GoodReceiptPO", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DocNum", Object_Key); conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception ex) { Application.SBO_Application.MessageBox("Delete JournalEntry GoodsReceipt PO Error: " + ex.Message); } finally { conn.Close(); cmd.Dispose(); } //Get Info From Goods Receipt PO by UI SAPbouiCOM.Form oForm = Application.SBO_Application.Forms.ActiveForm; string p_post_date = ((SAPbouiCOM.EditText)oForm.Items.Item("10").Specific).Value; string p_document_date = ((SAPbouiCOM.EditText)oForm.Items.Item("46").Specific).Value; List <Inventory_Item> Inven_Lst = new List <Inventory_Item>(); oForm.Freeze(true); oForm.PaneLevel = 1; try { SAPbouiCOM.Matrix oMtx = ((SAPbouiCOM.Matrix)oForm.Items.Item("38").Specific); for (int i = 1; i <= oMtx.RowCount; i++) { if (!String.IsNullOrEmpty(((SAPbouiCOM.EditText)oMtx.Columns.Item(3).Cells.Item(i).Specific).Value)) { Inventory_Item tmp = new Inventory_Item(); tmp.Item_No = ((SAPbouiCOM.EditText)oMtx.Columns.Item(3).Cells.Item(i).Specific).Value; double.TryParse(((SAPbouiCOM.EditText)oMtx.Columns.Item(13).Cells.Item(i).Specific).Value, out tmp.Quantity); string tmp_unit_price = ((SAPbouiCOM.EditText)oMtx.Columns.Item(20).Cells.Item(i).Specific).Value.Replace(" VND", ""); if (!String.IsNullOrEmpty(tmp_unit_price)) { double.TryParse(tmp_unit_price.Split(',')[0].Replace('.', ','), out tmp.Unitprice); } tmp.Whse = ((SAPbouiCOM.EditText)oMtx.Columns.Item(32).Cells.Item(i).Specific).Value; Inven_Lst.Add(tmp); } } } catch { } finally { oForm.Freeze(false); } //Using DI Create Goods Receipt SAPbobsCOM.Documents oGrp = (SAPbobsCOM.Documents)oCom.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oInventoryGenEntry); oGrp.DocDate = DateTime.ParseExact(p_document_date, "yyyyMMdd", CultureInfo.InvariantCulture); oGrp.TaxDate = DateTime.ParseExact(p_post_date, "yyyyMMdd", CultureInfo.InvariantCulture); oGrp.Reference2 = Object_Key; int tmp_i = 0; int FixedAsset_Count = 0; foreach (Inventory_Item t in Inven_Lst) { tmp_i++; //string str_query = string.Format("Select count(*) as IsFixedAsset from OITM where ItemCode in (Select U_FA from OITM where ItemCode = '{0}')and ItemType ='F'", t.Item_No); string str_query = string.Format("Select a.ItemCode,a.U_FA,(Select b.ItemType from OITM b where b.ItemCode = a.U_FA) as ItemType, a.ItmsGrpCod,(Select b.ItmsGrpCod from OITM b where b.ItemCode = a.U_FA) as ItmsGrpCod_FA from OITM a where a.U_FA = '{0}'", t.Item_No); oR_RecordSet.DoQuery(str_query); if (oR_RecordSet.RecordCount > 0) { if (oR_RecordSet.Fields.Item("ItemType").Value.ToString() == "F" && ((oR_RecordSet.Fields.Item("ItmsGrpCod").Value.ToString() == "103" && oR_RecordSet.Fields.Item("ItmsGrpCod_FA").Value.ToString() == "103") || (oR_RecordSet.Fields.Item("ItmsGrpCod").Value.ToString() == "105" && oR_RecordSet.Fields.Item("ItmsGrpCod_FA").Value.ToString() == "105"))) { t.FixedAsset_ItemNo = oR_RecordSet.Fields.Item("ItemCode").Value.ToString(); if (!string.IsNullOrEmpty(t.FixedAsset_ItemNo)) { oGrp.Lines.ItemCode = t.FixedAsset_ItemNo; oGrp.Lines.Quantity = t.Quantity; oGrp.Lines.UnitPrice = 0; oGrp.Lines.Price = 0; oGrp.Lines.WarehouseCode = t.Whse; t.LineNum = FixedAsset_Count++; if (tmp_i < Inven_Lst.Count) { oGrp.Lines.Add(); } } } } } if (FixedAsset_Count > 0) { int RetVal = oGrp.Add(); if (RetVal == 0) { string New_Object_Key = oCom.GetNewObjectKey(); //Update Unit Price cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; double receipt_total = 0; //Update IGN1 SQL foreach (Inventory_Item t in Inven_Lst) { if (t.LineNum >= 0) { double tmp_sum = t.Unitprice * t.Quantity; receipt_total += tmp_sum; string update_IGN1_query = string.Format("Update IGN1 set Price={0},LineTotal={1},OpenSum={2},PriceBefDi={3},TotalSumSy={4},OpenSumSys={5},INMPrice={6},StockPrice={7},StockSum={8},StockSumSc={9} where DocEntry={10} and ItemCode='{11}' and LineNum={12};" , t.Unitprice, tmp_sum, tmp_sum, t.Unitprice, tmp_sum, tmp_sum, t.Unitprice, t.Unitprice, tmp_sum, tmp_sum, New_Object_Key, t.FixedAsset_ItemNo, t.LineNum); cmd.CommandText += update_IGN1_query; } } //Update OIGN SQL string update_OIGN_query = string.Format("Update OIGN set DocTotal={0},DocTotalSy={1},Max1099={2} where DocEntry={3};", receipt_total, receipt_total, receipt_total, New_Object_Key); cmd.CommandText += update_OIGN_query; try { cmd.Connection = conn; conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception ex) { Application.SBO_Application.MessageBox(string.Format("Addon: Error when update GoodsRecipt: {0}", ex.Message)); } finally { conn.Close(); cmd.Dispose(); } } else { int ErrCode; string ErrMsg; oCom.GetLastError(out ErrCode, out ErrMsg); Application.SBO_Application.StatusBar.SetText(string.Format("Addon: Failed create Good Receipt from Good Receipt PO: {0}|{1}", ErrCode, ErrMsg), SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Error); } } } }
/// <summary> /// Función que estable conexión con la BD de SAP. /// </summary> /// <returns>Retorna un objeto de tipo SAPbobsCOM.Company si la conexión /// fue realizada de manera exitosa en caso contrario retornara null.</returns> public bool Conectar() { SAPbobsCOM.BoDataServerTypes BDTipo; string BDtype = string.Empty; bool ok = false; try { oCompany = new SAPbobsCOM.Company(); BDTipo = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2005; BDtype = ConfigurationManager.AppSettings["DataServerType"]; switch (BDtype) { case ("SQL_2005"): BDTipo = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2005; break; case ("SQL_2008"): BDTipo = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2008; break; case ("SQL_2012"): BDTipo = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2012; break; case ("SQL_2014"): BDTipo = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2014; break; case ("HANA"): BDTipo = SAPbobsCOM.BoDataServerTypes.dst_HANADB; break; } oCompany.Server = ConfigurationManager.AppSettings["ServerSAP"]; oCompany.CompanyDB = ConfigurationManager.AppSettings["BD"]; oCompany.DbUserName = ConfigurationManager.AppSettings["HanaUser"]; oCompany.DbPassword = ConfigurationManager.AppSettings["HanaPwd"]; if (!ConfigurationManager.AppSettings["LicenseServer"].Equals("")) { oCompany.LicenseServer = ConfigurationManager.AppSettings["LicenseServer"]; } oCompany.UserName = ConfigurationManager.AppSettings["SapUser"]; oCompany.Password = ConfigurationManager.AppSettings["SapPwd"]; oCompany.DbServerType = BDTipo; oCompany.language = SAPbobsCOM.BoSuppLangs.ln_Spanish_La; if (oCompany != null) { oCompany.UseTrusted = false; int Con = oCompany.Connect(); if (Con == 0) { ok = true; } else { oCompany.GetLastError(out intError, out strError); } } } catch (Exception ex) { ok = false; //System.Diagnostics.EventLog.WriteEntry("Application", "Ocurrió el siguiente error: " + ex.Message); } return(ok); }
private void SBO_Application_ItemEvent(string FormUID, ref SAPbouiCOM.ItemEvent pVal, out bool BubbleEvent) { BubbleEvent = true; // SOCIO DE NEGOCIOS if ((pVal.FormType == 134 & pVal.EventType != SAPbouiCOM.BoEventTypes.et_FORM_UNLOAD) & (pVal.Before_Action == true)) { oOrderForm = SBO_Application.Forms.GetFormByTypeAndCount(pVal.FormType, pVal.FormTypeCount); if ((pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_LOAD) & (pVal.BeforeAction == true)) { DibujaItems.BtnCoRuc(oOrderForm); } if (pVal.ItemUID == "btnCRu" & (pVal.EventType == SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED)) { /*VALIDAMOS LICENCIA*/ DateTime dt1, dt2; dt1 = DateTime.Parse("01/01/2021"); dt2 = DateTime.Now; TimeSpan ts = dt2 - dt1; if (ts.Days < 15) { if ((oOrderForm.Mode == SAPbouiCOM.BoFormMode.fm_ADD_MODE)) { try { txtRuc = (SAPbouiCOM.EditText)oOrderForm.Items.Item("41").Specific; oCardType = (SAPbouiCOM.ComboBox)oOrderForm.Items.Item("40").Specific; Ruc = txtRuc.Value; if (Ruc.Length == 11) { oSocioNegocio = new SocioNegocio(); DatosSunat = ClassDatosSN.GetDatosSN(Ruc); oSocioNegocio.CardType = oCardType.Value; // [C] cliente [S] Proveedor oSocioNegocio.ruc = DatosSunat[0]; oSocioNegocio.razonSocial = DatosSunat[1]; oSocioNegocio.estado = DatosSunat[2]; oSocioNegocio.condicion = DatosSunat[3]; oSocioNegocio.direccion = DatosSunat[4]; oSocioNegocio.departamento = DatosSunat[5]; oSocioNegocio.provincia = DatosSunat[6]; oSocioNegocio.distrito = DatosSunat[7]; if (!(SetConnectionContext() == 0)) { SBO_Application.MessageBox("Failed setting a connection to DI API", 1, "Ok", "", ""); System.Environment.Exit(0); // Terminating the Add-On Application } if (!(ConnectToCompany() == 0)) { SBO_Application.MessageBox("Failed connecting to the company's Data Base", 1, "Ok", "", ""); System.Environment.Exit(0); // Terminating the Add-On Application } if (oSocioNegocio.estado == "ACTIVO" && oSocioNegocio.condicion == "HABIDO") { if (SBO_Application.MessageBox("Esta seguro de [Cear] Socio de negocios:" + oSocioNegocio.razonSocial, 2, "Ok", "Cancelar") == 1) { int res = AddSocioNegocioController.CreaSoNe(oCompany, oSocioNegocio); if (res == 0) { SBO_Application.MessageBox("Socio de negocios creado: " + oCompany.CompanyName + Constants.vbNewLine, 1, "Ok", "", ""); oOrderForm.Close(); } else { string LastError = ""; oCompany.GetLastError(out res, out LastError); SBO_Application.MessageBox(res + "-" + LastError); } } } else { if (SBO_Application.MessageBox("El SN: " + oSocioNegocio.razonSocial + "\r\n" + "Estado: " + oSocioNegocio.estado + " Condición: " + oSocioNegocio.condicion + "\r\n" + "Desea crear SN de todas formas?", 2, "Ok", "Cancelar") == 1) { int res = AddSocioNegocioController.CreaSoNe(oCompany, oSocioNegocio); if (res == 0) { SBO_Application.MessageBox("Socio de negocios creado: " + oCompany.CompanyName + Constants.vbNewLine, 1, "Ok", "", ""); oOrderForm.Close(); } else { string LastError = ""; oCompany.GetLastError(out res, out LastError); SBO_Application.MessageBox(res + "-" + LastError); } } } } else { SBO_Application.MessageBox("Nùmero de RUC debe de contener 12 caracteres"); } } catch (Exception ex) { SBO_Application.MessageBox(ex.Message); } } else { SBO_Application.MessageBox("Esta obcion solo esta activada para [Crear] Socio de negocio."); } } else { SBO_Application.MessageBox("Periodo de prueba [terminado]"); } } } }
//private void ListaInter () //{ // try // { // SAPbobsCOM.UserTables tbls = null; // SAPbobsCOM.UserTable tbl = null; // tbls = oCompany.UserTables; // tbl = tbls.Item("FEDIAN_CODDOC"); // tbl.Code = Constants.CodDIAN_01[0]; // tbl.Name = Constants.CodDIAN_01[1]; // lRetCode = tbl.Add(); // if (lRetCode != 0) // { // if (lRetCode == -1 || lRetCode == -2035 || lRetCode == -5002) // { } // else // { // oCompany.GetLastError(out lRetCode, out sErrMsg); // Procesos.EscribirLogFileTXT("PreCarga: " + lRetCode + " > " + sErrMsg); // } // } // tbl.Code = Constants.CodDIAN_02[0]; // tbl.Name = Constants.CodDIAN_02[1]; // lRetCode = tbl.Add(); // if (lRetCode != 0) // { // if (lRetCode == -1 || lRetCode == -2035 || lRetCode == -5002) // { } // else // { // oCompany.GetLastError(out lRetCode, out sErrMsg); // Procesos.EscribirLogFileTXT("PreCarga: " + lRetCode + " > " + sErrMsg); // } // } // tbl.Code = Constants.CodDIAN_03[0]; // tbl.Name = Constants.CodDIAN_03[1]; // lRetCode = tbl.Add(); // if (lRetCode != 0) // { // if (lRetCode == -1 || lRetCode == -2035 || lRetCode == -5002) // { } // else // { // oCompany.GetLastError(out lRetCode, out sErrMsg); // Procesos.EscribirLogFileTXT("PreCarga: " + lRetCode + " > " + sErrMsg); // } // } // tbl.Code = Constants.CodDIAN_04[0]; // tbl.Name = Constants.CodDIAN_04[1]; // lRetCode = tbl.Add(); // if (lRetCode != 0) // { // if (lRetCode == -1 || lRetCode == -2035 || lRetCode == -5002) // { } // else // { // oCompany.GetLastError(out lRetCode, out sErrMsg); // Procesos.EscribirLogFileTXT("PreCarga: " + lRetCode + " > " + sErrMsg); // } // } // tbl.Code = Constants.CodDIAN_05[0]; // tbl.Name = Constants.CodDIAN_05[1]; // lRetCode = tbl.Add(); // if (lRetCode != 0) // { // if (lRetCode == -1 || lRetCode == -2035 || lRetCode == -5002) // { } // else // { // oCompany.GetLastError(out lRetCode, out sErrMsg); // Procesos.EscribirLogFileTXT("PreCarga: " + lRetCode + " > " + sErrMsg); // } // } // } // catch (Exception ex) // { // Procesos.EscribirLogFileTXT("CargueInicial: " + ex.Message); // } //} //private void cfgInter () //{ // string urlFebos = ""; // urlFebos = "https://api.febos.co/pruebas/documentos?simular=no&debug=si&tipo={0}&entrada=txt&foliar=si&firmar=si&obtenerXml=si&obtenerPdf=si"; // try // { // SAPbobsCOM.UserTables tbls = null; // SAPbobsCOM.UserTable tbl = null; // tbls = oCompany.UserTables; // tbl = tbls.Item("FEDIAN_INTERF_CFG"); // tbl.Code = "1"; // tbl.Name = "Factura de Venta"; // tbl.UserFields.Fields.Item("U_WS_Activo").Value = "Y"; // tbl.UserFields.Fields.Item("U_Job_Activo").Value = "Y"; // tbl.UserFields.Fields.Item("U_URL").Value = string.Format(urlFebos, tbl.Code); // lRetCode = tbl.Add(); // if (lRetCode != 0) // { // if (lRetCode == -1 || lRetCode == -2035 || lRetCode == -5002) // { } // else // { // oCompany.GetLastError(out lRetCode, out sErrMsg); // Procesos.EscribirLogFileTXT("PreCarga: " + lRetCode + " > " + sErrMsg); // } // } // tbl.Code = "2"; // tbl.Name = "Factura de Exportacion"; // tbl.UserFields.Fields.Item("U_WS_Activo").Value = "Y"; // tbl.UserFields.Fields.Item("U_Job_Activo").Value = "Y"; // tbl.UserFields.Fields.Item("U_URL").Value = string.Format(urlFebos, tbl.Code); // lRetCode = tbl.Add(); // if (lRetCode != 0) // { // if (lRetCode == -1 || lRetCode == -2035 || lRetCode == -5002) // { } // else // { // oCompany.GetLastError(out lRetCode, out sErrMsg); // Procesos.EscribirLogFileTXT("PreCarga: " + lRetCode + " > " + sErrMsg); // } // } // tbl.Code = "3"; // tbl.Name = "Factura de Contingencia"; // tbl.UserFields.Fields.Item("U_WS_Activo").Value = "Y"; // tbl.UserFields.Fields.Item("U_Job_Activo").Value = "Y"; // tbl.UserFields.Fields.Item("U_URL").Value = string.Format(urlFebos, tbl.Code); // lRetCode = tbl.Add(); // if (lRetCode != 0) // { // if (lRetCode == -1 || lRetCode == -2035 || lRetCode == -5002) // { } // else // { // oCompany.GetLastError(out lRetCode, out sErrMsg); // Procesos.EscribirLogFileTXT("PreCarga: " + lRetCode + " > " + sErrMsg); // } // } // tbl.Code = "4"; // tbl.Name = "Nota de Credito"; // tbl.UserFields.Fields.Item("U_WS_Activo").Value = "Y"; // tbl.UserFields.Fields.Item("U_Job_Activo").Value = "Y"; // tbl.UserFields.Fields.Item("U_URL").Value = string.Format(urlFebos, tbl.Code); // lRetCode = tbl.Add(); // if (lRetCode != 0) // { // if (lRetCode == -1 || lRetCode == -2035 || lRetCode == -5002) // { } // else // { // oCompany.GetLastError(out lRetCode, out sErrMsg); // Procesos.EscribirLogFileTXT("PreCarga: " + lRetCode + " > " + sErrMsg); // } // } // tbl.Code = "5"; // tbl.Name = "Nota de Debito"; // tbl.UserFields.Fields.Item("U_WS_Activo").Value = "Y"; // tbl.UserFields.Fields.Item("U_Job_Activo").Value = "Y"; // tbl.UserFields.Fields.Item("U_URL").Value = string.Format(urlFebos, tbl.Code); // lRetCode = tbl.Add(); // if (lRetCode != 0) // { // if (lRetCode == -1 || lRetCode == -2035 || lRetCode == -5002) // { } // else // { // oCompany.GetLastError(out lRetCode, out sErrMsg); // Procesos.EscribirLogFileTXT("PreCarga: " + lRetCode + " > " + sErrMsg); // } // } // tbl.Code = "6"; // tbl.Name = "Lectura de Respuesta DIAN"; // tbl.UserFields.Fields.Item("U_WS_Activo").Value = "Y"; // tbl.UserFields.Fields.Item("U_Job_Activo").Value = "Y"; // tbl.UserFields.Fields.Item("U_URL").Value = Constants.urlstatusFebos; // lRetCode = tbl.Add(); // if (lRetCode != 0) // { // if (lRetCode == -1 || lRetCode == -2035 || lRetCode == -5002) // { } // else // { // oCompany.GetLastError(out lRetCode, out sErrMsg); // Procesos.EscribirLogFileTXT("PreCarga: " + lRetCode + " > " + sErrMsg); // } // } // tbl.Code = "7"; // tbl.Name = "Lectura por Folio"; // tbl.UserFields.Fields.Item("U_WS_Activo").Value = "Y"; // tbl.UserFields.Fields.Item("U_Job_Activo").Value = "Y"; // tbl.UserFields.Fields.Item("U_URL").Value = Constants.urlstatusFolio; // lRetCode = tbl.Add(); // if (lRetCode != 0) // { // if (lRetCode == -1 || lRetCode == -2035 || lRetCode == -5002) // { } // else // { // oCompany.GetLastError(out lRetCode, out sErrMsg); // Procesos.EscribirLogFileTXT("PreCarga: " + lRetCode + " > " + sErrMsg); // } // } // } // catch (Exception ex) // { // Procesos.EscribirLogFileTXT("PreCarga: " + ex.Message); // } //} public static bool version(SAPbobsCOM.Company oCmpn) { try { System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); string version = fvi.FileVersion; bool resultado; SAPbobsCOM.UserTables tbls = null; SAPbobsCOM.UserTable tbl = null; tbls = oCmpn.UserTables; tbl = tbls.Item("FEDIAN_VERSION"); if (tbl.GetByKey("1") == true & tbl.Name == version) { resultado = false; } else if (tbl.GetByKey("1") == true & tbl.Name != version) { resultado = true; tbl.Name = version; lRetCode = tbl.Update(); if (lRetCode != 0) { if (lRetCode == -1 || lRetCode == -2035 || lRetCode == -5002) { } else { oCmpn.GetLastError(out lRetCode, out sErrMsg); Procesos.EscribirLogFileTXT("PreCarga: " + lRetCode + " > " + sErrMsg); } } } else { resultado = true; tbl.Code = "1"; tbl.Name = version; lRetCode = tbl.Add(); if (lRetCode != 0) { if (lRetCode == -1 || lRetCode == -2035 || lRetCode == -5002) { } else { oCmpn.GetLastError(out lRetCode, out sErrMsg); Procesos.EscribirLogFileTXT("PreCarga: " + lRetCode + " > " + sErrMsg); } } } return(resultado); } catch (Exception ex) { Procesos.EscribirLogFileTXT("Version: " + ex.Message); return(true); } }
public static SAPCompany InitializeCompany(DTO.SAPConnection connection, out string errorMessage) { try { errorMessage = ""; SAPCompany company = new SAPCompany(); // ' Step 1 // ' Initialize the Company Object. // ' You must create this first to enable connection to the company database. Company = new SAPbobsCOM.Company(); // ' Step 2 // ' Set the mandatory connection properties. Company.Server = connection.SERVER; // ' Name of the DB Server Company.CompanyDB = connection.DB_NAME; // ' Enter the name of your company Company.UserName = connection.USERNAME; // ' Enter the B1 user name Company.Password = connection.PASSWORD; // ' Enter the B1 password Company.language = SAPbobsCOM.BoSuppLangs.ln_English; Company.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2014; if (string.IsNullOrEmpty(connection.LICENSE_SERVER) == false) { Company.LicenseServer = connection.LICENSE_SERVER; } // ' Step 3 // ' Use Windows authentication for database server. // ' True for NT server authentication, // ' False for database server authentication. Company.UseTrusted = connection.UseTrusted; if (!connection.UseTrusted) { Company.DbUserName = connection.DB_USERNAME; Company.DbPassword = connection.DB_PASSWORD; } // ' Step 4 // ' Log on SAP Business One database. // ' Check result code. // ' To continue, the result code must be 0. // ' Otherwise, check the error code and its related error message. if (Company.Connect() != 0) { int code = 0; errorMessage = ""; Company.GetLastError(out code, out errorMessage); errorMessage = "Unable to Log on to SAP Business One database " + Environment.NewLine + String.Format("Error Code : {0} ", code) + Environment.NewLine + String.Format("Error Message : {0} ", errorMessage); return(null); } return(company); } catch (Exception) { throw; } }
public static bool JEAllocation(string _Branch, string _PayrolPeriod) { string sysDftDBCompany = ConfigurationManager.AppSettings["sysDftDBCompany"]; string sysDBUsername = ConfigurationManager.AppSettings["sysSAPUsername"]; string sysDBPassword = ConfigurationManager.AppSettings["sysSAPPassword"]; bool isConnected = false; string _Msg = ""; oCompany = SAPConnection(sysDftDBCompany, sysDBUsername, sysDBPassword, out isConnected, out _Msg); MessageBox.Show(_Msg); if (isConnected == true) { string _sqlSelect; DataTable _tblSelect; _sqlSelect = @" SELECT A.Account, A.Credit, A.Debit, A.AccountName, A.EmployeeName, A.DocDate FROM [dbo].[fnSAPTransaction]('" + _Branch + @"','" + _PayrolPeriod + @"') A "; _tblSelect = clsSQLClientFunctions.DataList(clsDeclaration.sSystemConnection, _sqlSelect); string _DocDate = clsSQLClientFunctions.GetData(_tblSelect, "DocDate", "0"); SAPbobsCOM.JournalEntries _JournalEntries; _JournalEntries = (SAPbobsCOM.JournalEntries)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oJournalEntries); _JournalEntries.ReferenceDate = DateTime.Parse(_DocDate); _JournalEntries.TaxDate = DateTime.Parse(_DocDate); _JournalEntries.DueDate = DateTime.Parse(_DocDate); _JournalEntries.Memo = "PAYROLL PERIOD " + _PayrolPeriod + @" FOR " + _Branch; _JournalEntries.UserFields.Fields.Item("U_NSAPADVISENO").Value = _PayrolPeriod; foreach (DataRow row in _tblSelect.Rows) { { string _Account = row["Account"].ToString(); string _Credit = row["Credit"].ToString(); string _Debit = row["Debit"].ToString(); string _AccountName = row["AccountName"].ToString(); string _EmployeeName = row["EmployeeName"].ToString(); if (_Account.Substring(0, 1) == "V") { _JournalEntries.Lines.ShortName = _Account; } else { _JournalEntries.Lines.AccountCode = _Account; } _JournalEntries.Lines.LineMemo = _AccountName; _JournalEntries.Lines.Credit = double.Parse(_Credit); _JournalEntries.Lines.Debit = double.Parse(_Debit); _JournalEntries.Lines.UserFields.Fields.Item("U_NSAPADVISENO").Value = _PayrolPeriod; _JournalEntries.Lines.UserFields.Fields.Item("U_EMPLOYEE").Value = _EmployeeName; _JournalEntries.Lines.Add(); } } int lRetCode; string sErrMsg; int lErrCode; Application.DoEvents(); lRetCode = _JournalEntries.Add(); if (lRetCode != 0) { oCompany.GetLastError(out lErrCode, out sErrMsg); MessageBox.Show(lErrCode + " " + sErrMsg); return(false); } else { MessageBox.Show("Payroll Successfully Posted"); return(true); } //oCompany.Disconnect(); } else { return(false); } }
public void CrearPedido(SAPbobsCOM.Documents oDoc, string nro_comprobante, int Respuesta, string MsgErrSBO, string identi, bool esPedido, bool creditoOK, bool stockOK, bool precioOK, string almacen, int listaPrecio) { DBOracle consultas = new DBOracle(ServerOracle, UserOracle, PassOracle); DBOracle dbOracleUpdate = new DBOracle(ServerOracle, UserOracle, PassOracle); SAPbobsCOM.Recordset oRecordset = null; oRecordset = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset); string empresa = string.Empty; string empresaSAp = ""; string nroPedido = ""; int filas = 0; if (esPedido) { oDoc = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oOrders); } else { oDoc = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oQuotations); } //oRecordset.DoQuery(ConsultasSap.GetCardCode(dbOracleCab.oDataReader["ruc"].ToString())); //if (oRecordset.RecordCount > 0) //{ // oDoc.CardCode = oRecordset.Fields.Item("CardCode").Value.ToString(); //} empresa = dbOracleCab.oDataReader["cod_empresa"].ToString(); consultas.EjecutaSQL(ConsultasOracle.EmpresaEquivalencia(empresa)); if (consultas.oDataReader.Read()) { oDoc.BPL_IDAssignedToInvoice = Convert.ToInt32(consultas.oDataReader["codEmpresaSAP"].ToString()); empresaSAp = consultas.oDataReader["codEmpresaSAP"].ToString(); } consultas.EjecutaSQL(ConsultasOracle.EmpleadoEquivalencia(dbOracleCab.oDataReader["cod_cliente"].ToString(), empresaSAp)); if (consultas.oDataReader.Read()) { oDoc.CardCode = consultas.oDataReader["codCliente"].ToString(); } oDoc.DocDate = Convert.ToDateTime(dbOracleCab.oDataReader["fec_comprobante"].ToString()); oDoc.DocDueDate = Convert.ToDateTime(dbOracleCab.oDataReader["fec_comprobante"].ToString()); //oDoc.SalesPersonCode = Convert.ToInt32(dbOracleCab.oDataReader["cod_vendedor"].ToString()); consultas.EjecutaSQL(ConsultasOracle.CondicionVentaEquivalencia(empresa, dbOracleCab.oDataReader["cod_condicion_venta"].ToString())); if (consultas.oDataReader.Read()) { oDoc.PaymentGroupCode = Convert.ToInt32(consultas.oDataReader["codCondicionSAP"].ToString()); } consultas.EjecutaSQL(ConsultasOracle.MonedaEquivalencia(dbOracleCab.oDataReader["cod_moneda"].ToString())); if (consultas.oDataReader.Read()) { oDoc.DocCurrency = consultas.oDataReader["codMonedaSAP"].ToString(); } if (!dbOracleCab.oDataReader["tip_cambio"].ToString().Equals("")) { oDoc.DocRate = Convert.ToDouble(dbOracleCab.oDataReader["tip_cambio"].ToString()); } //oDoc.DocumentStatus = SAPbobsCOM.BoStatus.bost_Open;// dbOracleCab.oDataReader["estado"].ToString(); oDoc.Comments = dbOracleCab.oDataReader["comentario"].ToString(); oDoc.FederalTaxID = dbOracleCab.oDataReader["ruc"].ToString(); oDoc.Address = dbOracleCab.oDataReader["dir_cliente"].ToString(); //oDoc.DocTotal = Convert.ToDouble(dbOracleCab.oDataReader["monto_total"].ToString()); nroPedido = dbOracleCab.oDataReader["tip_comprobante"].ToString() + "-" + dbOracleCab.oDataReader["ser_comprobante"].ToString() + "-" + dbOracleCab.oDataReader["nro_comprobante"].ToString(); oDoc.UserFields.Fields.Item("U_Tipo").Value = dbOracleCab.oDataReader["tip_comprobante"].ToString(); oDoc.UserFields.Fields.Item("U_Serie").Value = dbOracleCab.oDataReader["ser_comprobante"].ToString(); oDoc.UserFields.Fields.Item("U_Numero").Value = dbOracleCab.oDataReader["nro_comprobante"].ToString(); oDoc.UserFields.Fields.Item("U_cod_provincia").Value = dbOracleCab.oDataReader["cod_provincia"].ToString(); oDoc.UserFields.Fields.Item("U_cod_ciudad").Value = dbOracleCab.oDataReader["cod_ciudad"].ToString(); oDoc.UserFields.Fields.Item("U_enviar_ypane").Value = dbOracleCab.oDataReader["enviar_ypane"].ToString(); oDoc.UserFields.Fields.Item("U_wms_preparado").Value = dbOracleCab.oDataReader["wms_preparado"].ToString(); oDoc.UserFields.Fields.Item("U_wms_id_transaccion").Value = dbOracleCab.oDataReader["wms_id_transaccion"].ToString(); oDoc.UserFields.Fields.Item("U_control").Value = dbOracleCab.oDataReader["solo_credito"].ToString(); string origen = ""; if (dbOracleCab.oDataReader["origen"].ToString().Equals("")) { origen = "CAST"; } else { origen = "INVENTIVA"; } oDoc.UserFields.Fields.Item("U_DocOrigen").Value = origen; if (!creditoOK) { oDoc.UserFields.Fields.Item("U_LimiCrediVal").Value = "S"; } if (!stockOK) { oDoc.UserFields.Fields.Item("U_StockVal").Value = "S"; } if (!precioOK) { oDoc.UserFields.Fields.Item("U_PrecioVal").Value = "S"; } oDoc.DocType = SAPbobsCOM.BoDocumentTypes.dDocument_Items; dbOracleDet = new DBOracle(ServerOracle, UserOracle, PassOracle); int i = 0; if (dbOracleDet.EjecutaSQL(ConsultasOracle.GetPedidosDet(nro_comprobante))) { while (dbOracleDet.oDataReader.Read()) { oDoc.Lines.ItemCode = dbOracleDet.oDataReader["cod_articulo"].ToString(); oDoc.Lines.Quantity = Convert.ToDouble(dbOracleDet.oDataReader["cantidad"].ToString()); oDoc.Lines.UnitPrice = Convert.ToDouble(dbOracleDet.oDataReader["precio_unitario"].ToString()); oDoc.Lines.TaxCode = "IVA_10"; if (!stockOK && !precioOK) { double cantidad = 0; double precio = 0; oRecordset.DoQuery(ConsultasSap.GetItemStock(oDoc.Lines.ItemCode, almacen)); if (oRecordset.RecordCount > 0) { if (oDoc.Lines.Quantity > Convert.ToDouble(oRecordset.Fields.Item("Stock").Value.ToString())) { cantidad = Convert.ToDouble(oRecordset.Fields.Item("Stock").Value.ToString()); } } oRecordset.DoQuery(ConsultasSap.GetPrecioLista(oDoc.Lines.ItemCode, listaPrecio)); if (oRecordset.RecordCount > 0) { if (oDoc.Lines.UnitPrice < Convert.ToDouble(oRecordset.Fields.Item("Price").Value.ToString())) { precio = Convert.ToDouble(oRecordset.Fields.Item("Price").Value.ToString()); } } oDoc.Lines.UserFields.Fields.Item("U_MotivoOferta").Value = String.Format("Cantidad solicitada: {0}, disponible: {1}. Precio venta: {2}, lista: {3}.", oDoc.Lines.Quantity, cantidad, oDoc.Lines.UnitPrice, precio); } else { if (!stockOK) { oRecordset.DoQuery(ConsultasSap.GetItemStock(oDoc.Lines.ItemCode, almacen)); if (oRecordset.RecordCount > 0) { if (oDoc.Lines.Quantity > Convert.ToDouble(oRecordset.Fields.Item("Stock").Value.ToString())) { oDoc.Lines.UserFields.Fields.Item("U_MotivoOferta").Value = String.Format("Cantidad solicitada ({0}) supera el stock disponible ({1}).", oDoc.Lines.Quantity, Convert.ToDouble(oRecordset.Fields.Item("Stock").Value.ToString())); } } } if (!precioOK) { oRecordset.DoQuery(ConsultasSap.GetPrecioLista(oDoc.Lines.ItemCode, listaPrecio)); if (oRecordset.RecordCount > 0) { if (oDoc.Lines.UnitPrice < Convert.ToDouble(oRecordset.Fields.Item("Price").Value.ToString())) { oDoc.Lines.UserFields.Fields.Item("U_MotivoOferta").Value = String.Format("Precio de venta ({0}) es menor al de la lista de precio predeterminada ({1}).", oDoc.Lines.UnitPrice, Convert.ToDouble(oRecordset.Fields.Item("Price").Value.ToString())); } } } } oDoc.Lines.SetCurrentLine(i); oDoc.Lines.Add(); i++; } } Respuesta = oDoc.Add(); if (Respuesta != 0) { oCompany.GetLastError(out Respuesta, out MsgErrSBO); CrearRegistroLog(Respuesta.ToString(), MsgErrSBO, nro_comprobante); filas = 0; dbOracleUpdate.EjecutaSQL(ConsultasOracle.UpdatePedidoCab(nro_comprobante), ref filas); filas = 0; dbOracleUpdate.EjecutaSQL(ConsultasOracle.UpdatePedidoDet(nro_comprobante), ref filas); WriteErrorLog("CrearPedido:" + nroPedido + " Error: " + Respuesta + " " + MsgErrSBO); } else { identi = oCompany.GetNewObjectKey(); dbOracleUpdate.EjecutaSQL(ConsultasOracle.UpdatePedidoCab(nro_comprobante), ref filas); filas = 0; dbOracleUpdate.EjecutaSQL(ConsultasOracle.UpdatePedidoDet(nro_comprobante), ref filas); } dbSap.LiberarObjeto(oRecordset); }