public static ErpBS AbreEmpresa(string strEmpresa, string strUtilizador, string strPassword, string strInstancia)
        {
            //------------------------------------------------------------------------
            //Open plt
            //------------------------------------------------------------------------

            StdBSConfApl objAplConf = new StdBSConfApl();
            ErpBS objMotor = new ErpBS();

            //[ Open Plt 1ª time ]
            EnumTipoPlataforma objTipoPlataforma = new EnumTipoPlataforma();
            objTipoPlataforma = EnumTipoPlataforma.tpProfissional;

            objAplConf.Instancia = strInstancia;
            objAplConf.AbvtApl = "GCP";
            objAplConf.PwdUtilizador = "";
            objAplConf.Utilizador = "";

            StdBETransaccao objStdTransac = new StdBETransaccao();

            Plataforma.AbrePlataformaEmpresaIntegrador(ref strEmpresa, ref objStdTransac, ref objAplConf, ref objTipoPlataforma);

            bool blnModoPrimario = true;
            objMotor.AbreEmpresaTrabalho(ref objTipoPlataforma, ref strEmpresa, ref strUtilizador, ref strPassword, ref objStdTransac, ref strInstancia, ref blnModoPrimario);

            MotorLE = objMotor;

            return MotorLE;
        }
        public static ErpBS AbreEmpresa(string strEmpresa, string strUtilizador, string strPassword, string strInstancia)
        {
            //------------------------------------------------------------------------
            //Open plt
            //------------------------------------------------------------------------

            StdBSConfApl objAplConf = new StdBSConfApl();
            ErpBS        objMotor   = new ErpBS();

            //[ Open Plt 1ª time ]
            EnumTipoPlataforma objTipoPlataforma = new EnumTipoPlataforma();

            objTipoPlataforma = EnumTipoPlataforma.tpProfissional;

            objAplConf.Instancia     = strInstancia;
            objAplConf.AbvtApl       = "GCP";
            objAplConf.PwdUtilizador = "";
            objAplConf.Utilizador    = "";

            StdBETransaccao objStdTransac = new StdBETransaccao();

            Plataforma.AbrePlataformaEmpresaIntegrador(ref strEmpresa, ref objStdTransac, ref objAplConf, ref objTipoPlataforma);


            bool blnModoPrimario = true;

            objMotor.AbreEmpresaTrabalho(ref objTipoPlataforma, ref strEmpresa, ref strUtilizador, ref strPassword, ref objStdTransac, ref strInstancia, ref blnModoPrimario);

            MotorLE = objMotor;

            return(MotorLE);
        }
Example #3
0
        public ScriptResponse Execute(ContextDataObject context, string query)
        {
            ErpBS bsERP = new ErpBS();

            if (!context.Parameters.ContainsKey("TipoPlataforma"))
            {
                throw new Exception("TipoPlataforma inválido");
            }

            EnumTipoPlataforma tipoPlataforma;

            if (!Enum.TryParse <EnumTipoPlataforma>((string)context.Parameters["TipoPlataforma"], out tipoPlataforma))
            {
                throw new Exception("TipoPlataforma inválido");
            }

            try
            {
                bsERP.AbreEmpresaTrabalho(tipoPlataforma, context.Company, context.Username, context.Password);
            }
            catch (Exception e)
            {
                throw new Exception("Erro a abrir a empresa no ERP: " + e.Message);
            }

            StdBELista queryResults = bsERP.Consulta(query);

            int numLinhas  = queryResults.NumLinhas();
            int numColunas = queryResults.NumColunas();

            string[] headers = new string[numColunas];
            for (short i = 0; i < numColunas; i++)
            {
                headers[i] = queryResults.Nome(i);
            }

            object[,] data = new object[numLinhas, numColunas];
            for (short i = 0; i < numLinhas; i++)
            {
                for (short j = 0; j < numColunas; j++)
                {
                    var nome = headers[j];
                    data[i, j] = queryResults.Valor(nome);
                }
                queryResults.Seguinte();
            }

            QueryResult response = new QueryResult()
            {
                Headers = headers,
                Data    = data
            };

            bsERP.FechaEmpresaTrabalho();

            return(new ScriptResponse
            {
                Object = response
            });
        }
Example #4
0
        private void button2AbririMotor_Click(object sender, EventArgs e)
        {
            try
            {
                BSO = new ErpBS100.ErpBS();

                StdBE100.StdBETipos.EnumTipoPlataforma tipoPlataforma =
                    StdBE100.StdBETipos.EnumTipoPlataforma.tpEmpresarial;
                BSO.AbreEmpresaTrabalho(tipoPlataforma, "DEMO", "primavera", "qualquer");

                //use this service to trigger the API events.
                ExtensibilityService service = new ExtensibilityService();

                service.Initialize(BSO);

                // Check if service is operational
                if (service.IsOperational)
                {
                    // Inshore that all extensions are loaded.
                    service.LoadExtensions();
                }

                label2EstadoMotor.Text = "Motor aberto...";
            }
            catch (Exception)
            {
                label2EstadoMotor.Text = " Erro ao abrir o motor!";
            }
        }
Example #5
0
        /// <summary>
        /// Return a list of companies where the credit limit of the given customer is exceeded orelse has been blocked.
        /// </summary>
        /// <param name="strCustomer">Customer to be analised</param>
        /// <returns>List<String></String></returns>
        internal static List <String> CreditLimitExceeded(ERPContext ERPContext, String strCustomer)
        {
            List <String> companiesList = new List <String>();
            Dictionary <String, String> groupCompanies = CrossCompany.Platform.GetGroupCompanies(ERPContext);

            foreach (string company in groupCompanies.Keys)
            {
                ErpBS currentCompany = new ErpBS();

                currentCompany.AbreEmpresaTrabalho(
                    StdBETipos.EnumTipoPlataforma.tpEmpresarial,
                    company,
                    Properties.Settings.Default.User,    //ERPContext.BSO.Contexto.ObjUtilizador.Codigo,
                    Properties.Settings.Default.Password //ERPContext.BSO.Contexto.ObjUtilizador.Password
                    );

                if ((currentCompany.Base.Clientes.DaValorAtributo(strCustomer, "TipoCred") == "2") ||
                    (currentCompany.Base.Clientes.DaValorAtributo(strCustomer, "limitecred") < currentCompany.Base.Clientes.DaValorAtributo(strCustomer, "totaldeb")))
                {
                    companiesList.Add(company);
                }

                currentCompany.FechaEmpresaTrabalho();
            }

            return(companiesList);
        }
Example #6
0
        /// <summary>
        /// Creats the context.
        /// </summary>
        /// <param name="Company">The company.</param>
        /// <param name="User">The user.</param>
        /// <param name="Password">The password.</param>
        /// <param name="Instance">ERP instance.</param>
        /// <returns></returns>
        public static PriEngine CreatContext(string Company, string User, string Password, string Instance)
        {
            try
            {
                StdLoggingHandler.FileTraceEnterMethod();
                StdLoggingHandler.FileTrace("Creating objects");

                StdBSConfApl objAplConf = new StdBSConfApl();
                StdPlatBS    Plataforma = new StdPlatBS();
                ErpBS        MotorLE    = new ErpBS();

                StdLoggingHandler.FileTrace("Setting configuration");
                EnumTipoPlataforma objTipoPlataforma = EnumTipoPlataforma.tpEmpresarial;

                objAplConf.Instancia       = Instance;
                objAplConf.AbvtApl         = "ERP";
                objAplConf.PwdUtilizador   = Password;
                objAplConf.Utilizador      = User;
                objAplConf.LicVersaoMinima = "10.00";

                StdLoggingHandler.FileTrace("Setting transaccao");
                StdBETransaccao objStdTransac = new StdBETransaccao();

                try
                {
                    StdLoggingHandler.FileTrace("Calling AbrePlataformaEmpresa");
                    Plataforma.AbrePlataformaEmpresa(Company, objStdTransac, objAplConf, objTipoPlataforma);
                    StdLoggingHandler.FileTrace("Exit from AbrePlataformaEmpresa");
                }
                catch (Exception ex)
                {
                    StdLoggingHandler.FileTraceWithThrow(ex);
                    throw;
                }

                if (Plataforma.Inicializada)
                {
                    StdLoggingHandler.FileTrace("Calling AbreEmpresaTrabalho");
                    MotorLE.AbreEmpresaTrabalho(objTipoPlataforma, Company, User, Password, objStdTransac, Instance);
                    StdLoggingHandler.FileTrace("Exit from AbreEmpresaTrabalho");

                    Platform = Plataforma;
                    Engine   = MotorLE;

                    EngineStatus = true;
                }

                return(engineInstance);
            }
            catch (Exception ex)
            {
                StdLoggingHandler.FileTraceWithThrow(ex);
                throw;
            }
            finally
            {
                StdLoggingHandler.FileTraceExitMethod();
            }
        }
Example #7
0
        public static bool InitializeCompany(string Company, string User, string Password)
        {
            if (!initialized)
            {
                StdBSConfApl objAplConf = new StdBSConfApl();
                objAplConf.Instancia       = "Default";
                objAplConf.AbvtApl         = "GCP";
                objAplConf.PwdUtilizador   = Password;
                objAplConf.Utilizador      = User;
                objAplConf.LicVersaoMinima = "9.00";
                StdBETransaccao objStdTransac = new StdBETransaccao();

                StdPlatBS Plataforma = new StdPlatBS();
                ErpBS     MotorLE    = new ErpBS();

                EnumTipoPlataforma objTipoPlataforma = new EnumTipoPlataforma();
                objTipoPlataforma = EnumTipoPlataforma.tpProfissional;

                objAplConf.Instancia       = "Default";
                objAplConf.AbvtApl         = "GCP";
                objAplConf.PwdUtilizador   = Password;
                objAplConf.Utilizador      = User;
                objAplConf.LicVersaoMinima = "9.00";

                // Retuns the ptl.
                Platform = Plataforma;
                // Returns the engine.
                Engine = MotorLE;

                try
                {
                    Platform.AbrePlataformaEmpresa(ref Company, ref objStdTransac, ref objAplConf, ref objTipoPlataforma, "");
                }
                catch (Exception ex)
                {
                    throw new Exception("Error on open Primavera Platform.");
                }

                // Is plt initialized?
                if (Platform.Inicializada)
                {
                    bool blnModoPrimario = true;
                    // Open Engine
                    Engine.AbreEmpresaTrabalho(EnumTipoPlataforma.tpProfissional, ref Company, ref User, ref Password, ref objStdTransac, "Default", ref blnModoPrimario);
                    Engine.set_CacheActiva(false);
                    initialized = true;
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(true);
            }
        }
Example #8
0
        public static bool InitializeCompany(string Company, string User, string Password)
        {
            var postCompany  = HttpContext.Current.Request.Form["company"];
            var postUsername = HttpContext.Current.Request.Form["username"];
            var postPassword = HttpContext.Current.Request.Form["password"];

            StdBSConfApl objAplConf = new StdBSConfApl();
            StdPlatBS    Plataforma = new StdPlatBS();
            ErpBS        MotorLE    = new ErpBS();

            EnumTipoPlataforma objTipoPlataforma = new EnumTipoPlataforma();

            objTipoPlataforma = EnumTipoPlataforma.tpProfissional;

            objAplConf.Instancia       = "Default";
            objAplConf.AbvtApl         = "GCP";
            objAplConf.PwdUtilizador   = postPassword;
            objAplConf.Utilizador      = postUsername;
            objAplConf.LicVersaoMinima = "9.00";

            StdBETransaccao objStdTransac = new StdBETransaccao();

            // Opem platform.
            try
            {
                Plataforma.AbrePlataformaEmpresa(ref postCompany, ref objStdTransac, ref objAplConf, ref objTipoPlataforma, "");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.StatusCode      = (int)HttpStatusCode.Forbidden;
                HttpContext.Current.Response.SuppressContent = true;
                HttpContext.Current.ApplicationInstance.CompleteRequest();
                return(false);
            }

            // Is plt initialized?
            if (Plataforma.Inicializada)
            {
                // Retuns the ptl.
                Platform = Plataforma;

                bool blnModoPrimario = true;

                // Open Engine
                MotorLE.AbreEmpresaTrabalho(EnumTipoPlataforma.tpProfissional, ref postCompany, ref postUsername, ref postPassword, ref objStdTransac, "Default", ref blnModoPrimario);
                MotorLE.set_CacheActiva(false);

                // Returns the engine.
                Engine = MotorLE;

                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #9
0
        public object Execute(ContextDataObject context, Entity document)
        {
            /* **************************************** */
            /* **************************************** */
            /*          ADD YOUR CODE HERE              */
            ErpBS bsERP = new ErpBS();

            try {
                if (!context.Parameters.ContainsKey("TipoPlataforma"))
                {
                    throw new Exception("TipoPlataforma inválido");
                }

                EnumTipoPlataforma tipoPlataforma;
                if (!Enum.TryParse <EnumTipoPlataforma>((string)context.Parameters["TipoPlataforma"], out tipoPlataforma))
                {
                    throw new Exception("TipoPlataforma inválido");
                }

                try
                {
                    bsERP.AbreEmpresaTrabalho(tipoPlataforma, context.Company, context.Username, context.Password);
                }
                catch (Exception e)
                {
                    throw new Exception("Erro a abrir a empresa no ERP: " + e.Message);
                }
                GcpBEDocumentoCompra purchaseOrder = new GcpBEDocumentoCompra();
                purchaseOrder.set_Tipodoc("ECF");
                purchaseOrder.set_Serie("A");
                purchaseOrder.set_TipoEntidade("F");
                purchaseOrder.set_Entidade(document.Attributes.Supplier);
                purchaseOrder.set_NumDocExterno("0");
                purchaseOrder.set_Observacoes("Documento gerado no portal OMNIA: Pedido de Encomenda " + document.NumberSerieCode + "/" + document.Number);
                purchaseOrder.set_DataCarga(document.DateCreated.ToShortDateString());
                purchaseOrder.set_DataDescarga(document.DateCreated.ToShortDateString());

                bsERP.Comercial.Compras.PreencheDadosRelacionados(purchaseOrder);
                foreach (var line in document.Commitments.GoodsPurchaseRequest)
                {
                    bsERP.Comercial.Compras.AdicionaLinha(purchaseOrder, line.Resource, line.Quantity, "A1", "", line.Amount);
                }

                bsERP.Comercial.Compras.Actualiza(purchaseOrder);

                bsERP.FechaEmpresaTrabalho();

                return(new ScriptResponse {
                    Message = "Integrado documento " + purchaseOrder.get_Tipodoc() + " " + purchaseOrder.get_Serie() + "/" + purchaseOrder.get_NumDoc()
                });
            } catch (Exception ex) {
                bsERP.FechaEmpresaTrabalho();

                throw ex;
            }
        }
        internal static Dictionary <String, int> CheckPendingDocuments(ERPContext oERPContext)
        {
            Dictionary <String, int>    result         = new Dictionary <string, int>();
            Dictionary <String, String> groupCompanies = CrossCompany.Platform.GetGroupCompanies(oERPContext);

            //Exit if no companies where found
            if (groupCompanies.Count == 0)
            {
                return(result);
            }

            result.Add("Purchases", 0);
            result.Add("Sales", 0);

            //Load the documents to import from all the group companies
            groupCompanies.Remove(oERPContext.BSO.Contexto.CodEmp);
            foreach (string groupCompany in groupCompanies.Keys)
            {
                ErpBS oCompany = new ErpBS();

                oCompany.AbreEmpresaTrabalho(
                    StdBE100.StdBETipos.EnumTipoPlataforma.tpEmpresarial,
                    groupCompany,
                    Properties.Settings.Default.User,
                    Properties.Settings.Default.Password);


                String strSQL = String.Format(
                    "select sum(pur) Purchases, sum(sls) Sales " +
                    "from(" +
                    "   select count(*) pur, 0 sls from cabecdoc cd inner join CabecDocStatus cds on cds.IdCabecDoc=cd.Id left join documentosvenda dv on cd.tipodoc = dv.documento " +
                    "   where dv.cdu_exportagrupo = 1 AND cd.cdu_exportado = 0  AND cds.Anulado=0 AND cd.entidade = '{0}' " +
                    "   UNION ALL " +
                    "   select 0 pur, count(*) pur from cabeccompras cc inner join CabecComprasStatus ccs on ccs.IdCabecCompras=cc.Id left join documentoscompra dc on cc.tipodoc = dc.documento " +
                    "   where dc.cdu_exportagrupo = 1 AND isnull(cc.cdu_exportado, 0) = 0 AND ccs.Anulado=0 AND cc.entidade = '{0}' " +
                    "   ) as tmp"
                    , oERPContext.BSO.Contexto.CodEmp);

                StdBELista lstPendDocs = oCompany.Consulta(strSQL);

                if (!lstPendDocs.Vazia())
                {
                    if (lstPendDocs.DaValor <int>("Purchases") > 0)
                    {
                        result["Purchases"] += lstPendDocs.DaValor <int>("Purchases");
                    }

                    if (lstPendDocs.DaValor <int>("Sales") > 0)
                    {
                        result["Sales"] += lstPendDocs.DaValor <int>("Sales");
                    }
                }
            }

            return(result);
        }
Example #11
0
        public static PriEngine CreatContext(string Company, string User, string Password)
        {
            StdBSConfApl objAplConf = new StdBSConfApl();
            StdPlatBS    Plataforma = new StdPlatBS();
            ErpBS        MotorLE    = new ErpBS();

            EnumTipoPlataforma objTipoPlataforma;

            objTipoPlataforma = EnumTipoPlataforma.tpEmpresarial;

            objAplConf.Instancia       = "Default";
            objAplConf.AbvtApl         = "ERP";
            objAplConf.PwdUtilizador   = Password;
            objAplConf.Utilizador      = User;
            objAplConf.LicVersaoMinima = "10.00";

            StdBETransaccao objStdTransac = new StdBETransaccao();

            try
            {
                Plataforma.AbrePlataformaEmpresa(Company, objStdTransac, objAplConf, objTipoPlataforma);
            }
            catch (Exception ex)
            {
                throw (ex);
            }

            if (Plataforma.Inicializada)
            {
                // Use this service to trigger the API events.
                ExtensibilityService service = new ExtensibilityService();

                // Suppress all message box events from the API.
                // Plataforma.ExtensibilityLogger.AllowInteractivity = false;
                service.Initialize(MotorLE);

                // Check if service is operational
                if (service.IsOperational)
                {
                    // Inshore that all extensions are loaded.
                    service.LoadExtensions();
                }

                MotorLE.AbreEmpresaTrabalho(objTipoPlataforma, Company, User, Password, objStdTransac, "Default");

                Platform = Plataforma;
                Engine   = MotorLE;

                EngineStatus = true;
            }

            return(engineInstance);
        }
Example #12
0
        public Boolean AbrirMotorPrimavera(string userPrimavera, string passUserPrimavera, string empresa, int tipoEmpPRI)
        {
            try
            {
                StdBSConfApl objAplConf = new StdBSConfApl();
                StdPlatBS    Plataforma = new StdPlatBS();
                ErpBS        MotorLE    = new ErpBS();

                EnumTipoPlataforma objTipoPlataforma = new EnumTipoPlataforma();
                objTipoPlataforma = EnumTipoPlataforma.tpEmpresarial;

                objAplConf.Instancia       = "Default";
                objAplConf.AbvtApl         = "ERP";
                objAplConf.PwdUtilizador   = passUserPrimavera;
                objAplConf.Utilizador      = userPrimavera;
                objAplConf.LicVersaoMinima = "9.00";

                StdBETransaccao objStdTransac = new StdBETransaccao();

                try
                {
                    Plataforma.AbrePlataformaEmpresa(ref empresa, ref objStdTransac, ref objAplConf, ref objTipoPlataforma, "");
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                if (Plataforma.Inicializada)
                {
                    plat = Plataforma.InterfacePublico;

                    bool blnModoPrimario = true;

                    MotorLE.AbreEmpresaTrabalho(tipoEmpPRI == 0 ? EnumTipoPlataforma.tpEmpresarial : EnumTipoPlataforma.tpProfissional,
                                                ref empresa, ref userPrimavera, ref passUserPrimavera, ref objStdTransac, "Default", ref blnModoPrimario);
                    MotorLE.set_CacheActiva(true);

                    bso = MotorLE;

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #13
0
        public static bool InitializeCompany(string Company, string User, string Password)
        {
            StdBSConfApl objAplConf = new StdBSConfApl();
            StdPlatBS    Plataforma = new StdPlatBS();
            ErpBS        MotorLE    = new ErpBS();

            EnumTipoPlataforma objTipoPlataforma = new EnumTipoPlataforma();

            objTipoPlataforma = EnumTipoPlataforma.tpProfissional;

            objAplConf.Instancia       = "Default";
            objAplConf.AbvtApl         = "GCP";
            objAplConf.PwdUtilizador   = Password;
            objAplConf.Utilizador      = User;
            objAplConf.LicVersaoMinima = "9.00";

            StdBETransaccao objStdTransac = new StdBETransaccao();

            // Opem platform (verifica se o utilizador tem permissões de acesso)
            try {
                Plataforma.AbrePlataformaEmpresa(ref Company, ref objStdTransac, ref objAplConf, ref objTipoPlataforma, "");
            } catch (Exception ex) {
                throw new Exception("Error on open Primavera Platform: " + ex.Message);
            }

            // Is plt initialized?
            if (Plataforma.Inicializada)
            {
                // Retuns the ptl.
                platform = Plataforma;

                bool blnModoPrimario = true;

                // Open Engine
                MotorLE.AbreEmpresaTrabalho(EnumTipoPlataforma.tpProfissional, ref Company, ref User, ref Password, ref objStdTransac, "Default", ref blnModoPrimario);
                MotorLE.set_CacheActiva(false);

                // Returns the engine.
                engine = MotorLE;

                string databaseInstance = "Default";
                string dbNomeEmpresa    = platform.BaseDados.DaNomeBDdaEmpresa(engine.Contexto.CodEmp);
                databaseConnectionString = platform.BaseDados.DaConnectionStringNET(dbNomeEmpresa, databaseInstance);

                return(true);
            }
            else
            {
                return(false);
            }
        }
        public Boolean AbrirMotorPrimavera(string userPrimavera, string passUserPrimavera, string empresa, int tipoEmpPRI)
        {
            try
            {
                bso = new ErpBS();

                bso.AbreEmpresaTrabalho(tipoEmpPRI, empresa, userPrimavera, passUserPrimavera);

                AbrePlataforma(bso);

                return(bso.Contexto.EmpresaAberta);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #15
0
        /// <summary>
        /// Only intialized in the frist time.
        /// </summary>
        /// <param name="Company"></param>
        /// <param name="User"></param>
        /// <param name="Password"></param>
        public static bool InitializeCompany(string Company, string User, string Password)
        {
            StdBSConfApl objAplConf = new StdBSConfApl();
            StdPlatBS    Plataforma = new StdPlatBS();
            ErpBS        MotorLE    = new ErpBS();

            EnumTipoPlataforma objTipoPlataforma = new EnumTipoPlataforma();

            objTipoPlataforma = EnumTipoPlataforma.tpEmpresarial;

            objAplConf.Instancia       = "Default";
            objAplConf.AbvtApl         = "ERP";
            objAplConf.PwdUtilizador   = Password;
            objAplConf.Utilizador      = User;
            objAplConf.LicVersaoMinima = "9.00";

            StdBETransaccao objStdTransac = new StdBETransaccao();

            try
            {
                Plataforma.AbrePlataformaEmpresa(ref Company, ref objStdTransac, ref objAplConf, ref objTipoPlataforma, "");
            }
            catch (Exception ex)
            {
                throw (ex);
            }

            if (Plataforma.Inicializada)
            {
                Platform = Plataforma;

                bool blnModoPrimario = true;

                MotorLE.AbreEmpresaTrabalho(EnumTipoPlataforma.tpEmpresarial, ref Company, ref User, ref Password, ref objStdTransac, "Default", ref blnModoPrimario);
                MotorLE.set_CacheActiva(true);

                Engine = MotorLE;

                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #16
0
        public Boolean AbrirMotorPrimavera(string userPrimavera, string passUserPrimavera, string empresa, int tipoEmpPRI)
        {
            try
            {
                bso = new ErpBS();

                bso.AbreEmpresaTrabalho(tipoEmpPRI == 0 ? EnumTipoPlataforma.tpEmpresarial : EnumTipoPlataforma.tpProfissional,
                                        ref empresa, ref userPrimavera, ref passUserPrimavera);

                //AbrePlataforma(bso);

                return(bso.Contexto.EmpresaAberta);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #17
0
        public static bool InitializeCompany(string Company, string User, string Password)
        {
            StdBSConfApl objAplConf = new StdBSConfApl();
            StdPlatBS Plataforma = new StdPlatBS();
            ErpBS MotorLE = new ErpBS();

            EnumTipoPlataforma objTipoPlataforma = new EnumTipoPlataforma();
            objTipoPlataforma = EnumTipoPlataforma.tpProfissional;

            objAplConf.Instancia = "Default";
            objAplConf.AbvtApl = "GCP";
            objAplConf.PwdUtilizador = Password;
            objAplConf.Utilizador = User;

            StdBETransaccao objStdTransac = new StdBETransaccao();

            // Opem platform.
            Plataforma.AbrePlataformaEmpresaIntegrador(ref Company, ref objStdTransac, ref objAplConf, ref objTipoPlataforma);

            // Is plt initialized?
            if (Plataforma.Inicializada)
            {

                // Retuns the ptl.
                Platform = Plataforma;

                bool blnModoPrimario = true;

                // Open Engine
                MotorLE.AbreEmpresaTrabalho(EnumTipoPlataforma.tpProfissional, ref Company, ref User, ref Password, ref objStdTransac, "Default", ref blnModoPrimario);
                _connection = Plataforma.BaseDados.AbreBaseDadosADO("Default", "PRI" + Company);

                // Returns the engine.
                Engine = MotorLE;

                return true;
            }
            else
            {
                return false;
            }
        }
        public static bool InitializeCompany()
        {
            if (Platform != null && Platform.Inicializada)
            {
                return(true);
            }

            bool blnModoPrimario = true;
            var  objAplConf      = new StdBSConfApl();

            objAplConf.Instancia       = "Default";
            objAplConf.AbvtApl         = "GCP";
            objAplConf.PwdUtilizador   = Properties.Settings.Default.Password.Trim();
            objAplConf.Utilizador      = Properties.Settings.Default.User.Trim();
            objAplConf.LicVersaoMinima = "9.00";

            var MotorLE        = new ErpBS();
            var Plataforma     = new StdPlatBS();
            var objStdTransac  = new StdBETransaccao();
            var tipoPlataforma = EnumTipoPlataforma.tpProfissional;

            try
            {
                Plataforma.AbrePlataformaEmpresa(Properties.Settings.Default.Company.Trim(), ref objStdTransac, ref objAplConf, ref tipoPlataforma, "");
            }
            catch
            {
                return(false);
            }

            PrimaveraEngine.InitializeSQLite();

            if (Plataforma.Inicializada)
            {
                Platform = Plataforma;
                MotorLE.AbreEmpresaTrabalho(EnumTipoPlataforma.tpProfissional, Properties.Settings.Default.Company.Trim(), Properties.Settings.Default.User.Trim(), Properties.Settings.Default.Password.Trim(), ref objStdTransac, "Default", ref blnModoPrimario);
                MotorLE.set_CacheActiva(true);
                Engine = MotorLE;
            }

            return(Plataforma.Inicializada);
        }
        public static bool InitializeCompany(string Company, string User, string Password)
        {
            StdBSConfApl objAplConf = new StdBSConfApl();
            StdPlatBS    Plataforma = new StdPlatBS();
            ErpBS        MotorLE    = new ErpBS();

            EnumTipoPlataforma objTipoPlataforma = new EnumTipoPlataforma();

            objTipoPlataforma = EnumTipoPlataforma.tpProfissional;

            objAplConf.Instancia     = "Default";
            objAplConf.AbvtApl       = "GCP";
            objAplConf.Utilizador    = User;
            objAplConf.PwdUtilizador = Password;


            StdBETransaccao objStdTransac = new StdBETransaccao();

            // Opem platform.
            Plataforma.AbrePlataformaEmpresaIntegrador(ref Company, ref objStdTransac, ref objAplConf, ref objTipoPlataforma);

            // Is plt initialized?
            if (Plataforma.Inicializada)
            {
                // Retuns the ptl.
                Platform = Plataforma;

                bool blnModoPrimario = true;

                // Open Engine
                MotorLE.AbreEmpresaTrabalho(EnumTipoPlataforma.tpProfissional, ref Company, ref User, ref Password, ref objStdTransac, "Default", ref blnModoPrimario);

                // Returns the engine.
                Engine = MotorLE;

                return(true);
            }
            else
            {
                return(false);
            }
        }
        /// <summary>
        /// Update the Item in the group companies
        /// </summary>
        /// <param name="oERPContext"></param>
        /// <param name="Artigo"></param>
        /// <returns>List<String> of the updated companies</returns>
        internal static List <String> UpdateItem_GroupCompanies(ERPContext oERPContext, String Item)
        {
            Dictionary <String, String> groupCompanies = CrossCompany.Platform.GetGroupCompanies(oERPContext);
            List <String> updatedCompanies             = new List <string>();

            //Exit if no companies where found
            if (groupCompanies.Count == 0)
            {
                return(updatedCompanies);
            }

            groupCompanies.Remove(oERPContext.BSO.Contexto.CodEmp);
            foreach (string company in groupCompanies.Keys)
            {
                ErpBS oCompany = new ErpBS();

                oCompany.AbreEmpresaTrabalho(
                    StdBE100.StdBETipos.EnumTipoPlataforma.tpEmpresarial,
                    company,
                    Properties.Settings.Default.User,
                    Properties.Settings.Default.Password);

                //Create or update the item
                BasBEArtigo      oItem       = oERPContext.BSO.Base.Artigos.Edita(Item);
                BasBEArtigoMoeda oItemPrices = oERPContext.BSO.Base.ArtigosPrecos.Edita(Item, "EUR", oERPContext.BSO.Base.Artigos.DaValorAtributo(Item, "UnidadeBase"));
                if (!oCompany.Base.Artigos.Existe(Item))
                {
                    oItem.EmModoEdicao       = false;
                    oItemPrices.EmModoEdicao = false;
                }
                oCompany.Base.Artigos.Actualiza(oItem);
                oCompany.Base.ArtigosPrecos.Actualiza(oItemPrices);
                updatedCompanies.Add(company);

                oCompany.FechaEmpresaTrabalho();
            }

            return(updatedCompanies);
        }
Example #21
0
        public static PriEngine CreatContext(string Company, string User, string Password)
        {
            StdBSConfApl objAplConf = new StdBSConfApl();
            StdPlatBS    Plataforma = new StdPlatBS();
            ErpBS        MotorLE    = new ErpBS();

            EnumTipoPlataforma objTipoPlataforma;

            objTipoPlataforma = EnumTipoPlataforma.tpEmpresarial;

            objAplConf.Instancia       = "Default";
            objAplConf.AbvtApl         = "ERP";
            objAplConf.PwdUtilizador   = Password;
            objAplConf.Utilizador      = User;
            objAplConf.LicVersaoMinima = "10.00";

            StdBETransaccao objStdTransac = new StdBETransaccao();

            try
            {
                Plataforma.AbrePlataformaEmpresa(Company, objStdTransac, objAplConf, objTipoPlataforma);
            }
            catch (Exception ex)
            {
                throw (ex);
            }

            if (Plataforma.Inicializada)
            {
                MotorLE.AbreEmpresaTrabalho(objTipoPlataforma, Company, User, Password, objStdTransac, "Default");

                Platform = Plataforma;
                Engine   = MotorLE;

                EngineStatus = true;
            }

            return(engineInstance);
        }
Example #22
0
        /// <summary>
        /// Metodo para inicializar o motor do primavera
        /// </summary>
        /// <param name="tipoPlataforma"> 0 - Executiva, 1- Profissional</param>
        /// <param name="codEmpresa"></param>
        /// <param name="codUsuario"></param>
        /// <param name="password"></param>
        /// <remarks></remarks>
        public PrimaveraResultStructure AbreEmpresaPrimavera(int tipoPlataforma, string codEmpresa, string codUsuario, string password)
        {
            PrimaveraResultStructure result = new PrimaveraResultStructure();

            try
            {
                this.tipoPlataforma = tipoPlataforma;
                this.codUsuario     = codUsuario;
                this.codEmpresa     = codEmpresa;
                this.password       = password;

                if (_erpBs == null)
                {
                    _erpBs = new ErpBS();
                }
                else
                {
                    _erpBs.FechaEmpresaTrabalho();
                }

                _erpBs.AbreEmpresaTrabalho(tipoPlataforma == 0 ? EnumTipoPlataforma.tpEmpresarial : EnumTipoPlataforma.tpProfissional,
                                           codEmpresa, codUsuario, password, null, "DEFAULT", true);

                result.codigo    = 0;
                result.descricao = string.Format("Empresa {0} - {1} Aberta Com Sucesso", _erpBs.Contexto.CodEmp, _erpBs.Contexto.IDNome);
                Console.WriteLine(String.Format("[{0}] Empresa {1} - {2} Aberta Com Sucesso", DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss"), _erpBs.Contexto.CodEmp, _erpBs.Contexto.IDNome));

                return(result);
            }
            catch (Exception ex)
            {
                result.codigo    = 3;
                result.descricao = ex.Message;
                Console.WriteLine(String.Format("[{0}] Erro a abrir a Empresa {1} - {2} devido a: {3}", DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss"), _erpBs.Contexto.CodEmp, _erpBs.Contexto.IDNome, ex.Message));

                return(result);
            }
        }
        public ScriptResponse Execute(ContextData context, Entity document, Dictionary <string, object> parameters)
        {
            /* **************************************** */
            /* **************************************** */
            /*          ADD YOUR CODE HERE              */
            ErpBS bsERP          = new ErpBS();
            var   externalSystem = context.ExternalSystems.FirstOrDefault().Value;

            try
            {
                if (!externalSystem.Parameters.ContainsKey("TipoPlataforma"))
                {
                    throw new Exception("TipoPlataforma invalido");
                }

                EnumTipoPlataforma tipoPlataforma;
                if (!Enum.TryParse <EnumTipoPlataforma>((string)externalSystem.Parameters["TipoPlataforma"], out tipoPlataforma))
                {
                    throw new Exception("TipoPlataforma invalido");
                }

                try
                {
                    bsERP.AbreEmpresaTrabalho(tipoPlataforma, externalSystem.Code, (string)externalSystem.Parameters["Username"], (string)externalSystem.Parameters["Password"]);
                }
                catch (Exception e)
                {
                    throw new Exception("Erro a abrir a empresa no ERP: " + e.Message);
                }

                string str       = externalSystem.Parameters["0"].ToString();
                int    first     = str.IndexOf("Commitments.GoodsPurchaseRequest[") + "Commitments.GoodsPurchaseRequest[".Length;
                int    last      = str.LastIndexOf("].ERPCode");
                int    commIndex = int.Parse(str.Substring(first, last - first));

                StdBELista queryResults = bsERP.Consulta($"SELECT Nome,Pais FROM Fornecedores WHERE Fornecedor='{document.Commitments.GoodsPurchaseRequest[commIndex].Attributes.ERPCode}'");

                int numLinhas  = queryResults.NumLinhas();
                int numColunas = queryResults.NumColunas();

                string[] headers = new string[numColunas];
                for (short i = 0; i < numColunas; i++)
                {
                    headers[i] = queryResults.Nome(i);
                }

                object[,] data = new object[numLinhas, numColunas];
                for (short i = 0; i < numLinhas; i++)
                {
                    for (short j = 0; j < numColunas; j++)
                    {
                        var nome = headers[j];
                        data[i, j] = queryResults.Valor(nome);
                    }
                    queryResults.Seguinte();
                }

                QueryResult response = new QueryResult()
                {
                    Headers         = headers,
                    Data            = data,
                    NumberOfRecords = numLinhas
                };

                bsERP.FechaEmpresaTrabalho();

                return(new ScriptResponse
                {
                    Result = response
                });
            }
            catch (Exception ex)
            {
                bsERP.FechaEmpresaTrabalho();

                throw ex;
            }
        }
        internal static List <String> UpdateEntity(ERPContext oERPContext, string EntityType, string Entity)
        {
            Dictionary <String, String> groupCompanies = CrossCompany.Platform.GetGroupCompanies(oERPContext);
            List <String> updatedCompanies             = new List <string>();

            //Exit if no companies where found
            if (groupCompanies.Count == 0)
            {
                return(updatedCompanies);
            }

            groupCompanies.Remove(oERPContext.BSO.Contexto.CodEmp);
            foreach (string groupCompany in groupCompanies.Keys)
            {
                ErpBS oCompany = new ErpBS();

                oCompany.AbreEmpresaTrabalho(
                    StdBE100.StdBETipos.EnumTipoPlataforma.tpEmpresarial,
                    groupCompany,
                    Properties.Settings.Default.User,
                    Properties.Settings.Default.Password);

                //get the last exercise (to create the entity accounts for each exercise)
                int lastYear = oERPContext.BSO.Contabilidade.ExerciciosCBL.DaUltimoAno();

                switch (EntityType)
                {
                case "C":
                    if (Convert.ToBoolean(oERPContext.BSO.Base.Clientes.DaValorAtributo(Entity, "CDU_EntidadeGrupo")))
                    {
                        //Entity
                        BasBECliente objNewEntity = oERPContext.BSO.Base.Clientes.Edita(Entity);
                        if (!oCompany.Base.Clientes.Existe(Entity))
                        {
                            objNewEntity.EmModoEdicao = false;
                        }
                        oCompany.Base.Clientes.Actualiza(objNewEntity);
                        updatedCompanies.Add(groupCompany);

                        //Connection to CBL
                        for (int currentYear = DateTime.Now.Year; currentYear <= lastYear; currentYear++)
                        {
                            CblBECnfTabLinhaLigCBL objNewLinhaCnfTabLigCBL = oERPContext.BSO.Contabilidade.ConfiguracaoTabCBL.Edita(CblBE100.CblBECnfTabLinhaLigCBL.TETipoTabela.GCPClientes, currentYear, "001", Entity, 1);
                            if (objNewLinhaCnfTabLigCBL != null)
                            {
                                if (oCompany.Contabilidade.ConfiguracaoTabCBL.ExisteID(objNewLinhaCnfTabLigCBL.Id))
                                {
                                    oCompany.Contabilidade.ConfiguracaoTabCBL.ActualizaValorAtributoID(objNewLinhaCnfTabLigCBL.Id, "Conta", objNewLinhaCnfTabLigCBL.Conta);
                                }
                                else
                                {
                                    objNewLinhaCnfTabLigCBL.EmModoEdicao = false;
                                    CblBECnfTabLigCBL objNewCnfTabLigCBL = oCompany.Contabilidade.ConfiguracaoTabCBL.EditaTabela(CblBECnfTabLinhaLigCBL.TETipoTabela.GCPClientes);
                                    objNewCnfTabLigCBL.PlanoExercicios.GetEdita(1).Linhas.Insere(objNewLinhaCnfTabLigCBL);
                                    oCompany.Contabilidade.ConfiguracaoTabCBL.Actualiza(objNewCnfTabLigCBL);
                                }
                            }
                        }
                    }
                    break;

                case "F":
                    if (Convert.ToBoolean(oERPContext.BSO.Base.Fornecedores.DaValorAtributo(Entity, "CDU_EntidadeGrupo")))
                    {
                        //Entity
                        BasBEFornecedor objNewEntity = oERPContext.BSO.Base.Fornecedores.Edita(Entity);
                        if (!oCompany.Base.Fornecedores.Existe(Entity))
                        {
                            objNewEntity.EmModoEdicao = false;
                        }
                        oCompany.Base.Fornecedores.Actualiza(objNewEntity);
                        updatedCompanies.Add(groupCompany);

                        //Connection to CBL
                        for (int currentYear = DateTime.Now.Year; currentYear <= lastYear; currentYear++)
                        {
                            CblBECnfTabLinhaLigCBL objNewLinhaCnfTabLigCBL = oERPContext.BSO.Contabilidade.ConfiguracaoTabCBL.Edita(CblBE100.CblBECnfTabLinhaLigCBL.TETipoTabela.GCPFornecedores, currentYear, "001", Entity, 1);
                            if (objNewLinhaCnfTabLigCBL != null)
                            {
                                if (oCompany.Contabilidade.ConfiguracaoTabCBL.ExisteID(objNewLinhaCnfTabLigCBL.Id))
                                {
                                    oCompany.Contabilidade.ConfiguracaoTabCBL.ActualizaValorAtributoID(objNewLinhaCnfTabLigCBL.Id, "Conta", objNewLinhaCnfTabLigCBL.Conta);
                                }
                                else
                                {
                                    objNewLinhaCnfTabLigCBL.EmModoEdicao = false;
                                    CblBECnfTabLigCBL objNewCnfTabLigCBL = oCompany.Contabilidade.ConfiguracaoTabCBL.EditaTabela(CblBECnfTabLinhaLigCBL.TETipoTabela.GCPFornecedores);
                                    objNewCnfTabLigCBL.PlanoExercicios.GetEdita(1).Linhas.Insere(objNewLinhaCnfTabLigCBL);
                                    oCompany.Contabilidade.ConfiguracaoTabCBL.Actualiza(objNewCnfTabLigCBL);
                                }
                            }
                        }
                    }
                    break;

                case "R":
                case "D":
                    if (Convert.ToBoolean(oERPContext.BSO.Base.OutrosTerceiros.DaValorAtributo(Entity, EntityType, "CDU_EntidadeGrupo")))
                    {
                        //Entity
                        BasBEOutroTerceiro objNewEntity = oERPContext.BSO.Base.OutrosTerceiros.Edita(Entity);
                        if (!oCompany.Base.OutrosTerceiros.Existe(Entity))
                        {
                            objNewEntity.EmModoEdicao = false;
                        }
                        oCompany.Base.OutrosTerceiros.Actualiza(objNewEntity);
                        updatedCompanies.Add(groupCompany);

                        //Connection to CBL
                        for (int currentYear = DateTime.Now.Year; currentYear <= lastYear; currentYear++)
                        {
                            CblBECnfTabLinhaLigCBL objNewLinhaCnfTabLigCBL = oERPContext.BSO.Contabilidade.ConfiguracaoTabCBL.Edita(CblBE100.CblBECnfTabLinhaLigCBL.TETipoTabela.GCPOutrosTerceiros, currentYear, "001", Entity, 1);
                            if (objNewLinhaCnfTabLigCBL != null)
                            {
                                if (oCompany.Contabilidade.ConfiguracaoTabCBL.ExisteID(objNewLinhaCnfTabLigCBL.Id))
                                {
                                    oCompany.Contabilidade.ConfiguracaoTabCBL.ActualizaValorAtributoID(objNewLinhaCnfTabLigCBL.Id, "Conta", objNewLinhaCnfTabLigCBL.Conta);
                                }
                                else
                                {
                                    objNewLinhaCnfTabLigCBL.EmModoEdicao = false;
                                    CblBECnfTabLigCBL objNewCnfTabLigCBL = oCompany.Contabilidade.ConfiguracaoTabCBL.EditaTabela(CblBECnfTabLinhaLigCBL.TETipoTabela.GCPOutrosTerceiros);
                                    objNewCnfTabLigCBL.PlanoExercicios.GetEdita(1).Linhas.Insere(objNewLinhaCnfTabLigCBL);
                                    oCompany.Contabilidade.ConfiguracaoTabCBL.Actualiza(objNewCnfTabLigCBL);
                                }
                            }
                        }
                    }
                    break;

                case "E":
                    if (Convert.ToBoolean(oERPContext.BSO.CRM.EntidadesExternas.DaValorAtributo(Entity, "CDU_EntidadeGrupo")))
                    {
                        //Entity
                        CrmBEEntidadeExterna objNewEntity = oERPContext.BSO.CRM.EntidadesExternas.Edita(Entity);
                        if (!oCompany.CRM.EntidadesExternas.Existe(Entity))
                        {
                            objNewEntity.EmModoEdicao = false;
                        }
                        oCompany.CRM.EntidadesExternas.Actualiza(objNewEntity);
                        updatedCompanies.Add(groupCompany);
                    }
                    break;

                default:
                    break;
                }

                oCompany.FechaEmpresaTrabalho();
            }

            return(updatedCompanies);
        }
        internal static List <String> RemoveEntity(ERPContext oERPContext, string EntityType, string Entity)
        {
            Dictionary <String, String> groupCompanies = CrossCompany.Platform.GetGroupCompanies(oERPContext);
            List <String> updatedCompanies             = new List <string>();

            //Exit if no companies where found
            if (groupCompanies.Count == 0)
            {
                return(updatedCompanies);
            }

            groupCompanies.Remove(oERPContext.BSO.Contexto.CodEmp);
            foreach (string groupCompany in groupCompanies.Keys)
            {
                ErpBS oCompany = new ErpBS();

                oCompany.AbreEmpresaTrabalho(
                    StdBE100.StdBETipos.EnumTipoPlataforma.tpEmpresarial,
                    groupCompany,
                    Properties.Settings.Default.User,
                    Properties.Settings.Default.Password);

                switch (EntityType)
                {
                case "C":
                    if (Convert.ToBoolean(oERPContext.BSO.Base.Clientes.DaValorAtributo(Entity, "CDU_EntidadeGrupo")))
                    {
                        oCompany.Base.Clientes.Remove(Entity);
                        updatedCompanies.Add(groupCompany);
                    }
                    break;

                case "F":
                    if (Convert.ToBoolean(oERPContext.BSO.Base.Fornecedores.DaValorAtributo(Entity, "CDU_EntidadeGrupo")))
                    {
                        oCompany.Base.Fornecedores.Remove(Entity);
                        updatedCompanies.Add(groupCompany);
                    }
                    break;

                case "R":
                case "D":
                    if (Convert.ToBoolean(oERPContext.BSO.Base.OutrosTerceiros.DaValorAtributo(Entity, EntityType, "CDU_EntidadeGrupo")))
                    {
                        oCompany.Base.OutrosTerceiros.Remove(Entity);
                        updatedCompanies.Add(groupCompany);
                    }
                    break;

                case "E":
                    if (Convert.ToBoolean(oERPContext.BSO.CRM.EntidadesExternas.DaValorAtributo(Entity, "CDU_EntidadeGrupo")))
                    {
                        oCompany.CRM.EntidadesExternas.Remove(Entity);
                        updatedCompanies.Add(groupCompany);
                    }
                    break;

                default:
                    break;
                }

                oCompany.FechaEmpresaTrabalho();
            }

            return(updatedCompanies);
        }
Example #26
0
        /// <summary>
        /// Processes before open the company
        /// </summary>
        /// <param name="Cancel"></param>
        internal static void BeforeOpenCompany(ERPContext oERPContext, ref Boolean Cancel)
        {
            String             groupCategory = GetCompanyCategory(ref oERPContext);
            StdBSDialogoEspera oDialog;

            //Validation: the current company belongs to a category
            if (string.IsNullOrEmpty(groupCategory))
            {
                Cancel = true;
                oERPContext.PSO.Dialogos.MostraAviso(
                    "A empresa actual não está inserida em nenhuma categoria no administrador.",
                    StdPlatBS100.StdBSTipos.IconId.PRI_Critico,
                    "É necessário associar esta empresa à categoria onde estão inseridas as restantes empresas do grupo.");
                return;
            }

            oDialog = oERPContext.PSO.Dialogos.MostraDialogoEspera(
                sMensagem: "A processar manutenções nas empresas do grupo.",
                iNumProgressBars: 2,
                eIcon: StdBSTipos.IconId.PRI_Informativo,
                eAnim: StdBSTipos.AnimId.PRI_AviCalculos,
                sLabel1: "Calcular lista de empresas...",
                sLabel2: "Analisar lista de operações...");


            //Validation: there are further companies in the group. If not nothing should happen.
            Dictionary <String, String> groupCompanies = GetGroupCompanies(oERPContext);

            if (groupCompanies.Count == 0)
            {
                return; // No message is needed
            }


            //Validations by company
            int processedCompanies = 0;

            foreach (String groupCompany in groupCompanies.Keys)
            {
                oDialog.SetCaption(string.Format("A processar: {0}.", groupCompany), 1);

                ErpBS oCompany = new ErpBS();
                oCompany.AbreEmpresaTrabalho(
                    StdBETipos.EnumTipoPlataforma.tpEmpresarial,
                    groupCompany,
                    Properties.Settings.Default.User,
                    Properties.Settings.Default.Password);
                oDialog.ProgressBar2 = 2;

                //Check DATA MODEL
                oDialog.SetCaption("A verificar o modelo de dados...", 2);
                DataUpgrade(ref oCompany);
                oDialog.ProgressBar2 = 50;

                //Check Projects (not implemented - example for further entity validations)
                oDialog.SetCaption("A actualizar Projectos...", 2);
                //Do something
                oDialog.ProgressBar2 = 80;

                //Check default data (not implemented - example for defaults mastering)
                oDialog.SetCaption("A actualizar dados predefinidos...", 2);
                //Do something
                oDialog.ProgressBar2 = 100;


                //Final by company operations
                oCompany.FechaEmpresaTrabalho();
                oDialog.SetCaption("", 2);
                processedCompanies  += 1;
                oDialog.ProgressBar1 = Convert.ToInt32(((processedCompanies * 100) / groupCompanies.Count));
                oDialog.ProgressBar2 = 0;
            }

            oDialog.Termina();
        }
        //Method that executes the query in the external system.
        private ScriptResponse executeQuery(ContextData context, Entity document, string query)
        {
            ErpBS bsERP = new ErpBS();

            if (context.ExternalSystems == null || context.ExternalSystems.Count == 0)
            {
                throw new Exception("External System em falta");
            }

            var externalSystem = context.ExternalSystems.FirstOrDefault().Value;

            if (!externalSystem.Parameters.ContainsKey("TipoPlataforma"))
            {
                throw new Exception("TipoPlataforma inválido");
            }

            EnumTipoPlataforma tipoPlataforma;

            if (!Enum.TryParse <EnumTipoPlataforma>((string)externalSystem.Parameters["TipoPlataforma"], out tipoPlataforma))
            {
                throw new Exception("TipoPlataforma inválido");
            }

            try
            {
                bsERP.AbreEmpresaTrabalho(tipoPlataforma, externalSystem.Code, (string)externalSystem.Parameters["Username"], (string)externalSystem.Parameters["Password"]);
            }
            catch (Exception e)
            {
                throw new Exception("Erro a abrir a empresa no ERP: " + e.Message);
            }

            StdBELista queryResults = bsERP.Consulta(query);

            int numLinhas  = queryResults.NumLinhas();
            int numColunas = queryResults.NumColunas();

            string[] headers = new string[numColunas];
            for (short i = 0; i < numColunas; i++)
            {
                headers[i] = queryResults.Nome(i);
            }

            object[,] data = new object[numLinhas, numColunas];
            for (short i = 0; i < numLinhas; i++)
            {
                for (short j = 0; j < numColunas; j++)
                {
                    var nome = headers[j];
                    data[i, j] = queryResults.Valor(nome);
                }
                queryResults.Seguinte();
            }

            QueryResult response = new QueryResult()
            {
                Headers = headers,
                Data    = data
            };

            bsERP.FechaEmpresaTrabalho();

            return(new ScriptResponse
            {
                Result = response
            });
        }
        /// <summary>
        /// Import a purchases document.
        /// </summary>
        /// <param name="oERPContext"></param>
        /// <param name="Company"></param>
        /// <param name="IdDoc"></param>
        /// <returns>The reference of the created document or the error text.</returns>
        internal static Tuple <string, string> ImportPurchasesDocument(ERPContext oERPContext, String Company, String IdDoc)
        {
            Tuple <string, string> retValue = new Tuple <string, string>(String.Empty, String.Empty);
            ErpBS  oCompany   = new ErpBS();
            string strErrWarn = string.Empty;

            try
            {
                oCompany.AbreEmpresaTrabalho(
                    StdBE100.StdBETipos.EnumTipoPlataforma.tpEmpresarial,
                    Company,
                    Properties.Settings.Default.User,
                    Properties.Settings.Default.Password);

                CmpBEDocumentoCompra sourceDocument = oCompany.Compras.Documentos.EditaID(IdDoc);
                String targetDocumentType           = oCompany.Compras.TabCompras.DaValorAtributo(sourceDocument.Tipodoc, "CDU_DocDestino");


                //Error if the target document not exists in the target company
                if (!oERPContext.BSO.Vendas.TabVendas.Existe(targetDocumentType))
                {
                    throw new Exception(String.Format("O tipo de documento {0} não existe na empresa atual.", targetDocumentType));
                }
                VndBETabVenda salesTable = oERPContext.BSO.Vendas.TabVendas.Edita(targetDocumentType);


                //NEW DOCUMENT
                VndBEDocumentoVenda targetDocument = new VndBEDocumentoVenda();
                targetDocument.Filial       = "000";
                targetDocument.Serie        = oERPContext.BSO.Base.Series.DaSerieDefeito("V", targetDocumentType);
                targetDocument.Tipodoc      = targetDocumentType;
                targetDocument.TipoEntidade = "C";

                //Error if the entity doesnt exists in the target company
                if (!oERPContext.BSO.Base.Clientes.Existe(Company))
                {
                    throw new Exception(String.Format("O cliente {0} não existe na empresa atual.", Company));
                }
                targetDocument.Entidade = Company;

                targetDocument.DataDoc = sourceDocument.DataDoc;
                int preencheDadosTodos = (int)BasBETiposGcp.PreencheRelacaoVendas.vdDadosTodos;
                targetDocument = oERPContext.BSO.Vendas.Documentos.PreencheDadosRelacionados(targetDocument, ref preencheDadosTodos);
                if (targetDocument.DataVenc == default(DateTime))
                {
                    targetDocument.DataVenc = sourceDocument.DataVenc;
                }
                if (string.IsNullOrEmpty(targetDocument.CondPag))
                {
                    targetDocument.CondPag = sourceDocument.CondPag;
                }
                if (string.IsNullOrEmpty(targetDocument.ModoPag))
                {
                    targetDocument.ModoPag = sourceDocument.ModoPag;
                }
                targetDocument.DescFinanceiro = sourceDocument.DescFinanceiro;
                targetDocument.DescEntidade   = sourceDocument.DescFornecedor;
                targetDocument.CamposUtil["CDU_Exportado"].Valor = 1;

                //NEW DOCUMENT DETAILS
                foreach (CmpBELinhaDocumentoCompra detailSourceDocument in sourceDocument.Linhas)
                {
                    double quantity                = detailSourceDocument.Quantidade;
                    string targetWarehouse         = oERPContext.BSO.Base.Artigos.DaValorAtributo(detailSourceDocument.Artigo, "ArmazemSugestao") ?? detailSourceDocument.Armazem;
                    string targetWarehouseLocation = oERPContext.BSO.Base.Artigos.DaValorAtributo(detailSourceDocument.Artigo, "LocalizacaoSugestao") ?? detailSourceDocument.Localizacao;
                    targetDocument = oERPContext.BSO.Vendas.Documentos.AdicionaLinha(
                        targetDocument,
                        detailSourceDocument.Artigo,
                        ref quantity,
                        ref targetWarehouse,
                        ref targetWarehouseLocation,
                        detailSourceDocument.PrecUnit,
                        detailSourceDocument.Desconto1);
                }

                //SAVE
                string settlementSeries = string.Empty;
                if (!oERPContext.BSO.Vendas.Documentos.ValidaActualizacao(targetDocument, salesTable, ref settlementSeries, ref strErrWarn))
                {
                    throw new Exception(strErrWarn);
                }
                else
                {
                    oERPContext.BSO.Vendas.Documentos.Actualiza(targetDocument, ref strErrWarn);

                    retValue = Tuple.Create <string, string>(
                        string.Format("{0} {1}/{2}", targetDocument.Tipodoc, targetDocument.Serie, targetDocument.NumDoc.ToString()),
                        strErrWarn);

                    oCompany.DSO.ExecuteSQL(string.Format("UPDATE CabecCompras SET CDU_Exportado=1 WHERE ID='{0}'", sourceDocument.ID));
                    //TODO: Eliminar (foi adicionado porque o objeto não estava a gravar os valores dos CDUs)
                    oERPContext.BSO.DSO.ExecuteSQL(string.Format("UPDATE CabecDoc SET CDU_Exportado=1 WHERE ID='{0}'", targetDocument.ID));
                }
            }
            catch (Exception e)
            {
                retValue = Tuple.Create <string, string>("ERRO", e.Message);
            }
            finally
            {
                if (oCompany != null)
                {
                    oCompany.FechaEmpresaTrabalho();
                }
            }

            return(retValue);
        }