Exemple #1
0
        public static void Main(string[] args)
        {
            Company company = SAPHelper.GetCompany();

            if (company.Connected)
            {
                company.Disconnect();
            }
            int result = company.Connect();

            if (result != 0)
            {
                company.GetLastError(out ERROR_CODE, out ERROR_MESSAGE);
                Console.Error.Write($"({ERROR_CODE})-{ERROR_MESSAGE}");
                Console.Read();
                Environment.Exit(ERROR_CODE);
            }

            var udoManager = (FormattedSearches)company.GetBusinessObject(BoObjectTypes.oFormattedSearches);
            var oRecordSet = (Recordset)company.GetBusinessObject(BoObjectTypes.BoRecordset);

            oRecordSet.DoQuery("select FRQ.IndexID, QRY.IntrnalKey, CAT.CategoryId from OQCN CAT, OUQR QRY, CSHS FRQ where CAT.CategoryId = QRY.QCategory and QRY.IntrnalKey = FRQ.QueryId and CAT.CatName like '%BPVS - Producción Agrícola%'");
            while (!oRecordSet.EoF)
            {
                int mappedIndexForm = int.Parse(oRecordSet.Fields.Item("IndexID").Value.ToString());
                if (!udoManager.GetByKey(mappedIndexForm))
                {
                    Console.WriteLine("Don't exists the match between UDO form and query");
                    continue;
                }
                Console.WriteLine("Removing match between UDO form and query: {0}", udoManager.Remove() == 0);
                oRecordSet.MoveNext();
            }
            oRecordSet.MoveFirst();
            var userQueries = (UserQueries)company.GetBusinessObject(BoObjectTypes.oUserQueries);

            while (!oRecordSet.EoF)
            {
                int queryId    = int.Parse(oRecordSet.Fields.Item("IntrnalKey").Value.ToString());
                int categoryId = int.Parse(oRecordSet.Fields.Item("CategoryId").Value.ToString());
                if (!userQueries.GetByKey(queryId, categoryId))
                {
                    Console.Error.WriteLine("Don't exists the query");
                    continue;
                }
                Console.WriteLine("Removing the query: {0}", userQueries.Remove() == 0);
                oRecordSet.MoveNext();
            }
            Console.WriteLine("Finish process, press any key");
            Console.Read();
            company.Disconnect();
        }
Exemple #2
0
 internal static void LogOff()
 {
     if (b1Connected)
     {
         company.Disconnect();
     }
 }
Exemple #3
0
        public static void Release(string Servername, string Dbuser, string Dbpassword, string SAPDBName, string SAPUser, string SAPUserPassword, string SAPLicense)
        {
            try
            {
                SAPbobsCOM.Company oCompany = new SAPbobsCOM.Company();

                oCompany.DbServerType  = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2014;
                oCompany.Server        = Servername;
                oCompany.DbUserName    = Dbuser;
                oCompany.DbPassword    = Dbpassword;
                oCompany.CompanyDB     = SAPDBName;
                oCompany.UserName      = SAPUser;
                oCompany.Password      = SAPUserPassword;
                oCompany.LicenseServer = SAPLicense;

                if (oCompany.Connected)
                {
                    oCompany.Disconnect();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 void FinalizarSAPCómpany()
 {
     try
     {
         oCompany.Disconnect();
     }
     catch (Exception Ex)
     {
         throw Ex;
     }
 }
Exemple #5
0
 public void disconnect()
 {
     try
     {
         oCompany.Disconnect();
     }
     catch (Exception e)
     {
         SB1ControlException.SB1ControlException.Save(e);
     }
 }
 private static void Disconnect()
 {
     try
     {
         if (_diCompany.Connected)
         {
             _diCompany.Disconnect();
         }
     }
     finally
     {
         _diCompany   = null;
         _application = null;
     }
 }
Exemple #7
0
 public void ExitAddon()
 {
     try
     {
         //Process p = Process.GetProcessesByName(AppDomain);
         Log.Logger.getInstance().Prepared = false;
         oCompany.Disconnect();
         oApp     = null;
         oCompany = null;
     }
     catch (Exception e)
     {
         SB1ControlException.SB1ControlException.Save(e);
     }
 }
Exemple #8
0
 /// <summary>
 /// Se desconecta de SAP
 /// </summary>
 public void DesconectarSAP()
 {
     try
     {
         if (_oCompany.Connected)
         {
             if (!_oCompany.InTransaction)
             {
                 _oCompany.Disconnect();
             }
         }
     }
     catch (Exception ex)
     {
         throw new Exception("Error al desconectar SAP: " + ex);
     }
 }
Exemple #9
0
 internal static void LogOff()
 {
     if (b1Connected)
     {
         company.Disconnect();
         if (company != null)
         {
             System.Runtime.InteropServices.Marshal.ReleaseComObject(company);
             company = null;
         }
         if (application != null)
         {
             System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
             application = null;
         }
         b1Connected = false;
     }
 }
Exemple #10
0
 public void salirAddon()
 {
     try
     {
         if (oCompany != null)
         {
             if (oCompany.Connected == true)
             {
                 oCompany.Disconnect();
             }
         }
         Application.Exit();
     }
     catch (Exception ex)
     {
         Application.Exit();
     }
 }
Exemple #11
0
        private int SetConnectionContext()
        {
            int    setConnectionContextReturn = 0;
            string sCookie = null;

            _oCompany               = new SAPbobsCOM.Company();
            _oCompany.Server        = UserSettings.SERVERNAME; //"vm-lmk-saptsent";
            _oCompany.language      = SAPbobsCOM.BoSuppLangs.ln_German;
            _oCompany.DbServerType  = BoDataServerTypes.dst_MSSQL2008;
            _oCompany.LicenseServer = UserSettings.SERVERNAME + ":30000";
            _oCompany.UseTrusted    = false;
            _oCompany.CompanyDB     = UserSettings.COMPANYDB;    //"DFE_20170803";
            _oCompany.UserName      = UserSettings.USERNAME;     //"manager";
            _oCompany.Password      = UserSettings.USERPASSWORD; //"U1Iir23B";
            sCookie = _oCompany.GetContextCookie();
            if (_oCompany.Connected == true)
            {
                _oCompany.Disconnect();
            }
            return(setConnectionContextReturn);
        }
Exemple #12
0
        private int SetConnectionContext()
        {
            String sCookie;
            String sConnectionContext;

            try
            {
                oCompany           = new SAPbobsCOM.Company();
                sCookie            = oCompany.GetContextCookie();
                sConnectionContext = oApplication.Company.GetConnectionContext(sCookie);
                if (oCompany.Connected)
                {
                    oCompany.Disconnect();
                }
                return(oCompany.SetSboLoginContext(sConnectionContext));
            }
            catch (Exception ex)
            {
                oApplication.StatusBar.SetText(ex.Message, SAPbouiCOM.BoMessageTime.bmt_Short, SAPbouiCOM.BoStatusBarMessageType.smt_Error);
            }
            return(1);
        }
Exemple #13
0
 public void CloseConnection()
 {
     _oCompany.Disconnect();
     _isConnected = false;
 }
Exemple #14
0
 public void CloseConnection()
 {
     sboCompany.Disconnect();
 }
Exemple #15
0
        private void button2_Click(object sender, EventArgs e)
        {
            labelConnLiber.Text = String.Empty;

            labelConnSAP.Refresh();
            labelConnSAP.Text      = "Conectando...";
            labelConnSAP.ForeColor = Color.Gray;
            labelConnSAP.Refresh();

            SAPbobsCOM.Company oCompany = null;

            int    retCode = -1;
            string strMsg;

            try
            {
                oCompany        = new SAPbobsCOM.Company();
                oCompany.Server = textBoxServerName.Text;
                //oCompany.LicenseServer = textBoxServerName.Text;
                oCompany.CompanyDB  = textBoxDBName.Text;
                oCompany.language   = SAPbobsCOM.BoSuppLangs.ln_English;
                oCompany.UseTrusted = false;

                switch (comboBox1.Text)
                {
                case "dst_MSSQL": oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL; break;

                case "dst_DB_2": oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_DB_2; break;

                case "dst_SYBASE": oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_SYBASE; break;

                case "dst_MSSQL2005": oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2005; break;

                case "dst_MAXDB": oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MAXDB; 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_HANADB": oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_HANADB; break;

                case "dst_MSSQL2016": oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2016; break;

                case "dst_MSSQL2017": oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2017; break;

                default:
                    oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2017;;
                    break;
                }
                //oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2016;
                //dst_MSSQL;//1
                //dst_DB_2;//2
                //dst_SYBASE;//3
                //dst_MSSQL2005;//4
                //dst_MAXDB;//5
                //dst_MSSQL2008;//6
                //dst_MSSQL2012;//7
                //dst_MSSQL2014;//8
                //dst_HANADB;//9
                //dst_MSSQL2016;//10
                ////dst_MSSQL2017;//11
                //oCompany.SLDServer = "172.16.0.4";
                //oCompany.LicenseServer = "SAP-SERVER";
                oCompany.DbUserName = textBoxDBID.Text;
                oCompany.DbPassword = textBoxDBPass.Text;

                oCompany.UserName   = textBoxSAPUser.Text;
                oCompany.Password   = textBoxSAPPass.Text;
                oCompany.UseTrusted = false;

                retCode = oCompany.Connect();

                if (retCode != 0)
                {
                    strMsg                 = oCompany.GetLastErrorDescription();
                    labelConnSAP.Text      = strMsg;
                    labelConnSAP.ForeColor = Color.Red;
                    MessageBox.Show(strMsg);
                }
                else
                {
                    labelConnSAP.Text      = "Conectando a " + oCompany.CompanyName;
                    labelConnSAP.ForeColor = Color.Green;
                    button1.BackColor      = Color.Green;

                    oCompany.Disconnect();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                labelConnSAP.Text      = ex.Message;
                labelConnSAP.ForeColor = Color.Red;
            }
        }
Exemple #16
0
        public bool ExportPayments(/*DateTime lasttime*/)
        {
            MyLogger.Log("Exportando títulos...");
            try
            {
                SAPbobsCOM.Recordset oRecordset =
                    this.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);


                String query = "";
                query = query + "select * from dbo.[LB_titulos]";

                oRecordset.DoQuery(query);

                List <TitulosSAP> titulos = new List <TitulosSAP>();

                while (!oRecordset.EoF)
                {
                    List <Contacts> conts = new List <Contacts>();

                    SAPbobsCOM.Recordset oRecordset2 =
                        this.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

                    String varname1 = "";
                    varname1 = varname1 + "select *, ROW_NUMBER() over(partition by cardcode order by sort, email,phone) as rownumber " + "\n";
                    varname1 = varname1 + "	from( " + "\n";
                    varname1 = varname1 + "		select distinct  T1.CardCode, "+ "\n";
                    varname1 = varname1 + "		isnull(t0.Name,'') +' - '+ isnull(t0.FirstName,'')  as name, "+ "\n";
                    varname1 = varname1 + "			isnull(t0.E_MailL,t1.E_Mail) as email, "+ "\n";
                    varname1 = varname1 + "			ISNULL(t0.Tel1+ '-','') + ISNULL(t0.Tel2+ ' / ','') + "+ "\n";
                    varname1 = varname1 + "				isnull(t1.Phone1+ '-', '')+ISNULL(t1.Phone2,'') as phone, "+ "\n";
                    varname1 = varname1 + "		case when isnull(t0.E_MailL,t1.E_Mail) is null then '3' else '1' end sort "+ "\n";
                    varname1 = varname1 + "		from OCRD t1 left join OCPR t0 on t0.CardCode = t1.CardCode "+ "\n";
                    varname1 = varname1 + "				 "+ "\n";
                    varname1 = varname1 + "		where t0.Name like ('%fin%') or t0.E_MailL like ('%fin%') "+ "\n";
                    varname1 = varname1 + " " + "\n";
                    varname1 = varname1 + "		UNION "+ "\n";
                    varname1 = varname1 + " " + "\n";
                    varname1 = varname1 + "		select distinct  T1.CardCode, "+ "\n";
                    varname1 = varname1 + "			isnull(t0.Name,'') +' - '+ isnull(t0.FirstName,''), "+ "\n";
                    varname1 = varname1 + "			isnull(t0.E_MailL,t1.E_Mail), "+ "\n";
                    varname1 = varname1 + "			ISNULL(t0.Tel1+ '-','') + ISNULL(t0.Tel2+ ' / ','') + "+ "\n";
                    varname1 = varname1 + "					isnull(t1.Phone1+ '-', '')+ISNULL(t1.Phone2,''), "+ "\n";
                    varname1 = varname1 + "			case when isnull(t0.E_MailL,t1.E_Mail) is null then '3' else '2' end"+ "\n";
                    varname1 = varname1 + "				 "+ "\n";
                    varname1 = varname1 + "		from OCRD t1 left join OCPR t0 on t0.CardCode = t1.CardCode "+ "\n";
                    varname1 = varname1 + " " + "\n";
                    varname1 = varname1 + " " + "\n";
                    varname1 = varname1 + "	) t0 " + "\n";
                    varname1 = varname1 + "	where CardCode = '" + oRecordset.Fields.Item("cardcode").Value + "' " + "\n";
                    varname1 = varname1 + "	order by cardcode, sort, rownumber";

                    oRecordset2.DoQuery(varname1);


                    while (!oRecordset2.EoF)
                    {
                        Contacts cont = new Contacts(oRecordset2.Fields.Item("name").Value + "",
                                                     oRecordset2.Fields.Item("email").Value + "",
                                                     oRecordset2.Fields.Item("phone").Value + ""
                                                     );

                        conts.Add(cont);

                        oRecordset2.MoveNext();
                    }

                    Payees payee = new Payees(oRecordset.Fields.Item("id_type").Value + "",
                                              oRecordset.Fields.Item("id").Value + "",
                                              oRecordset.Fields.Item("legal_name").Value + "",
                                              null, //trade_name
                                              oRecordset.Fields.Item("email").Value + "",
                                              oRecordset.Fields.Item("phone").Value + "",
                                              null, //accounts
                                              conts
                                              );

                    //inserindo CNPJ sacado
                    SAPbobsCOM.Recordset oRecordset3 =
                        this.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                    oRecordset3.DoQuery("select top 1 REPLACE(REPLACE(REPLACE ( TaxIdNum , '.' , '' ), '/',''),'-','') as payer from OADM");

                    //criando o pay_doc_id
                    String payer_doc_id = oRecordset.Fields.Item("transID").Value + "-" + oRecordset.Fields.Item("Line_ID").Value;

                    TitulosSAP titulo = new TitulosSAP(
                        oRecordset3.Fields.Item("payer").Value + "",
                        payee,
                        oRecordset.Fields.Item("value").Value + "",
                        oRecordset.Fields.Item("original_value").Value + "",
                        oRecordset.Fields.Item("currency").Value + "",
                        oRecordset.Fields.Item("due_date").Value + "",
                        oRecordset.Fields.Item("issue_date").Value + "",
                        oRecordset.Fields.Item("tax_doc_id").Value + "",
                        oRecordset.Fields.Item("tax_doc_sec_id").Value + "",
                        oRecordset.Fields.Item("tax_doc_key").Value + "",
                        oRecordset.Fields.Item("installment").Value + "",
                        payer_doc_id,
                        String.Equals(oRecordset.Fields.Item("release").Value + "", "true")
                        );

                    titulos.Add(titulo);

                    oRecordset.MoveNext();
                }

                //String invoice = JsonConvert.SerializeObject(titulos, Formatting.Indented);
                String invoice = JsonConvert.SerializeObject(titulos, Formatting.None);


                json = "{\"batch\": \"" + System.Guid.NewGuid() + "\", \"invoices\":" + invoice + "}";


                System.IO.File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\LiberB1\\path.txt", json);

                oCompany.Disconnect();
                MyLogger.Log("Usuário SAP desconectado.");
                LiberRabbit rabbitsend = new LiberRabbit();
                rabbitsend.Connect();
                rabbitsend.WriteJson(json, "invoice.batch.imported");


                MyLogger.Log("Escrito na fila");

                return(true);
            }
            catch (Exception ex)
            {
                MyLogger.Log("Error 508 - " + ex);
                return(false);
            }
        }
Exemple #17
0
        public static bool ConnectToSAP()
        {
            Console.WriteLine("Connecting to SAP.");
            bool ret = true;

            try
            {
                int lRetCode;


                oCompany = new SAPbobsCOM.Company();

                Properties.Settings setting = new Properties.Settings();

                oCompany.Server    = setting.LicenseServer;
                oCompany.CompanyDB = setting.CompanyDB;
                oCompany.CompanyDB = setting.CompanyDB;

                oCompany.DbServerType = BoDataServerTypes.dst_MSSQL2008;

                //db user name
                oCompany.DbUserName = setting.DBUserName;
                oCompany.DbPassword = setting.DBPassword;
                //user name
                oCompany.UserName = setting.SAPUserName;
                //user password
                oCompany.Password = setting.SAPPassword;

                oCompany.language = SAPbobsCOM.BoSuppLangs.ln_English;

                //Use Windows authentication for database server.
                // True for NT server authentication,
                //False for database server authentication.
                oCompany.UseTrusted = false;

                //insert license server and port
                oCompany.LicenseServer = setting.LicenseServer.Trim() + ":30000";
                //Connecting to a company DB
                lRetCode = oCompany.Connect();


                if (lRetCode != 0)
                {
                    oCompany.GetLastError(out errCode, out errMsg);
                    Console.WriteLine(errMsg);
                    oCompany.Disconnect();
                    ret = false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            if (ret)
            {
                Console.WriteLine("Connection to SAP ok.");
            }

            //Return True
            return(ret);
        }
Exemple #18
0
        public static void CreateOrders()
        {
            try
            {
                using (var context = new POSStagingContext())
                {
                    Properties.Settings setting = new Properties.Settings();
                    var      loc        = context.SAPMappings.ToList();
                    var      Terminals  = context.POSTerminals.ToList();
                    string   dateString = setting.DateStart;
                    DateTime date1      = DateTime.Parse(dateString,
                                                         System.Globalization.CultureInfo.InvariantCulture);

                    var Orders = context.Orders.Include("Order_Lines").Include("OrderPayments2")
                                 .Where(o => o.DocNum == 0 && o.Order_Status_Code == 4 && o.Order_Date >= date1)
                                 .OrderBy(o => o.Order_Date).ThenBy(o => o.Location_Code).ThenBy(o => o.Order_Number);

                    int count;
                    int x = 0;

                    var countNum = (from c in context.Orders
                                    where c.DocNum == 0 && c.Order_Status_Code == 4 && c.Order_Date >= date1
                                    select c.id).Count();

                    count = countNum;
                    int TranCount = 0;
                    //context.
                    foreach (var OINV in Orders.ToList())
                    {
                        //count = Orders.Count();
                        Console.WriteLine("Creating doc." + x.ToString() + " of " + count.ToString());
                        x++;
                        SAPbobsCOM.Documents Invoice;

                        Invoice   = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(BoObjectTypes.oInvoices);
                        TranCount = 0;


                        if (OINV.Order_Status_Code != 4)
                        {
                            continue;
                        }
                        OINV.ErrMsg     = "";
                        Invoice.DocDate = OINV.Order_Date;

                        Invoice.DocDueDate = OINV.Order_Date;
                        Invoice.Project    = "DominoPizza";
                        string CardCode       = "";
                        string CostCenter     = "";
                        string cashGL         = "";
                        string BankGL         = "";
                        bool   ConsumptionTax = true;

                        foreach (var Location in loc)
                        {
                            if (Location.Location_Code == OINV.Location_Code)
                            {
                                CardCode   = Location.BPCode;
                                CostCenter = Location.PrcCode;
                                cashGL     = Location.CashGL;
                                //BankGL = Location.BankGL;
                                ConsumptionTax = Location.ConsumptionTax;
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }


                        Invoice.CardCode = CardCode;
                        Invoice.UserFields.Fields.Item("U_POSNumber").Value     = OINV.Order_Number;
                        Invoice.UserFields.Fields.Item("U_Location_Code").Value = OINV.Location_Code;

                        int i = 0;
                        foreach (var OrderLines in OINV.Order_Lines)
                        {
                            if (i != 0)
                            {
                                Invoice.Lines.Add();
                            }
                            Invoice.Lines.SetCurrentLine(i);
                            Invoice.Lines.ItemCode = OrderLines.ProductCode;
                            Invoice.Lines.Quantity = OrderLines.Quantity;
                            Invoice.Lines.Price    = (Double)(OrderLines.OrdLineTaxableSales / OrderLines.Quantity);
                            Invoice.Lines.TaxCode  = "X0";
                            Invoice.Lines.UserFields.Fields.Item("U_IdealFood").Value = (Double)OrderLines.OrdLineIdealFoodOptionQty;
                            Invoice.Lines.CostingCode5     = "CM0002";
                            Invoice.Lines.CostingCode2     = CostCenter;
                            Invoice.Lines.COGSCostingCode5 = "CM0002";
                            Invoice.Lines.COGSCostingCode2 = CostCenter;

                            Invoice.Lines.ProjectCode = "DominoPizza";

                            i++;
                        }

                        Invoice.Lines.Add();
                        Invoice.Lines.SetCurrentLine(i);



                        Invoice.Lines.ItemCode    = "VAT";
                        Invoice.Lines.Quantity    = 1;
                        Invoice.Lines.Price       = (Double)(OINV.Taxable_Sales1) * .05;
                        Invoice.Lines.TaxCode     = "X0";
                        Invoice.Lines.ProjectCode = "DominoPizza";
                        Invoice.Lines.AccountCode = "211501";
                        if (ConsumptionTax)
                        {
                            i++;
                            Invoice.Lines.Add();
                            Invoice.Lines.SetCurrentLine(i);

                            Invoice.Lines.ItemCode    = "Consumption";
                            Invoice.Lines.Quantity    = 1;
                            Invoice.Lines.Price       = (Double)(OINV.Taxable_Sales1) * .05;
                            Invoice.Lines.TaxCode     = "X0";
                            Invoice.Lines.ProjectCode = "DominoPizza";
                            Invoice.Lines.AccountCode = "211505";
                        }


                        //oCompany.StartTransaction();
                        if (Invoice.Add() != 0)
                        {
                            oCompany.GetLastError(out errCode, out errMsg);
                            Console.WriteLine(errMsg);
                            OINV.ErrMsg += "-" + errMsg;
                            //oCompany.Disconnect();
                            //if (oCompany.InTransaction)
                            //{
                            //    oCompany.EndTransaction(BoWfTransOpt.wf_RollBack);
                            //}
                        }
                        else
                        {
                            Console.WriteLine("Invoice for " + OINV.Location_Code + " - " + OINV.Order_Number + " - " + OINV.Order_Date.ToShortDateString() + " - created successfully ");

                            var invNum = (from c in context.InvoiceNumbers
                                          select c.DocNum).Max();

                            OINV.DocNum = invNum;
                            SAPbobsCOM.Payments Receipt;
                            Receipt = (SAPbobsCOM.Payments)oCompany.GetBusinessObject(BoObjectTypes.oIncomingPayments);

                            foreach (var OrderPayment in OINV.OrderPayments2)
                            {
                                Receipt.CardCode = CardCode;
                                Receipt.DocDate  = OrderPayment.Order_Date;
                                //Receipt.Reference1 = OrderPayment.OrdPayEPayRefNumber;
                                Receipt.Invoices.InvoiceType = BoRcptInvTypes.it_Invoice;
                                Receipt.Invoices.DocEntry    = invNum;
                                Receipt.Invoices.SumApplied  = (Double)OrderPayment.OrdPayAmt;
                                Receipt.ProjectCode          = "DominoPizza";

                                Receipt.UserFields.Fields.Item("U_POSNumber").Value     = OINV.Order_Number;
                                Receipt.UserFields.Fields.Item("U_Location_Code").Value = OINV.Location_Code;

                                switch (OrderPayment.Order_Pay_Type_Code)
                                {
                                case 1:
                                    Receipt.CashAccount = cashGL;
                                    Receipt.CashSum     = (Double)OINV.OrderFinalPrice;
                                    break;

                                case 4:
                                    BankGL = "";
                                    foreach (var Term in Terminals)
                                    {
                                        if (OrderPayment.Credit_Card_ID == Term.Credit_Card_ID &&
                                            OrderPayment.Location_Code == Term.Location_Code)
                                        {
                                            BankGL = Term.GLCode.ToString().TrimEnd();
                                            break;
                                        }
                                    }
                                    if (BankGL == "")
                                    {
                                        BankGL = "124211";
                                    }

                                    Receipt.TransferAccount = BankGL;
                                    Receipt.TransferDate    = OrderPayment.Order_Date;
                                    Receipt.TransferSum     = (Double)OrderPayment.OrdPayAmt;
                                    if (OrderPayment.OrdPayEPayRefNumber.Length < 27)
                                    {
                                        Receipt.TransferReference = OrderPayment.OrdPayEPayRefNumber;
                                    }
                                    else
                                    {
                                        Receipt.TransferReference = OrderPayment.OrdPayEPayRefNumber.ToString().Substring(0, 26);
                                    }


                                    break;

                                default:
                                    break;
                                }
                                if (Receipt.Add() != 0)
                                {
                                    oCompany.GetLastError(out errCode, out errMsg);
                                    Console.WriteLine(errMsg);
                                    oCompany.Disconnect();
                                    OINV.ReceiptErrMsg += errMsg;
                                    //if (oCompany.InTransaction)
                                    //{
                                    //    oCompany.EndTransaction(BoWfTransOpt.wf_RollBack);
                                    //}
                                }
                                else
                                {
                                    Console.WriteLine("Receipt for " + OrderPayment.Order_Number + " - " + OrderPayment.Location_Code + " - " + OrderPayment.Order_Date.ToShortDateString() + " - created successfully ");
                                    var RecNum = (from c in context.InvoiceNumbers
                                                  select c.ReceiptDocNum).Max();

                                    OINV.ReceiptDocNum = RecNum;
                                }
                                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Receipt);
                                break;
                            }
                        }

                        //if (oCompany.InTransaction)
                        //{
                        //    oCompany.EndTransaction(BoWfTransOpt.wf_Commit);
                        //}
                        string strSql = "Update Orders Set DocNum = " + OINV.DocNum.ToString() + ", errMsg = '" + OINV.ErrMsg +
                                        "', ReceiptDocNum = " + OINV.ReceiptDocNum.ToString() + ", ReceiptErrMsg = '" + OINV.ReceiptErrMsg + "'";
                        ;
                        strSql += " Where id = " + OINV.id.ToString();
                        int noOfRowsAffected = context.Database.ExecuteSqlCommand(strSql);

                        Console.WriteLine(OINV.Order_Number.ToString());
                        //using (var Context1 = new POSStagingContext())
                        //{
                        //    var Orders1 = context.Orders.Where(o => o.id == OINV.id).FirstOrDefault<Order>();
                        //    Orders1.DocNum = OINV.DocNum;

                        //    Context1.SaveChanges();
                        //}

                        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Invoice);
                    }

                    //context.SaveChanges();
                    //Console.WriteLine(" ");
                    //Console.WriteLine("Context saved successfully");
                }
            }
            catch (Exception ex)
            {
                //if (oCompany.InTransaction)
                //{
                //    oCompany.EndTransaction(BoWfTransOpt.wf_RollBack);
                //}
                Console.WriteLine(ex.Message);
            }
        }
        private void ConnectSBO(ref SAPbobsCOM.Company oCompany, ref int nErr, ref string sErr, string CompanyName)
        {
            VisualD.Core.TVisualDCore Core;

            sErr = "";
            nErr = 0;

            oLog.LogMsg("ConnectSBO start", "F", "D");
            SBO_VID_Currency.Properties.Settings.Default.Reload();
            // Set company properties

            switch (SBO_VID_Currency.Properties.Settings.Default.SQLType)    // 0->2005 1-2008 2-2012
            {
            case 0: oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2005;
                break;

            case 1: oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2008;
                break;

            case 2: oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2012;
                break;

            case 3: oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2014;
                break;

            case 4: oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2016;
                break;

            case 5: oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2017;
                break;

            case 6: oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_MSSQL2019;
                break;

            case 7: oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_HANADB;
                break;
            }
            oCompany.UseTrusted = false;
            oCompany.Server     = SBO_VID_Currency.Properties.Settings.Default.SBOServer; // +":40000";
            oCompany.DbUserName = SBO_VID_Currency.Properties.Settings.Default.DBUserName;
            oCompany.DbPassword = Crypt.Decrypt(SBO_VID_Currency.Properties.Settings.Default.DBPassword, "VIDCurrency0-09");
            oCompany.CompanyDB  = CompanyName;
            oCompany.UserName   = globals.SBOUser;
            oCompany.Password   = globals.SBOPass;

            //Try to connect
            nErr = oCompany.Connect();
            oLog.LogMsg("try connect", "F", "D");

            if (nErr != 0) // if the connection failed
            {
                oCompany.GetLastError(out nErr, out sErr);
            }
            else
            {
                SAPbobsCOM.Recordset oRecordSet; // A recordset object
                oRecordSet = (SAPbobsCOM.Recordset)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

                if (oCompany.DbServerType == SAPbobsCOM.BoDataServerTypes.dst_HANADB)
                {
                    oRecordSet.DoQuery("select \"InstallNo\" from \"CINF\"");
                }
                else
                {
                    oRecordSet.DoQuery("select InstallNo from cinf");
                }
                oLog.LogMsg("Select InstallNo", "F", "D");
                if (oRecordSet.EoF)
                {
                    sErr = "Installation Number no encontrado";
                    nErr = -1;
                    return;
                }

                string InstallId = (System.String)oRecordSet.Fields.Item("installNo").Value;

                if (oCompany.DbServerType == SAPbobsCOM.BoDataServerTypes.dst_HANADB)
                {
                    oRecordSet.DoQuery("Select CURRENT_DATE \"Fec\" from DUMMY");
                }
                else
                {
                    oRecordSet.DoQuery("Select GetDate() Fec");
                }
                DateTime            Fec          = (System.DateTime)(oRecordSet.Fields.Item("Fec").Value);
                TGlobalAddOnOptions FOpcionAddOn = new TGlobalAddOnOptions();
                List <String>       FAddonsList  = new List <String>();

                string oK = "C9A80FB4-D8C3-11E0-AEAD-7E944824019B";
                oLog.LogMsg("Before accept", "F", "D");

                Core = new VisualD.Core.TVisualDCore(InstallId, Fec, ref FOpcionAddOn, ref oK, FAddonsList);

                if (Core.ExitApp)
                {
                    sErr = "Licencia " + Core.Error;
                    nErr = -2;
                    oCompany.Disconnect();
                }
                else if (oK != "E6DCA176-D8C3-11E0-93B0-86944824019B")
                {
                    sErr = "VisualDCore enlace 2 inválido.";
                    nErr = -3;
                    oCompany.Disconnect();
                }
                else
                {
                    sErr = "OK";
                }

                if (Core.EsDEmo)
                {
                    oLog.LogMsg("Licencia de demostracion " + Core.AddOnName, "F", "W");
                }


                oLog.LogMsg("after accept", "F", "D");
            }

            oLog.LogMsg("Conexion a SBO: " + CompanyName + " - " + sErr, "F", "I");
        }
        public int SetConnectionContext()
        {
            int setConnectionContextReturn = 0;
            string sCookie = null;
            string sConnectionContext = null;

            oCompany = new SAPbobsCOM.Company();
            sCookie = oCompany.GetContextCookie();
            sConnectionContext = SBO_Application.Company.GetConnectionContext(sCookie);

            if (oCompany.Connected == true)
            {
                oCompany.Disconnect();
            }
            setConnectionContextReturn = oCompany.SetSboLoginContext(sConnectionContext);

            return setConnectionContextReturn;
        }