Exemplo n.º 1
0
        }//fin MenuEvent

        //Para PEru EasyDot
        public new void EnviarFE_PE_ED(String DocEntry, Boolean RunningUnderSQLServer, String SeriePE, String FolioNum, String TipoDocElec, String sObjType, String lRUC)
        {
            String      URL;
            String      URL_PDF;
            String      ProcedimientoE;
            String      ProcedimientoD;
            XmlDocument oXml = null;
            String      userED;
            String      passED;
            TFunctions  Reg = new TFunctions();

            SAPbobsCOM.Company Cmpny = SBO_f.Cmpny;
            Reg.SBO_f = SBO_f;
            String    Status;
            String    sMessage = "";
            Int32     lRetCode;
            String    DocDate = "";
            XDocument miXML   = null;
            XElement  xNodo   = null;
            String    ExternalFolio;

            SAPbobsCOM.Recordset ors = ((SAPbobsCOM.Recordset)Cmpny.GetBusinessObject(BoObjectTypes.BoRecordset));
            String        sXML;
            TDLLparaXMLPE Dll = new TDLLparaXMLPE();

            Dll.SBO_f = SBO_f;
            String MostrarXML = "N";

            try
            {
                if (RunningUnderSQLServer)
                {
                    s = @"SELECT U_URLEasyDot 'URL', ISNULL(U_UserED,'') 'User', ISNULL(U_PwdED,'') 'Pass', ISNULL(U_MostrarXML,'N') 'MostrarXML' FROM [@VID_FEPARAM]";
                }
                else
                {
                    s = @"SELECT ""U_URLEasyDot"" ""URL"", IFNULL(""U_UserED"",'') ""User"", IFNULL(""U_PwdED"",'') ""Pass"", IFNULL(""U_MostrarXML"",'N') ""MostrarXML"" FROM ""@VID_FEPARAM"" ";
                }

                ors.DoQuery(s);
                if (ors.RecordCount == 0)
                {
                    SBO_f.SBOApp.StatusBar.SetText("No se ha ingresado URL", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                }
                else if (((System.String)ors.Fields.Item("URL").Value).Trim() == "")
                {
                    SBO_f.SBOApp.StatusBar.SetText("No se ha ingresado URL", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                }
                else if (((System.String)ors.Fields.Item("User").Value).Trim() == "")
                {
                    throw new Exception("No se encuentra usuario en Parametros");
                }
                else if (((System.String)ors.Fields.Item("Pass").Value).Trim() == "")
                {
                    throw new Exception("No se encuentra password en Parametros");
                }
                else
                {
                    userED     = Reg.DesEncriptar((System.String)(ors.Fields.Item("User").Value).ToString().Trim());
                    passED     = Reg.DesEncriptar((System.String)(ors.Fields.Item("Pass").Value).ToString().Trim());
                    MostrarXML = ((System.String)ors.Fields.Item("MostrarXML").Value).Trim();

                    URL     = ((System.String)ors.Fields.Item("URL").Value).Trim() + "/SendRetencion.ashx";
                    URL_PDF = ((System.String)ors.Fields.Item("URL").Value).Trim() + "/SendPdf.ashx";
                    //validar que exista procedimentos para tipo documento
                    if (RunningUnderSQLServer)
                    {
                        s = "select ISNULL(U_ProcNomE,'') 'ProcNomE', ISNULL(U_ProcNomD,'') 'ProcNomD' FROM [@VID_FEPROCED] where ISNULL(U_Habili,'N') = 'Y' and U_TipoDocPE = '{0}'";
                    }
                    else
                    {
                        s = @"select IFNULL(""U_ProcNomE"",'') ""ProcNomE"", IFNULL(""U_ProcNomD"",'') ""ProcNomD"" FROM ""@VID_FEPROCED"" where IFNULL(""U_Habili"",'N') = 'Y' and ""U_TipoDocPE"" = '{0}'";
                    }

                    s = String.Format(s, TipoDocElec);
                    ors.DoQuery(s);
                    if (ors.RecordCount == 0)
                    {
                        throw new Exception("No se encuentra procedimientos para Documento electronico " + TipoDocElec);
                    }
                    else
                    {
                        ProcedimientoE = ((System.String)ors.Fields.Item("ProcNomE").Value).Trim();
                        ProcedimientoD = ((System.String)ors.Fields.Item("ProcNomD").Value).Trim();

                        if (ProcedimientoE == "")
                        {
                            throw new Exception("No se encuentra procedimiento de encabezado para Documento electronico " + TipoDocElec);
                        }
                        else if (ProcedimientoD == "")
                        {
                            throw new Exception("No se encuentra procedimiento de detalle para Documento electronico " + TipoDocElec);
                        }

                        if (RunningUnderSQLServer)
                        {
                            s = @"exec {0} {1}, '{2}', '{3}'";//Encabezado
                        }
                        else
                        {
                            s = @"CALL {0} ({1}, '{2}', '{3}')";
                        }
                        s = String.Format(s, ProcedimientoE, DocEntry, TipoDocElec, sObjType);
                        ors.DoQuery(s);

                        if (ors.RecordCount == 0)
                        {
                            throw new Exception("No se encuentra datos para Documento electronico " + TipoDocElec);
                        }
                        else
                        {
                            var bImpresion = false;
                            ExternalFolio = ((System.String)ors.Fields.Item("IdDocumento").Value).Trim();
                            miXML         = new XDocument(
                                new XDeclaration("1.0", "utf-8", "yes"),
                                new XElement("DocumentoElectronico"));

                            sXML = Dll.GenerarXMLStringPayment(ref ors, TipoDocElec, ref miXML, "E");
                            if (sXML == "")
                            {
                                throw new Exception("Problema para generar xml Documento electronico " + TipoDocElec);
                            }

                            //DETALLE
                            if (RunningUnderSQLServer)
                            {
                                s = @"exec {0} {1}, '{2}', '{3}'";
                            }
                            else
                            {
                                s = @"CALL {0} ({1}, '{2}', '{3}')";
                            }
                            s = String.Format(s, ProcedimientoD, DocEntry, TipoDocElec, sObjType);
                            ors.DoQuery(s);

                            if (ors.RecordCount == 0)
                            {
                                throw new Exception("No se encuentra datos de detalle para Documento electronico " + TipoDocElec);
                            }
                            else
                            {
                                sXML = Dll.GenerarXMLStringPayment(ref ors, TipoDocElec, ref miXML, "D");
                                if (sXML == "")
                                {
                                    throw new Exception("Problema para generar xml Documento electronico " + TipoDocElec);
                                }

                                oXml = new XmlDocument();
                                using (var xmlReader = miXML.CreateReader())
                                {
                                    oXml.Load(xmlReader);
                                }

                                //Agrega el PDF al xml
                                XmlNode node;
                                if (oXml.SelectSingleNode("//CamposExtras") == null)
                                {
                                    node = oXml.CreateNode(XmlNodeType.Element, "CamposExtras", null);
                                }
                                else
                                {
                                    node = oXml.SelectSingleNode("//CamposExtras");
                                }

                                if (MostrarXML == "Y")
                                {
                                    SBO_f.oLog.OutLog(oXml.InnerXml);
                                }
                                //ENVIO AL PORTAL
                                s = Reg.UpLoadDocumentByUrl2(oXml, null, RunningUnderSQLServer, URL, userED, passED, TipoDocElec + "_" + ExternalFolio);

                                oXml.LoadXml(s);
                                //var Configuracion = oXml.GetElementsByTagName("Error");
                                var lista     = ((XmlElement)oXml.GetElementsByTagName("Error")[0]).GetElementsByTagName("ErrorText");
                                var ErrorText = lista[0].InnerText;
                                if (ErrorText.Length > 250)
                                {
                                    ErrorText = ErrorText.Substring(0, 250);
                                }
                                lista = ((XmlElement)oXml.GetElementsByTagName("Error")[0]).GetElementsByTagName("ErrorCode");
                                var ErrorCode = lista[0].InnerText;
                                lista = ((XmlElement)oXml.GetElementsByTagName("Error")[0]).GetElementsByTagName("PDF417");
                                var PDF417 = lista[0].InnerText;
                                lista = ((XmlElement)oXml.GetElementsByTagName("Error")[0]).GetElementsByTagName("IdDocument");
                                var IdDocument = lista[0].InnerText;

                                if (ErrorCode != "0")
                                {
                                    SBO_f.SBOApp.StatusBar.SetText("Error envio documento electrónico (1)", SAPbouiCOM.BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                                    SBO_f.oLog.OutLog("Error en envio documento electronico al portal (1) Codigo Error Portal: " + ErrorCode + " Mensaje Portal: " + ErrorText);
                                    //sObjType = "13";
                                    if (ErrorCode == "-103")
                                    {
                                        Status = "RR";
                                    }
                                    else
                                    {
                                        Status = "EE";
                                    }
                                    sMessage = ErrorText;
                                    var emsg = sMessage;
                                    if (sMessage == "")
                                    {
                                        sMessage = "Error envio documento electronico a EasyDot";
                                    }

                                    var oPayments1 = (SAPbobsCOM.Documents)(Cmpny.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oVendorPayments));
                                    if (oPayments1.GetByKey(Convert.ToInt32(DocEntry)))
                                    {
                                        DocDate = SBO_f.DateToStr(oPayments1.DocDate);
                                        if (emsg == "")
                                        {
                                            oPayments1.UserFields.Fields.Item("U_EstadoFE").Value = "N";
                                        }
                                        else if (Status == "EE")
                                        {
                                            oPayments1.UserFields.Fields.Item("U_EstadoFE").Value = "P";
                                        }
                                        else if (Status == "RR")
                                        {
                                            oPayments1.UserFields.Fields.Item("U_EstadoFE").Value = "A";
                                        }
                                        else
                                        {
                                            oPayments1.UserFields.Fields.Item("U_EstadoFE").Value = "P";
                                        }

                                        lRetCode = oPayments1.Update();
                                        if (lRetCode != 0)
                                        {
                                            s = SBO_f.Cmpny.GetLastErrorDescription();
                                            SBO_f.SBOApp.StatusBar.SetText("Error actualizar documento - " + s, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Warning);
                                            sMessage = "Error actualizar documento - " + s;
                                            SBO_f.oLog.OutLog(sMessage);
                                        }
                                    }
                                }
                                else
                                {
                                    if (PDF417 == "")
                                    {
                                        SBO_f.oLog.OutLog("No se ha recibido PDF417 -> " + ExternalFolio);
                                        SBO_f.SBOApp.StatusBar.SetText("No se ha recibido PDF417", SAPbouiCOM.BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                                    }
                                    Status = "RR";
                                    //sObjType = "13";
                                    sMessage = "Enviado satisfactoriamente a EasyDot y Aceptado";
                                    SBO_f.SBOApp.StatusBar.SetText("Se ha enviado satisfactoriamente el documento electronico", SAPbouiCOM.BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                                    var oPayments = ((SAPbobsCOM.Payments)Cmpny.GetBusinessObject(BoObjectTypes.oVendorPayments));
                                    if (oPayments.GetByKey(Convert.ToInt32(DocEntry)))
                                    {
                                        DocDate = SBO_f.DateToStr(oPayments.DocDate);
                                        //oPayments.Printed = PrintStatusEnum.psYes;
                                        oPayments.UserFields.Fields.Item("U_EstadoFE").Value = "A";
                                        oPayments.UserFields.Fields.Item("U_PDF417").Value   = PDF417.Trim();
                                        lRetCode = oPayments.Update();
                                        if (lRetCode != 0)
                                        {
                                            s = SBO_f.Cmpny.GetLastErrorDescription();
                                            SBO_f.SBOApp.StatusBar.SetText("Error actualizar documento - " + s, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Warning);
                                            sMessage = "Error actualizar documento - " + s;
                                            SBO_f.oLog.OutLog(sMessage);
                                        }
                                        else
                                        {
                                            bImpresion = true;
                                        }
                                    }
                                    else
                                    {
                                        sMessage   = "No se ha encontrado documento al actualizar Impresion";
                                        bImpresion = false;
                                    }
                                }
                                oXml = null;

                                if (RunningUnderSQLServer)
                                {
                                    s = "SELECT DocEntry, U_Status, U_Id FROM [@VID_FELOG] WITH (NOLOCK) WHERE U_DocEntry = {0} AND U_ObjType = '{1}'";
                                }
                                else
                                {
                                    s = @"SELECT ""DocEntry"", ""U_Status"", ""U_Id"" FROM ""@VID_FELOG"" WHERE ""U_DocEntry"" = {0} AND ""U_ObjType"" = '{1}' ";
                                }
                                s = String.Format(s, DocEntry, sObjType);
                                ors.DoQuery(s);
                                if (ors.RecordCount == 0)
                                {
                                    Reg.FELOGAdd(Int32.Parse(DocEntry), sObjType, "--", SeriePE, Int32.Parse(FolioNum), Status, sMessage, TipoDocElec, SBO_f.SBOApp.Company.UserName, "", IdDocument, ErrorText, DocDate, ExternalFolio);
                                }
                                else
                                {
                                    if ((System.String)(ors.Fields.Item("U_Status").Value) != "RR")
                                    {
                                        SBO_f.SBOApp.StatusBar.SetText("Documento se ha enviado a EasyDot", SAPbouiCOM.BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                                        Reg.FELOGUptM((System.Int32)(ors.Fields.Item("DocEntry").Value), Int32.Parse(DocEntry), sObjType, "--", SeriePE, Int32.Parse(FolioNum), Status, sMessage, TipoDocElec, SBO_f.SBOApp.Company.UserName, "", (IdDocument == "0" ? ((System.String)ors.Fields.Item("U_Id").Value).Trim() : IdDocument), ErrorText, DocDate, ExternalFolio);
                                    }
                                    else
                                    {
                                        SBO_f.SBOApp.StatusBar.SetText("Documento ya se ha enviado anteriormente a EasyDot y se encuentra en Sunat", SAPbouiCOM.BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                                    }
                                }

                                if ((bImpresion) && (PDF417 != ""))
                                {
                                    //obtiene string de pdf
                                    var sPDF = Reg.PDFenString(TipoDocElec, DocEntry, sObjType, SeriePE, FolioNum, RunningUnderSQLServer);

                                    /*var sjson = @"<root><DocType>{0}</DocType><DocNum>{1}</DocNum><RUC>{2}</RUC><PDF>{3}</PDF></root>";
                                     * sjson = String.Format(sjson, TipoDocElec, ExternalFolio, RUC, sPDF);
                                     * XmlDocument xm = new XmlDocument();
                                     * xm.LoadXml(sjson);
                                     * String json = JsonConvert.SerializeXmlNode(xm);*/
                                    var sjson = @"""DocType"":""{0}"",""DocNum"":""{1}"",""RUC"":""{2}"",""PDF"":""{3}""";
                                    sjson = String.Format(sjson, TipoDocElec, ExternalFolio, lRUC, sPDF);
                                    sjson = "{" + sjson + "}";
                                    s     = Reg.UpLoadDocumentByUrl(null, sjson, RunningUnderSQLServer, URL_PDF, userED, passED, TipoDocElec + "_" + ExternalFolio);


                                    SBO_f.SBOApp.StatusBar.SetText("PDF enviado al portal", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception x)
            {
                SBO_f.SBOApp.StatusBar.SetText("EnviarFE_PE_ED: " + x.Message + " ** Trace: " + x.StackTrace, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                SBO_f.oLog.OutLog("EnviarFE_PE_ED: " + x.Message + " ** Trace: " + x.StackTrace);
            }
            finally
            {
                SBO_f._ReleaseCOMObject(ors);
                SBO_f._ReleaseCOMObject(oXml);
                SBO_f._ReleaseCOMObject(miXML);
                SBO_f._ReleaseCOMObject(xNodo);
            }
        }
        }//fin MenuEvent

        private void ActualizarRegistrosWS()
        {
            String sCode = "";

            //SqlDataAdapter cmd2;
            System.Data.DataTable resultDataTable;
            //System.Data.DataTable resultDataTable1;
            Int32   i;
            Boolean _return;

            SAPbouiCOM.GridColumn oColumn;
            String sDocEntry = "";

            SAPbobsCOM.Recordset orsAux;
            String RUTEmpresa = "";
            String URL        = "";
            String URLFinal;

            String[]    TipoDocs = { "33", "34", "39", "41", "43", "46", "52", "56", "61", "110", "111", "112" };
            String      UserWS   = "";
            String      PassWS   = "";
            String      sMessage;
            String      xmlCAF = "";
            XmlDocument oXml;
            String      Desde = "";
            String      Hasta = "";
            String      Fecha = "";

            try
            {
                ActualizarGrilla();

                orsAux = (SAPbobsCOM.Recordset)(FCmpny.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset));

                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"SELECT U_BuscarCAF, ISNULL(U_UserWSCL,'') 'UserWS', ISNULL(U_PassWSCL,'') 'PassWS' FROM [@VID_FEPARAM] WHERE Code = '1'";
                }
                else
                {
                    s = @"SELECT ""U_BuscarCAF"", IFNULL(""U_UserWSCL"",'') ""UserWS"", IFNULL(""U_PassWSCL"",'') ""PassWS"" FROM ""@VID_FEPARAM"" WHERE ""Code"" = '1'";
                }
                orsAux.DoQuery(s);

                if (orsAux.RecordCount == 0)
                {
                    throw new Exception("Debe parametrizar el addon");
                }
                else if (((System.String)orsAux.Fields.Item("U_BuscarCAF").Value).Trim() == "")
                {
                    throw new Exception("Debe ingresar http para buscar CAF en paramatros del addon");
                }
                else
                {
                    URL = ((System.String)orsAux.Fields.Item("U_BuscarCAF").Value).Trim();
                    if (((System.String)orsAux.Fields.Item("UserWS").Value).Trim() != "")
                    {
                        UserWS = Funciones.DesEncriptar(((System.String)orsAux.Fields.Item("UserWS").Value).Trim());
                    }
                    if (((System.String)orsAux.Fields.Item("PassWS").Value).Trim() != "")
                    {
                        PassWS = Funciones.DesEncriptar(((System.String)orsAux.Fields.Item("PassWS").Value).Trim());
                    }
                }

                if (bMultiSoc)
                {
                    if (GlobalSettings.RunningUnderSQLServer)
                    {
                        s = @"SELECT DocEntry, REPLACE(REPLACE(ISNULL(U_RUT,''),'.',''),'-','') TaxIdNum FROM [@VID_FEMULTISOC] WHERE U_Habilitada = 'Y'";
                    }
                    else
                    {
                        s = @"SELECT TO_VARCHAR(""DocEntry"") ""DocEntry"", REPLACE(REPLACE(IFNULL(""U_RUT"",''),'.',''),'-','') ""TaxIdNum"" FROM ""@VID_FEMULTISOC"" WHERE ""U_Habilitada"" = 'Y' ";
                    }
                }
                else
                {
                    if (GlobalSettings.RunningUnderSQLServer)
                    {
                        s = @"SELECT REPLACE(REPLACE(ISNULL(TaxIdNum,''),'-',''),'.','') TaxIdNum FROM OADM";
                    }
                    else
                    {
                        s = @"SELECT REPLACE(REPLACE(IFNULL(""TaxIdNum"",''),'-',''),'.','') ""TaxIdNum"" FROM ""OADM"" ";
                    }
                }
                oRecordSet.DoQuery(s);

                if (oRecordSet.RecordCount > 0)
                {
                    while (!oRecordSet.EoF)
                    {
                        try
                        {
                            RUTEmpresa = ((System.String)oRecordSet.Fields.Item("TaxIdNum").Value).Trim();
                            if (bMultiSoc)
                            {
                                sDocEntry = Convert.ToString((System.Int32)(oRecordSet.Fields.Item("DocEntry").Value));
                            }
                            else
                            {
                                sDocEntry = "0";
                            }

                            foreach (String xTipo in TipoDocs)
                            {
                                try
                                {
                                    //http://portal1.easydoc.cl/consulta/generaciondte.aspx?RUT={0}&TIPODTE={1}&OP=22
                                    URLFinal = URL;
                                    URLFinal = String.Format(URLFinal, RUTEmpresa, xTipo);


                                    WebRequest request = WebRequest.Create(URLFinal);
                                    if ((UserWS != "") && (PassWS != ""))
                                    {
                                        request.Credentials = new NetworkCredential(UserWS, PassWS);
                                    }
                                    request.Method = "POST";
                                    string postData  = "";//** xmlDOC.InnerXml;
                                    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                                    request.ContentType   = "text/xml";
                                    request.ContentLength = byteArray.Length;
                                    Stream dataStream = request.GetRequestStream();
                                    dataStream.Write(byteArray, 0, byteArray.Length);
                                    dataStream.Close();
                                    WebResponse response = request.GetResponse();
                                    Console.WriteLine(((HttpWebResponse)(response)).StatusDescription);
                                    dataStream = response.GetResponseStream();
                                    StreamReader reader             = new StreamReader(dataStream);
                                    string       responseFromServer = reader.ReadToEnd();
                                    reader.Close();
                                    dataStream.Close();
                                    response.Close();
                                    sMessage = responseFromServer;
                                    request  = null;
                                    response = null;
                                    GC.Collect();
                                    GC.WaitForPendingFinalizers();

                                    if (sMessage != "")
                                    {
                                        xmlCAF = sMessage;
                                        xmlCAF = xmlCAF.Replace(@"<?xml version=""1.0""?>", "");
                                        //xmlCAF = xmlCAF.Replace("\n", "");
                                        //xmlCAF = xmlCAF.Replace(@"\", "");
                                        //xmlCAF = xmlCAF.Replace(Environment.NewLine, "");
                                        oXml = new XmlDocument();
                                        oXml.LoadXml(xmlCAF);

                                        var DA  = oXml.GetElementsByTagName("DA");
                                        var RNG = ((XmlElement)DA[0]).GetElementsByTagName("RNG");
                                        foreach (XmlElement nodo in RNG)
                                        {
                                            var nDesde = nodo.GetElementsByTagName("D");
                                            var nHasta = nodo.GetElementsByTagName("H");
                                            Desde = (System.String)(nDesde[0].InnerText);
                                            Hasta = (System.String)(nHasta[0].InnerText);
                                        }

                                        var CAF = oXml.GetElementsByTagName("CAF");
                                        var DA2 = ((XmlElement)CAF[0]).GetElementsByTagName("DA");
                                        foreach (XmlElement nodo in CAF)
                                        {
                                            var nFecha = nodo.GetElementsByTagName("FA");
                                            Fecha = (System.String)(nFecha[0].InnerText);
                                        }

                                        if (GlobalSettings.RunningUnderSQLServer)
                                        {
                                            s = @"SELECT Code
                                          FROM [@VID_FECAF]
                                         WHERE U_TipoDoc = '{0}'
                                           AND U_Desde = {1}
                                           AND U_Hasta = {2}
                                           {3}";
                                        }
                                        else
                                        {
                                            s = @"SELECT ""Code""
                                          FROM ""@VID_FECAF""
                                         WHERE ""U_TipoDoc"" = '{0}'
                                           AND ""U_Desde"" = {1}
                                           AND ""U_Hasta"" = {2}
                                            {3}";
                                        }
                                        s = String.Format(s, xTipo, Desde, Hasta, (bMultiSoc ? " AND U_BaseMul = " + sDocEntry : ""));
                                        orsAux.DoQuery(s);
                                        if (orsAux.RecordCount == 0) //no existe en la base de datos
                                        {
                                            sCode = Funciones.sNuevoDocEntryLargo("@VID_FECAF", GlobalSettings.RunningUnderSQLServer);
                                            oDBDSH.Clear();
                                            oDBDSH.InsertRecord(0);
                                            oDBDSH.SetValue("Code", 0, sCode);
                                            //OutLog("Code -> " + oDBDSH.GetValue("Code",0));
                                            oDBDSH.SetValue("U_TipoDoc", 0, xTipo);
                                            //OutLog("TipoDoc -> " + oDBDSH.GetValue("U_TipoDoc", 0));
                                            oDBDSH.SetValue("U_Desde", 0, Desde);
                                            //OutLog("Desde -> " + oDBDSH.GetValue("U_Desde", 0));
                                            oDBDSH.SetValue("U_Hasta", 0, Hasta);
                                            //OutLog("Hasta -> " + oDBDSH.GetValue("U_Hasta", 0));
                                            DateTime oFecha;
                                            DateTime.TryParse(Fecha, out oFecha);
                                            oDBDSH.SetValue("U_Fecha", 0, oFecha.ToString("yyyyMMdd"));
                                            //OutLog("Fecha -> " + oDBDSH.GetValue("U_Fecha", 0));
                                            oDBDSH.SetValue("U_BaseMul", 0, sDocEntry);
                                            //OutLog("BaseMul -> " + oDBDSH.GetValue("U_BaseMul", 0));
                                            oDBDSH.SetValue("U_CAF", 0, xmlCAF);
                                            //OutLog("CAF -> " + oDBDSH.GetValue("U_CAF", 0));
                                            oDBDSH.SetValue("U_Utilizados", 0, "0");
                                            //OutLog("Utilizados -> " + oDBDSH.GetValue("U_Utilizados", 0));
                                            var iDif = (Convert.ToInt32(Hasta) - Convert.ToInt32(Desde)) + 1;
                                            oDBDSH.SetValue("U_Asignables", 0, iDif.ToString());
                                            //OutLog("Asignables -> " + oDBDSH.GetValue("U_Asignables", 0));
                                            oDBDSH.SetValue("U_FolioDesde", 0, Desde);
                                            //OutLog("FolioDesde -> " + oDBDSH.GetValue("U_FolioDesde", 0));
                                            _return = Funciones.CAFAdd(oDBDSH);
                                            if (_return)
                                            {
                                                FSBOApp.StatusBar.SetText("CAF Registrado, TipoDoc " + xTipo, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                                            }
                                            else
                                            {
                                                FSBOApp.StatusBar.SetText("CAF no se ha registrado, TipoDoc " + xTipo, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        FSBOApp.StatusBar.SetText("No se ha encontrado CAF para documento " + xTipo, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Warning);
                                    }
                                }
                                catch (Exception v)
                                {
                                    OutLog("Error actualizar CAF Tipo " + xTipo + " RUT Empresa " + RUTEmpresa + ", " + v.Message + ", TRACE " + v.StackTrace);
                                    FSBOApp.StatusBar.SetText("Error actualizar CAF Tipo " + xTipo + " RUT Empresa " + RUTEmpresa + ", " + v.Message, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                                }
                            }//Fin Foreach
                            FSBOApp.StatusBar.SetText("CAF actualizados", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                        }
                        catch (Exception v)
                        {
                            OutLog("Error actualizar empresa RUT " + RUTEmpresa + ", " + v.Message + ", TRACE " + v.StackTrace);
                            FSBOApp.StatusBar.SetText("Error actualizar empresa RUT " + RUTEmpresa + ", " + v.Message, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                        }
                        oRecordSet.MoveNext();
                    }

                    ActualizarGrilla();
                }
                else
                {
                    FSBOApp.StatusBar.SetText("Debe ingresar datos de conexion", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                }
            }
            catch (Exception e)
            {
                FSBOApp.MessageBox(e.Message + " ** Trace: " + e.StackTrace, 1, "Ok", "", "");
                OutLog("ActualizarRegistros: " + e.Message + " ** Trace: " + e.StackTrace);
            }
        }//fin ActualizarRegistros
        }//fin ActualizarRegistros

        private void ActualizarRegistros()
        {
            TFunctions     Reg;
            String         sCode = "";
            SqlDataAdapter cmd;
            //SqlDataAdapter cmd2;
            SqlConnection ConexionADO;

            System.Data.DataTable resultDataTable;
            //System.Data.DataTable resultDataTable1;
            Int32   i;
            Boolean _return;
            String  sCnn;

            SAPbouiCOM.GridColumn oColumn;
            Boolean    bExiste;
            SqlCommand cmd1;
            Int32      iDif;
            String     User, Pass, sDocEntry;

            SAPbobsCOM.Recordset orsAux;

            try
            {
                ActualizarGrilla();

                orsAux = (SAPbobsCOM.Recordset)(FCmpny.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset));

                if (bMultiSoc)
                {
                    if (GlobalSettings.RunningUnderSQLServer)
                    {
                        s = @"select DocEntry, U_Servidor, U_Base, U_Usuario, U_Password from [@VID_FEMULTISOC] where U_Habilitada = 'Y'";
                    }
                    else
                    {
                        s = @"select TO_VARCHAR(""DocEntry"") ""DocEntry"", ""U_Servidor"", ""U_Base"", ""U_Usuario"", ""U_Password"" from ""@VID_FEMULTISOC"" where ""U_Habilitada"" = 'Y' ";
                    }
                }
                else
                {
                    if (GlobalSettings.RunningUnderSQLServer)
                    {
                        s = @"select TOP 1 * from [@VID_FEPARAM]";
                    }
                    else
                    {
                        s = @"select TOP 1 * from ""@VID_FEPARAM"" ";
                    }
                }
                oRecordSet.DoQuery(s);
                if (oRecordSet.RecordCount > 0)
                {
                    Reg       = new TFunctions();
                    Reg.SBO_f = FSBOf;
                    while (!oRecordSet.EoF)
                    {
                        if (bMultiSoc)
                        {
                            User = (System.String)(oRecordSet.Fields.Item("U_Usuario").Value);
                            Pass = (System.String)(oRecordSet.Fields.Item("U_Password").Value);
                        }
                        else
                        {
                            User = Reg.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_Usuario").Value));
                            Pass = Reg.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_Password").Value));
                        }

                        sCnn      = Reg.sConexion((System.String)(oRecordSet.Fields.Item("U_Servidor").Value), (System.String)(oRecordSet.Fields.Item("U_Base").Value), User, Pass);
                        sDocEntry = Convert.ToString((System.Int32)(oRecordSet.Fields.Item("DocEntry").Value));
                        if (sCnn.Substring(0, 1) != "E")
                        {
                            ConexionADO = new SqlConnection(sCnn);
                            if (ConexionADO.State == ConnectionState.Closed)
                            {
                                ConexionADO.Open();
                            }

                            s = @"SELECT CAST(TPDOCUMENTO AS VARCHAR(20)) 'TipoDoc'
                                  ,CAST(RANGODESDE AS VARCHAR(20)) 'Desde'
	                              ,CAST(RANGOHASTA AS VARCHAR(20)) 'Hasta'
	                              ,CONVERT(Char(8),FECHA,112) 'Fecha'
                                  ,CAST((RANGOHASTA - (RANGODESDE + UTILIZADOS)) + 1 AS VARCHAR(20)) 'Asig'
                                  ,CAST(ID as varchar(20)) 'ID'
						          ,CAST((RANGODESDE + UTILIZADOS) AS VARCHAR(20)) 'FolioDesde'
                                  ,CAST(UTILIZADOS AS VARCHAR(20)) 'Utilizados'
                                  ,ISNULL(XML_CAF,'') 'XML_CAF'
                              FROM folios WITH(nolock)";

                            cmd             = new SqlDataAdapter(s, ConexionADO);
                            resultDataTable = new System.Data.DataTable();
                            cmd.Fill(resultDataTable);
                            foreach (System.Data.DataRow oRow in resultDataTable.Rows)
                            {
                                bExiste = false;
                                i       = 0;
                                if (!oDataTable.IsEmpty)
                                {
                                    while (i < oDataTable.Rows.Count)
                                    {
                                        s = oDataTable.Rows.Count.ToString();
                                        var dFecha = (System.DateTime)(oDataTable.GetValue("U_Fecha", i));
                                        if (((System.String)(oDataTable.GetValue("U_TipoDoc", i)) == oRow.Field <String>("TipoDoc").ToString()) &&
                                            (Convert.ToString((System.Int32)(oDataTable.GetValue("U_Desde", i))) == oRow.Field <String>("Desde")) &&
                                            (Convert.ToString((System.Int32)(oDataTable.GetValue("U_Hasta", i))) == oRow.Field <String>("Hasta")) &&
                                            (dFecha.ToString("yyyyMMdd") == oRow.Field <String>("Fecha")))
                                        {
                                            bExiste = true;
                                            i       = oDataTable.Rows.Count;
                                        }
                                        i++;
                                    }
                                }

                                if (!bExiste)
                                {
                                    sCode = Reg.sNuevoDocEntryLargo("@VID_FECAF", GlobalSettings.RunningUnderSQLServer);
                                    oDBDSH.Clear();
                                    oDBDSH.InsertRecord(0);
                                    oDBDSH.SetValue("Code", 0, sCode);
                                    //OutLog("Code -> " + oDBDSH.GetValue("Code",0));
                                    oDBDSH.SetValue("U_TipoDoc", 0, oRow.Field <String>("TipoDoc"));
                                    //OutLog("TipoDoc -> " + oDBDSH.GetValue("U_TipoDoc", 0));
                                    oDBDSH.SetValue("U_Desde", 0, oRow.Field <String>("Desde"));
                                    //OutLog("Desde -> " + oDBDSH.GetValue("U_Desde", 0));
                                    oDBDSH.SetValue("U_Hasta", 0, oRow.Field <String>("Hasta"));
                                    //OutLog("Hasta -> " + oDBDSH.GetValue("U_Hasta", 0));
                                    oDBDSH.SetValue("U_Fecha", 0, oRow.Field <String>("Fecha"));
                                    //OutLog("Fecha -> " + oDBDSH.GetValue("U_Fecha", 0));
                                    oDBDSH.SetValue("U_BaseMul", 0, sDocEntry);
                                    //OutLog("BaseMul -> " + oDBDSH.GetValue("U_BaseMul", 0));
                                    s = oRow.Field <String>("XML_CAF");
                                    oDBDSH.SetValue("U_CAF", 0, s);
                                    //OutLog("CAF -> " + oDBDSH.GetValue("U_CAF", 0));

                                    iDif = (Int32.Parse(oRow.Field <String>("Hasta")) - Int32.Parse(oRow.Field <String>("Desde"))) + 1;

                                    cmd1 = new SqlCommand();
                                    cmd1.CommandTimeout = 0;
                                    cmd1.CommandType    = CommandType.Text;
                                    cmd1.Connection     = ConexionADO;
                                    s = @"WITH n(n) AS
                                        (
                                        SELECT 1
                                            UNION ALL
                                        SELECT n + 1 
                                          FROM n WHERE n < {0} )
                                        SELECT COUNT(*) --n + {1} , T0.CAB_FOL_DOCTO_INT
                                          FROM n left outer join Faet_Erp_Encabezado_Doc T0 on n.n + {1} = T0.CAB_FOL_DOCTO_INT and T0.CAB_COD_TP_FACTURA = '{2}' 
                                           and T0.CAB_FOL_DOCTO_INT between {3} and {4} 
                                          where t0.CAB_FOL_DOCTO_INT is not null 
                                        --ORDER BY n 
                                        OPTION (MAXRECURSION 0)"; // antes OPTION (MAXRECURSION {0})";

                                    s = String.Format(s, iDif.ToString(), Int32.Parse(oRow.Field <String>("Desde")) - 1, oRow.Field <String>("TipoDoc"), oRow.Field <String>("Desde"), oRow.Field <String>("Hasta"));
                                    cmd1.CommandText = s;

                                    s = cmd1.ExecuteScalar().ToString();

                                    oDBDSH.SetValue("U_Utilizados", 0, s);
                                    //OutLog("Utilizados -> " + oDBDSH.GetValue("U_Utilizados", 0));
                                    iDif = iDif - Int32.Parse(s);
                                    oDBDSH.SetValue("U_Asignables", 0, iDif.ToString());
                                    //OutLog("Asignables -> " + oDBDSH.GetValue("U_Asignables", 0));

                                    s = @"WITH n(n) AS
                                        (
                                        SELECT 1
                                            UNION ALL
                                        SELECT n + 1 
                                          FROM n WHERE n < {0} )
                                        SELECT TOP 1 n + {1} --, T0.CAB_FOL_DOCTO_INT
                                          FROM n left outer join Faet_Erp_Encabezado_Doc T0 on n.n + {1} = T0.CAB_FOL_DOCTO_INT and T0.CAB_COD_TP_FACTURA = '{2}' 
                                           and T0.CAB_FOL_DOCTO_INT between {3} and {4} 
                                          where t0.CAB_FOL_DOCTO_INT is null 
                                        ORDER BY n 
                                        OPTION (MAXRECURSION 0)"; // antes OPTION (MAXRECURSION {0})";

                                    s = String.Format(s, iDif.ToString(), Int32.Parse(oRow.Field <String>("Desde")) - 1, oRow.Field <String>("TipoDoc"), oRow.Field <String>("Desde"), oRow.Field <String>("Hasta"));
                                    cmd1.CommandText = s;
                                    if (cmd1.ExecuteScalar() == null)
                                    {
                                        s = oRow.Field <String>("Desde");
                                    }
                                    else
                                    {
                                        s = cmd1.ExecuteScalar().ToString();
                                    }
                                    oDBDSH.SetValue("U_FolioDesde", 0, s);
                                    //OutLog("FolioDesde -> " + oDBDSH.GetValue("U_FolioDesde", 0));

                                    _return = Reg.CAFAdd(oDBDSH);
                                    if (_return)
                                    {
                                        FSBOApp.StatusBar.SetText("CAF Registrado, ID " + oRow.Field <String>("ID"), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                                    }
                                    else
                                    {
                                        FSBOApp.StatusBar.SetText("CAF no se ha registrado, ID " + oRow.Field <String>("ID"), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                                    }
                                }
                            }

                            if (ConexionADO.State == ConnectionState.Open)
                            {
                                ConexionADO.Close();
                            }

                            FSBOApp.StatusBar.SetText("CAF actualizados", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                        }
                        else
                        {
                            FSBOApp.StatusBar.SetText("Faltan datos Conexion. " + sCnn.Substring(1, sCnn.Length - 1), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                        }
                        oRecordSet.MoveNext();
                    }

                    ActualizarGrilla();
                }
                else
                {
                    FSBOApp.StatusBar.SetText("Debe ingresar datos de conexion", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                }
            }
            catch (Exception e)
            {
                FSBOApp.MessageBox(e.Message + " ** Trace: " + e.StackTrace, 1, "Ok", "", "");
                OutLog("ActualizarRegistros: " + e.Message + " ** Trace: " + e.StackTrace);
            }
        }//fin ActualizarRegistros
        }//fin FormEvent

        private void ActualizarRegistros()
        {
            TFunctions     Reg;
            SqlDataAdapter Adapter;
            SqlConnection  ConexionADO;
            DataSet        cDataSet;
            String         sCnn;
            int            lRetCode;
            String         User, Pass;

            try
            {
                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"select TOP 1 * from [@VID_FEPARAM]";
                }
                else
                {
                    s = @"select TOP 1 * from ""@VID_FEPARAM""";
                }

                oRecordSet.DoQuery(s);
                if (oRecordSet.RecordCount > 0)
                {
                    Reg       = new TFunctions();
                    Reg.SBO_f = FSBOf;
                    User      = Reg.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_Usuario").Value));
                    Pass      = Reg.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_Password").Value));
                    sCnn      = Reg.sConexion((System.String)(oRecordSet.Fields.Item("U_Servidor").Value), (System.String)(oRecordSet.Fields.Item("U_Base").Value), User, Pass);
                    if (sCnn.Substring(0, 1) != "E")
                    {
                        ConexionADO = new SqlConnection(sCnn);
                        if (ConexionADO.State == ConnectionState.Closed)
                        {
                            ConexionADO.Open();
                        }

                        if (GlobalSettings.RunningUnderSQLServer)
                        {
                            s = @"SELECT T0.DocEntry, T1.VisOrder, T0.U_TipoDoc, T1.U_Folio, T1.LineId
                                  FROM [@VID_FEDIST] T0 WITH(nolock)
                                  JOIN [@VID_FEDISTD] T1 WITH(nolock) ON T1.DocEntry = T0.DocEntry
                                 WHERE T1.U_Estado = 'D'
                                   AND T0.U_Sucursal <> 'Principal'
                                ";
                        }
                        else
                        {
                            s = @"SELECT T0.""DocEntry"", T1.""VisOrder"", T0.""U_TipoDoc"", T1.""U_Folio"", T1.""LineId""
                                  FROM ""@VID_FEDIST"" T0
                                  JOIN ""@VID_FEDISTD"" T1 ON T1.""DocEntry"" = T0.""DocEntry""
                                 WHERE T1.""U_Estado"" = 'D'
                                   AND T0.""U_Sucursal"" <> 'Principal'";
                        }

                        oRecordSet.DoQuery(s);
                        ConexionADO = new SqlConnection(sCnn);
                        if (ConexionADO.State == ConnectionState.Closed)
                        {
                            ConexionADO.Open();
                        }

                        while (!oRecordSet.EoF)
                        {
                            var VID_SP_EXISTEFOLIO = new SqlCommand("VID_SP_EXISTEFOLIO", ConexionADO);
                            var oParameter         = new SqlParameter();
                            VID_SP_EXISTEFOLIO.CommandType = CommandType.StoredProcedure;
                            oParameter       = VID_SP_EXISTEFOLIO.Parameters.Add("@TipoDoc", SqlDbType.VarChar, 10);
                            oParameter.Value = (System.String)(oRecordSet.Fields.Item("U_TipoDoc").Value);
                            oParameter       = VID_SP_EXISTEFOLIO.Parameters.Add("@FolioNum", SqlDbType.Int);
                            oParameter.Value = (System.Double)(oRecordSet.Fields.Item("U_Folio").Value);

                            Adapter  = new SqlDataAdapter(VID_SP_EXISTEFOLIO);
                            cDataSet = new DataSet(VID_SP_EXISTEFOLIO.CommandText);
                            Adapter.Fill(cDataSet);
                            s = (System.String)(cDataSet.Tables[0].Rows[0][0].ToString()).Trim();

                            if (s == "Y")
                            {
                                s        = Convert.ToString((System.Int32)(oRecordSet.Fields.Item("DocEntry").Value));
                                s        = Convert.ToString((System.Int32)(oRecordSet.Fields.Item("LineId").Value));
                                s        = Convert.ToString((System.Double)(oRecordSet.Fields.Item("U_Folio").Value));
                                lRetCode = Reg.ActEstadoFolioUpt((System.Int32)(oRecordSet.Fields.Item("DocEntry").Value), (System.Int32)(oRecordSet.Fields.Item("LineId").Value), (System.Double)(oRecordSet.Fields.Item("U_Folio").Value), (System.String)(oRecordSet.Fields.Item("U_TipoDoc").Value), "", "", "");
                                lRetCode = 1;
                                if (lRetCode == 0)
                                {
                                    FSBOApp.StatusBar.SetText("No se ha actualizado estado de Folio " + Convert.ToString((System.Double)(oRecordSet.Fields.Item("U_Folio").Value)), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                                    OutLog("No se ha actualizado estado de Folio " + Convert.ToString((System.Double)(oRecordSet.Fields.Item("U_Folio").Value)));
                                }
                            }

                            VID_SP_EXISTEFOLIO = null;

                            oRecordSet.MoveNext();
                        }

                        if (ConexionADO.State == ConnectionState.Open)
                        {
                            ConexionADO.Close();
                        }

                        Grilla();

                        if (ConexionADO.State == ConnectionState.Open)
                        {
                            ConexionADO.Close();
                        }

                        FSBOApp.StatusBar.SetText("Estado de Folios actualizados", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                    }
                    else
                    {
                        FSBOApp.StatusBar.SetText("Faltan datos Conexion. " + sCnn.Substring(1, sCnn.Length - 1), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                    }
                }
                else
                {
                    FSBOApp.StatusBar.SetText("Debe ingresar datos de conexion", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                }
            }
            catch (Exception e)
            {
                FSBOApp.MessageBox(e.Message + " ** Trace: " + e.StackTrace, 1, "Ok", "", "");
                OutLog("GuardarRegistros: " + e.Message + " ** Trace: " + e.StackTrace);
            }
        }//fin ActualizarRegistros
        public new bool InitForm(string uid, string xmlPath, ref Application application, ref SAPbobsCOM.Company company, ref CSBOFunctions SBOFunctions, ref TGlobalVid _GlobalSettings)
        {
            //SAPbouiCOM.ComboBox oCombo;
            TFunctions Param;

            SAPbouiCOM.CheckBox oCheckBox;
            SAPbouiCOM.EditText oEditText;

            //
            //  obetener recurso
            //  try
            //  .....
            //  finally
            //  liberar recurso
            //  end

            bool Result = base.InitForm(uid, xmlPath, ref application, ref company, ref SBOFunctions, ref _GlobalSettings);

            oRecordSet = (SAPbobsCOM.Recordset)(FCmpny.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset));
            try
            {
                //Lista    := New list<string>;

                FSBOf.LoadForm(xmlPath, "strCnn.srf", uid);
                //EnableCrystal := true;
                oForm = FSBOApp.Forms.Item(uid);
                oForm.Freeze(true);
                oForm.AutoManaged    = false;
                oForm.SupportedModes = -1;             // afm_All

                //oForm.DataBrowser.BrowseBy := "DocNum";

                // Ok Ad  Fnd Vw Rq Sec
                //Lista.Add('DocNum    , f,  f,  t,  f, n, 1');
                //Lista.Add('DocDate   , f,  t,  f,  f, r, 1');
                //Lista.Add('CardCode  , f,  t,  t,  f, r, 1');
                //FSBOf.SetAutoManaged(var oForm, Lista);

                oDBDSHeader = (DBDataSource)(oForm.DataSources.DBDataSources.Item("@VID_FEPARAM"));

                if (!GlobalSettings.RunningUnderSQLServer)
                {
                    oForm.Items.Item("btnProcFE").Visible = false;
                }
                else
                {
                    oForm.Items.Item("btnProcFE").Visible = true;
                }

                //s := 'Select count(*) cant from [@VID_FEPARAM]';
                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"Select count(*) CANT
                                ,U_UserED
                                ,U_PwdED
                                ,U_UserWS
                                ,U_PassWS
                            from [@VID_FEPARAM] 
                            group by U_UserED
                                ,U_PwdED
                                ,U_UserWS
                                ,U_PassWS";
                }
                else
                {
                    s = @"Select count(*) ""CANT"" 
                           ,""U_UserED""
                           ,""U_PwdED""
                           ,""U_UserWS""
                           ,""U_PassWS""
                      from ""@VID_FEPARAM"" 
                     group by ""U_UserED""
                             ,""U_PwdED""
                             ,""U_UserWS""
                             ,""U_PassWS""";
                }
                oRecordSet.DoQuery(s);
                if ((System.Int32)(oRecordSet.Fields.Item("CANT").Value) > 0)
                {
                    Param       = new TFunctions();
                    Param.SBO_f = FSBOf;

                    oForm.SupportedModes = 1;
                    oForm.Mode           = BoFormMode.fm_UPDATE_MODE;
                    oDBDSHeader.Query(null);

                    s = Param.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_UserED").Value).ToString().Trim());
                    oDBDSHeader.SetValue("U_UserED", 0, s);

                    s = Param.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_PwdED").Value).ToString().Trim());
                    oDBDSHeader.SetValue("U_PwdED", 0, s);

                    s = Param.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_UserWS").Value).ToString().Trim());
                    oDBDSHeader.SetValue("U_UserWS", 0, s);

                    s = Param.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_PassWS").Value).ToString().Trim());
                    oDBDSHeader.SetValue("U_PassWS", 0, s);
                }
                else
                {
                    oForm.SupportedModes = 3;
                    oForm.Mode           = BoFormMode.fm_ADD_MODE;
                    oForm.PaneLevel      = 106;
                }
            }
            catch (Exception e)
            {
                OutLog("InitForm: " + e.Message + " ** Trace: " + e.StackTrace);
                FSBOApp.MessageBox(e.Message + " ** Trace: " + e.StackTrace, 1, "Ok", "", "");
            }
            finally
            {
                oForm.Freeze(false);
            }


            return(Result);
        }//fin InitForm
Exemplo n.º 6
0
        private void LeerConfigTexto(String Arch)
        {
            try
            {
                string contenido = String.Empty;
                contenido = File.ReadAllText(Arch);
                //string[] lineas = contenido.Split(Environment.NewLine);
                //foreach (string linea in lineas)
                //{
                //    Console.WriteLine(linea);
                //}
                contenido = Func.DesEncriptar(contenido);
                xDoc      = new XmlDocument();
                xDoc.LoadXml(contenido);
                Configuracion = xDoc.GetElementsByTagName("Configuracion");
                lista         = ((XmlElement)Configuracion[0]).GetElementsByTagName("ServidorSAP");
                foreach (XmlElement nodo in lista)
                {
                    var nArchivos = nodo.GetElementsByTagName("Servidor");
                    txServidor.Text = (String)(nArchivos[0].InnerText);

                    nArchivos          = nodo.GetElementsByTagName("ServLicencia");
                    txServidorLic.Text = (String)(nArchivos[0].InnerText);

                    nArchivos         = nodo.GetElementsByTagName("UsuarioSAP");
                    txUsuarioSAP.Text = (String)(nArchivos[0].InnerText);

                    nArchivos      = nodo.GetElementsByTagName("PasswordSAP");
                    txPassSAP.Text = (String)(nArchivos[0].InnerText);

                    nArchivos         = nodo.GetElementsByTagName("SQL");
                    txVersionSQL.Text = (String)(nArchivos[0].InnerText);

                    nArchivos          = nodo.GetElementsByTagName("UsuarioSQL");
                    txUsuarioBase.Text = (String)(nArchivos[0].InnerText);

                    nArchivos       = nodo.GetElementsByTagName("PasswordSQL");
                    txPassBase.Text = (String)(nArchivos[0].InnerText);
                }

                lista = ((XmlElement)Configuracion[0]).GetElementsByTagName("SistemaSAP");
                foreach (XmlElement nodo in lista)
                {
                    var nArchivos = nodo.GetElementsByTagName("SAP");
                    txSistemaSAP.Text = (String)(nArchivos[0].InnerText);
                }

                lista = ((XmlElement)Configuracion[0]).GetElementsByTagName("EasyDoc");
                foreach (XmlElement nodo in lista)
                {
                    var nArchivos = nodo.GetElementsByTagName("Procesa21");
                    cbxOP21.Text = (String)(nArchivos[0].InnerText);
                    nArchivos    = nodo.GetElementsByTagName("OP21");
                    txOP21.Text  = (String)(nArchivos[0].InnerText);

                    nArchivos    = nodo.GetElementsByTagName("Procesa27");
                    cbxOP27.Text = (String)(nArchivos[0].InnerText);
                    nArchivos    = nodo.GetElementsByTagName("OP27");
                    txOP27.Text  = (String)(nArchivos[0].InnerText);

                    nArchivos    = nodo.GetElementsByTagName("Procesa28");
                    cbxOP28.Text = (String)(nArchivos[0].InnerText);
                    nArchivos    = nodo.GetElementsByTagName("OP28");
                    txOP28.Text  = (String)(nArchivos[0].InnerText);

                    nArchivos    = nodo.GetElementsByTagName("Procesa29");
                    cbxOP29.Text = (String)(nArchivos[0].InnerText);
                    nArchivos    = nodo.GetElementsByTagName("OP29");
                    txOP29.Text  = (String)(nArchivos[0].InnerText);

                    nArchivos    = nodo.GetElementsByTagName("Procesa30");
                    cbxOP30.Text = (String)(nArchivos[0].InnerText);
                    nArchivos    = nodo.GetElementsByTagName("OP30");
                    txOP30.Text  = (String)(nArchivos[0].InnerText);

                    nArchivos    = nodo.GetElementsByTagName("Procesa31");
                    cbxOP31.Text = (String)(nArchivos[0].InnerText);
                    nArchivos    = nodo.GetElementsByTagName("OP31");
                    txOP31.Text  = (String)(nArchivos[0].InnerText);

                    nArchivos    = nodo.GetElementsByTagName("Procesa36");
                    cbxOP36.Text = (String)(nArchivos[0].InnerText);
                    nArchivos    = nodo.GetElementsByTagName("OP36");
                    txOP36.Text  = (String)(nArchivos[0].InnerText);
                }

                lista = ((XmlElement)Configuracion[0]).GetElementsByTagName("Mail");
                foreach (XmlElement nodo in lista)
                {
                    var nArchivos = nodo.GetElementsByTagName("EnviarMail");
                    cbxMailEnvio.Text = (String)(nArchivos[0].InnerText);

                    nArchivos         = nodo.GetElementsByTagName("HoraEnvio1");
                    txHoraEnvio1.Text = (String)(nArchivos[0].InnerText);

                    nArchivos         = nodo.GetElementsByTagName("HoraEnvio2");
                    txHoraEnvio2.Text = (String)(nArchivos[0].InnerText);

                    nArchivos        = nodo.GetElementsByTagName("MailFrom");
                    txMailEnvia.Text = (String)(nArchivos[0].InnerText);

                    nArchivos       = nodo.GetElementsByTagName("MailSmtpHost");
                    txMailSmtp.Text = (String)(nArchivos[0].InnerText);

                    nArchivos          = nodo.GetElementsByTagName("MailUser");
                    txMailUsuario.Text = (String)(nArchivos[0].InnerText);

                    nArchivos           = nodo.GetElementsByTagName("MailPass");
                    txMailPassword.Text = (String)(nArchivos[0].InnerText);

                    nArchivos         = nodo.GetElementsByTagName("Puerto");
                    txMailPuerto.Text = (String)(nArchivos[0].InnerText);
                }

                lista = ((XmlElement)Configuracion[0]).GetElementsByTagName("BaseSAP");
                foreach (XmlElement nodo in lista)
                {
                    //var nArchivos = nodo.GetElementsByTagName("BaseSAP");
                    //lbxBases.Items.Add((String)(nArchivos[0].InnerText));
                    lbxBases.Items.Add((String)(nodo.InnerText));
                }
                btnGuardar.Enabled = true;
            }
            catch (Exception w)
            {
                MessageBox.Show("Error : " + w.Message + " ** Trace: " + w.StackTrace);
            }
        }
Exemplo n.º 7
0
        private void GuardarRegistros()
        {
            SAPbouiCOM.Grid oGrid;
            Boolean         Paso = false;
            String          ObjType;
            Int32           DocEntry;
            String          Tipo;
            String          Serie;
            String          Folio;
            Int32           lRetCode;
            String          errMsg;
            Int32           errCode;
            XDocument       miXMLDoc;
            XmlDocument     oXml;
            String          UserWS        = "";
            String          PassWS        = "";
            String          TaxIdNum      = "";
            String          URL           = "";
            String          ExternalFolio = "";
            XmlNode         oNode;

            SAPbobsCOM.Documents     oDocs;
            SAPbobsCOM.StockTransfer oStock;
            SAPbobsCOM.Payments      oPay;
            try
            {
                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"SELECT T0.U_URLDarBaja 'URL', ISNULL(T0.U_UserWS,'') 'UserWS', ISNULL(T0.U_PassWS,'') 'PassWS', ISNULL(T0.U_MostrarXML,'N') 'MostrarXML', ISNULL(A0.TaxIdNum,'') 'TaxIdNum' 
                           FROM [@VID_FEPARAM] T0 , OADM A0";
                }
                else
                {
                    s = @"SELECT T0.""U_URLDarBaja"" ""URL"", IFNULL(T0.""U_UserWS"",'') ""UserWS"", IFNULL(T0.""U_PassWS"",'') ""PassWS"", IFNULL(T0.""U_MostrarXML"",'N') ""MostrarXML"", IFNULL(A0.""TaxIdNum"",'') ""TaxIdNum"" 
                           FROM ""@VID_FEPARAM"" T0, ""OADM"" A0";
                }

                oRecordSet.DoQuery(s);
                if (oRecordSet.RecordCount == 0)
                {
                    FSBOApp.StatusBar.SetText("No se ha ingresado URL", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                }
                else if (((System.String)oRecordSet.Fields.Item("URL").Value).Trim() == "")
                {
                    FSBOApp.StatusBar.SetText("No se ha ingresado URL", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                }
                //else if (((System.String)oRecordSet.Fields.Item("UserWS").Value).Trim() == "")
                //    throw new Exception("No se encuentra usuario en Parametros");
                //else if (((System.String)oRecordSet.Fields.Item("PassWS").Value).Trim() == "")
                //    throw new Exception("No se encuentra password en Parametros");
                else if (((System.String)oRecordSet.Fields.Item("TaxIdNum").Value).Trim() == "")
                {
                    throw new Exception("No se encuentra RUC de Emisor, Gestión -> Inicialización Sistema -> Detalle Sociedad -> Datos de Contabilidad -> ID fiscal general 1");
                }
                else
                {
                    UserWS   = Funciones.DesEncriptar((System.String)(oRecordSet.Fields.Item("UserWS").Value).ToString().Trim());
                    PassWS   = Funciones.DesEncriptar((System.String)(oRecordSet.Fields.Item("PassWS").Value).ToString().Trim());
                    TaxIdNum = ((System.String)oRecordSet.Fields.Item("TaxIdNum").Value).Trim();
                    URL      = ((System.String)oRecordSet.Fields.Item("URL").Value).Trim();
                }

                oGrid = ((SAPbouiCOM.Grid)oForm.Items.Item("grid").Specific);
                FCmpny.StartTransaction();
                for (Int32 iLinea = 0; iLinea <= oGrid.DataTable.Rows.Count - 1; iLinea++)
                {
                    if (((System.String)oGrid.DataTable.GetValue("Sel", iLinea)).Trim() == "Y")
                    {
                        try
                        {
                            Paso          = true;
                            ObjType       = ((System.String)oGrid.DataTable.GetValue("ObjType", iLinea));
                            DocEntry      = ((System.Int32)oGrid.DataTable.GetValue("DocEntry", iLinea));
                            Tipo          = ((System.String)oGrid.DataTable.GetValue("TipoDoc", iLinea));
                            Serie         = ((System.String)oGrid.DataTable.GetValue("Serie", iLinea));
                            Folio         = ((System.String)oGrid.DataTable.GetValue("Folio", iLinea));
                            ExternalFolio = ((System.String)oGrid.DataTable.GetValue("ExtFolio", iLinea));

                            if (ObjType == "67")
                            {
                                oStock = ((SAPbobsCOM.StockTransfer)FCmpny.GetBusinessObject(BoObjectTypes.oStockTransfer));
                                if (oStock.GetByKey(DocEntry))
                                {
                                    lRetCode = oStock.Cancel();
                                }
                            }
                            else if (ObjType == "46")
                            {
                                oPay = ((SAPbobsCOM.Payments)FCmpny.GetBusinessObject(BoObjectTypes.oVendorPayments));
                                if (oPay.GetByKey(DocEntry))
                                {
                                    lRetCode = oPay.Cancel();
                                }
                            }
                            else
                            {
                                if (ObjType == "21")
                                {
                                    oDocs = ((SAPbobsCOM.Documents)FCmpny.GetBusinessObject(BoObjectTypes.oPurchaseReturns));
                                }
                                else if (ObjType == "15")
                                {
                                    oDocs = ((SAPbobsCOM.Documents)FCmpny.GetBusinessObject(BoObjectTypes.oDeliveryNotes));
                                }
                                else if (ObjType == "14")
                                {
                                    oDocs = ((SAPbobsCOM.Documents)FCmpny.GetBusinessObject(BoObjectTypes.oCreditNotes));
                                }
                                else if (ObjType == "203")
                                {
                                    oDocs = ((SAPbobsCOM.Documents)FCmpny.GetBusinessObject(BoObjectTypes.oDownPayments));
                                }
                                else
                                {
                                    oDocs = ((SAPbobsCOM.Documents)FCmpny.GetBusinessObject(BoObjectTypes.oInvoices));
                                }
                                if (oDocs.GetByKey(DocEntry))
                                {
                                    var oDocCancel = oDocs.CreateCancellationDocument();
                                    lRetCode = oDocCancel.Add();// Cancel();
                                    if (lRetCode != 0)
                                    {
                                        FCmpny.GetLastError(out errCode, out errMsg);
                                        throw new Exception("No se ha encontrado Documento " + Tipo + " " + Serie + "-" + Folio + ": " + errMsg);
                                    }
                                    else
                                    {
                                        //enviar baja al portal
                                        miXMLDoc = new XDocument(
                                            new XDeclaration("1.0", "utf-8", "yes")
                                            , new XElement("documentoelectronico",
                                                           new XElement("DocNum", TaxIdNum),
                                                           new XElement("DocType", Tipo),
                                                           new XElement("IdDocumento", ExternalFolio.Trim()
                                                                        ))
                                            );
                                        oXml = new XmlDocument();
                                        using (var xmlReader = miXMLDoc.CreateReader())
                                        {
                                            oXml.Load(xmlReader);
                                        }

                                        s = Funciones.UpLoadDocumentByUrl(oXml, null, GlobalSettings.RunningUnderSQLServer, URL, UserWS, PassWS, "D-" + ExternalFolio);

                                        oXml.LoadXml(s);

                                        oNode = oXml.DocumentElement.SelectSingleNode("/Error/ErrorCode");

                                        string ticket = oNode.InnerText;

                                        oNode = oXml.DocumentElement.SelectSingleNode("/Error/ErrorText");

                                        string errorText = oNode.InnerText;

                                        oNode = oXml.DocumentElement.SelectSingleNode("/Error/IdDocument");

                                        string idDocument = oNode.InnerText;

                                        if (errorText != "OK")
                                        {
                                            FSBOApp.StatusBar.SetText("Mensaje: " + errorText + " " + Tipo + " " + Serie + "-" + Folio, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Warning);
                                        }
                                        else
                                        {
                                            FSBOApp.StatusBar.SetText("Se ha creado cancelacion del documento " + Tipo + " " + Serie + "-" + Folio, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);

                                            //insertar en la tabla  y consultar por el estado mismo codigo que insert de factura
                                        }
                                    }
                                }
                                else
                                {
                                    FSBOApp.StatusBar.SetText("No se ha encontrado Documento " + Tipo + " " + Serie + "-" + Folio, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Warning);
                                }
                            }

                            oDocs  = null;
                            oPay   = null;
                            oStock = null;
                        }
                        catch (Exception ss)
                        {
                            FSBOApp.StatusBar.SetText("Dar de Baja: " + ss.Message + " ** Trace: " + ss.StackTrace, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                            OutLog("Dar de Baja: " + ss.Message + " ** Trace: " + ss.StackTrace);
                            if (FCmpny.InTransaction)
                            {
                                FCmpny.EndTransaction(BoWfTransOpt.wf_RollBack);
                            }
                        }
                    }
                }

                if (!Paso)
                {
                    FSBOApp.StatusBar.SetText("Debe seleccionar un documento minimo", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Warning);
                }
                else
                {
                    if (FCmpny.InTransaction)
                    {
                        FCmpny.EndTransaction(BoWfTransOpt.wf_Commit);
                    }
                }
            }
            catch (Exception e)
            {
                FSBOApp.StatusBar.SetText("GuardarRegistros: " + e.Message + " ** Trace: " + e.StackTrace, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                OutLog("GuardarRegistros: " + e.Message + " ** Trace: " + e.StackTrace);
                if (FCmpny.InTransaction)
                {
                    FCmpny.EndTransaction(BoWfTransOpt.wf_RollBack);
                }
            }
        }
Exemplo n.º 8
0
        private String sConnection()
        {
            String sMultiSoc;

            try
            {
                if (bMultiSoc == true)
                {
                    oComboBox = (ComboBox)(oForm.Items.Item("Instituto").Specific);
                    sMultiSoc = oComboBox.Selected.Value;

                    if (GlobalSettings.RunningUnderSQLServer)
                    {
                        s = @"select U_Servidor, U_Base, U_Usuario, U_Password
                                from [@VID_FEMULTISOC] WITH (NOLOCK)
                               where DocEntry = {0}";
                    }
                    else
                    {
                        s = @"select ""U_Servidor"", ""U_Base"", ""U_Usuario"", ""U_Password""
                                       from ""@VID_FEMULTISOC""
                                      where ""DocEntry"" = {0} ";
                    }
                    s = String.Format(s, sMultiSoc);
                }
                else
                {
                    if (GlobalSettings.RunningUnderSQLServer)
                    {
                        s = @"Select U_Servidor
                                    ,U_Base
                                    ,U_Usuario
                                    ,U_Password
                               from [@VID_FEPARAM] ";
                    }
                    else
                    {
                        s = @"Select ""U_Servidor""
                                    ,""U_Base""
                                    ,""U_Usuario""
                                    ,""U_Password""
                               from ""@VID_FEPARAM"" ";
                    }
                }
                oRecordSet.DoQuery(s);
                if (oRecordSet.RecordCount > 0)
                {
                    if (bMultiSoc == true)
                    {
                        User = (System.String)(oRecordSet.Fields.Item("U_Usuario").Value).ToString().Trim();
                        Pass = (System.String)(oRecordSet.Fields.Item("U_Password").Value).ToString().Trim();
                    }
                    else
                    {
                        User = Param.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_Usuario").Value).ToString().Trim());
                        Pass = Param.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_Password").Value).ToString().Trim());
                    }
                    return(Param.sConexion((System.String)(oRecordSet.Fields.Item("U_Servidor").Value), (System.String)(oRecordSet.Fields.Item("U_Base").Value), User, Pass));
                }
                else
                {
                    return("");
                }
            }
            catch (Exception e)
            {
                return("");
            }
        }
Exemplo n.º 9
0
        private void CargarProcedimientosPortal()
        {
            String SQLFile;

            System.IO.StreamReader sr;
            String ruta;

            System.String[] awords;
            String[]        charArray;
            SqlConnection   ConexionADO;
            String          sUser;
            String          sPass;
            TFunctions      Param;
            String          sCnn;
            SqlCommand      cmd;
            Boolean         bMultiSoc;

            try
            {
                if (((System.String)oDBDSHeader.GetValue("U_MultiSoc", 0)).Trim() == "Y")
                {
                    bMultiSoc = true;
                }
                else
                {
                    bMultiSoc = false;
                }

                charArray = new String[] { "GO--" };
                //cargar procedimiento SQL
                //ruta = TMultiFunctions.ExtractFilePath(TMultiFunctions.ParamStr(0)) + "\\SQLs\\SQLServer\\";
                ruta = Directory.GetCurrentDirectory() + "\\SQLs\\CL\\Portal\\";
                DirectoryInfo oDirectorio = new DirectoryInfo(ruta);


                if (bMultiSoc)
                {
                    if (GlobalSettings.RunningUnderSQLServer)
                    {
                        s = @"select U_Servidor, U_Base, U_Usuario, U_Password from [@VID_FEMULTISOC] where U_Habilitada = 'Y'";
                    }
                    else
                    {
                        s = @"select ""U_Servidor"", ""U_Base"", ""U_Usuario"", ""U_Password"" from ""@VID_FEMULTISOC"" where ""U_Habilitada"" = 'Y'";
                    }
                }
                else
                {
                    if (GlobalSettings.RunningUnderSQLServer)
                    {
                        s = @"Select U_Servidor
                                           ,U_Base
                                           ,U_Usuario
                                           ,U_Password
                                      from [@VID_FEPARAM] ";
                    }
                    else
                    {
                        s = @"Select ""U_Servidor""
                                           ,""U_Base""
                                           ,""U_Usuario""
                                           ,""U_Password""
                                      from ""@VID_FEPARAM"" ";
                    }
                }
                oRecordSet.DoQuery(s);
                Param       = new TFunctions();
                Param.SBO_f = FSBOf;


                while (!oRecordSet.EoF)
                {
                    if (bMultiSoc)
                    {
                        sUser = (System.String)(oRecordSet.Fields.Item("U_Usuario").Value).ToString().Trim();
                        sPass = (System.String)(oRecordSet.Fields.Item("U_Password").Value).ToString().Trim();
                    }
                    else
                    {
                        sUser = Param.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_Usuario").Value).ToString().Trim());
                        sPass = Param.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_Password").Value).ToString().Trim());
                    }
                    sCnn = Param.sConexion((System.String)(oRecordSet.Fields.Item("U_Servidor").Value), (System.String)(oRecordSet.Fields.Item("U_Base").Value), sUser, sPass);
                    if (sCnn.Substring(0, 1) != "E")
                    {
                        //obtengo ls ficheros contenidos en la ruta
                        foreach (FileInfo file in oDirectorio.GetFiles())
                        {
                            try
                            {
                                if (file.Extension == ".sql")
                                {
                                    ConexionADO = new SqlConnection(sCnn);
                                    if (ConexionADO.State == ConnectionState.Closed)
                                    {
                                        ConexionADO.Open();
                                    }

                                    SQLFile = file.FullName;
                                    sr      = new System.IO.StreamReader(SQLFile, System.Text.Encoding.GetEncoding("ISO8859-1"));
                                    s       = sr.ReadToEnd();
                                    sr.Close();
                                    if (s != "")
                                    {
                                        awords = s.Split(charArray, StringSplitOptions.None);
                                        foreach (String aword in awords)
                                        {
                                            cmd            = new SqlCommand(aword);
                                            cmd.Connection = ConexionADO;
                                            cmd.ExecuteNonQuery();
                                        }
                                        FSBOApp.StatusBar.SetText("Cargado exitosamente " + (System.String)(oRecordSet.Fields.Item("U_Base").Value) + ", " + file.Name, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                FSBOApp.StatusBar.SetText((System.String)(oRecordSet.Fields.Item("U_Base").Value) + " - " + ex.Message + " ** Trace: " + ex.StackTrace, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                                OutLog("CargarProcedimientosPortal " + (System.String)(oRecordSet.Fields.Item("U_Base").Value) + ": " + ex.Message + " ** Trace: " + ex.StackTrace);
                            }
                        }
                    }
                    else
                    {
                        FSBOApp.StatusBar.SetText("Debe ingresar datos de conexion", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                    }

                    oRecordSet.MoveNext();
                }
            }
            catch (Exception e)
            {
                FSBOApp.StatusBar.SetText(e.Message + " ** Trace: " + e.StackTrace, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                OutLog("CargarProcedimientosPortal: " + e.Message + " ** Trace: " + e.StackTrace);
            }
        }
Exemplo n.º 10
0
        public new bool InitForm(string uid, string xmlPath, ref Application application, ref SAPbobsCOM.Company company, ref CSBOFunctions SBOFunctions, ref TGlobalVid _GlobalSettings)
        {
            //SAPbouiCOM.ComboBox oCombo;
            TFunctions Param;

            SAPbouiCOM.CheckBox oCheckBox;
            SAPbouiCOM.EditText oEditText;

            //
            //  obetener recurso
            //  try
            //  .....
            //  finally
            //  liberar recurso
            //  end

            bool Result = base.InitForm(uid, xmlPath, ref application, ref company, ref SBOFunctions, ref _GlobalSettings);

            oRecordSet = (SAPbobsCOM.Recordset)(FCmpny.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset));
            try
            {
                //Lista    := New list<string>;

                FSBOf.LoadForm(xmlPath, "strCnn.srf", uid);
                //EnableCrystal := true;
                oForm = FSBOApp.Forms.Item(uid);
                oForm.Freeze(true);
                oForm.AutoManaged    = false;
                oForm.SupportedModes = -1;             // afm_All

                //oForm.DataBrowser.BrowseBy := "DocNum";

                // Ok Ad  Fnd Vw Rq Sec
                //Lista.Add('DocNum    , f,  f,  t,  f, n, 1');
                //Lista.Add('DocDate   , f,  t,  f,  f, r, 1');
                //Lista.Add('CardCode  , f,  t,  t,  f, r, 1');
                //FSBOf.SetAutoManaged(var oForm, Lista);

                oDBDSHeader = (DBDataSource)(oForm.DataSources.DBDataSources.Item("@VID_FEPARAM"));

                oCheckBox        = (CheckBox)(oForm.Items.Item("chkMon").Specific);
                oCheckBox.ValOn  = "Y";
                oCheckBox.ValOff = "N";

                oCheckBox        = (CheckBox)(oForm.Items.Item("chkDteTra").Specific);
                oCheckBox.ValOn  = "Y";
                oCheckBox.ValOff = "N";

                //oCheckBox = (CheckBox)(oForm.Items.Item("chkCrearD").Specific);
                //oCheckBox.ValOn = "Y";
                //oCheckBox.ValOff = "N";

                //oCheckBox = (CheckBox)(oForm.Items.Item("chkCrearDS").Specific);
                //oCheckBox.ValOn = "Y";
                //oCheckBox.ValOff = "N";

                oCheckBox        = (CheckBox)(oForm.Items.Item("chkPrint").Specific);
                oCheckBox.ValOn  = "Y";
                oCheckBox.ValOff = "N";

                oCheckBox        = (CheckBox)(oForm.Items.Item("chkDistrib").Specific);
                oCheckBox.ValOn  = "Y";
                oCheckBox.ValOff = "N";

                oCheckBox        = (CheckBox)(oForm.Items.Item("chkVal90").Specific);
                oCheckBox.ValOn  = "Y";
                oCheckBox.ValOff = "N";

                oCheckBox        = (CheckBox)(oForm.Items.Item("MultiSoc").Specific);
                oCheckBox.ValOn  = "Y";
                oCheckBox.ValOff = "N";

                oCheckBox        = (CheckBox)(oForm.Items.Item("ValDescL").Specific);
                oCheckBox.ValOn  = "Y";
                oCheckBox.ValOff = "N";

                oCheckBox        = (CheckBox)(oForm.Items.Item("GeneraT").Specific);
                oCheckBox.ValOn  = "Y";
                oCheckBox.ValOff = "N";

                oCheckBox        = (CheckBox)(oForm.Items.Item("SubirSuc").Specific);
                oCheckBox.ValOn  = "Y";
                oCheckBox.ValOff = "N";

                oCheckBox        = (CheckBox)(oForm.Items.Item("AbrirDoc").Specific);
                oCheckBox.ValOn  = "Y";
                oCheckBox.ValOff = "N";

                oCheckBox        = (CheckBox)(oForm.Items.Item("chkFProv").Specific);
                oCheckBox.ValOn  = "Y";
                oCheckBox.ValOff = "N";

                oEditText            = (EditText)(oForm.Items.Item("Pasword").Specific);
                oEditText.IsPassword = true;


                //Configuración RadioButtons
                DSOpDif = oForm.DataSources.UserDataSources.Add("rbOpDif", SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 1);
                ((OptionBtn)oForm.Items.Item("opDifPor").Specific).DataBind.SetBound(true, "", "rbOpDif"); //1

                ((OptionBtn)oForm.Items.Item("opDifMon").Specific).DataBind.SetBound(true, "", "rbOpDif"); //2
                ((OptionBtn)oForm.Items.Item("opDifMon").Specific).GroupWith("opDifPor");


                if (!GlobalSettings.RunningUnderSQLServer)
                {
                    oForm.Items.Item("btnProcFE").Visible = false;
                }
                else
                {
                    oForm.Items.Item("btnProcFE").Visible = true;
                }

                //s := 'Select count(*) cant from [@VID_FEPARAM]';
                if (GlobalSettings.RunningUnderSQLServer)
                {
                    s = @"Select count(*) CANT
                                ,U_Usuario
                                ,U_Password
                                ,U_UserWSCL
                                ,U_PassWSCL
                                ,ISNULL(U_TipoDif,'M') 'U_TipoDif'
                            from [@VID_FEPARAM] 
                            group by U_Usuario
                                ,U_Password
                                ,U_UserWSCL
                                ,U_PassWSCL
                                ,ISNULL(U_TipoDif,'M')";
                }
                else
                {
                    s = @"Select count(*) ""CANT"" 
                           ,""U_Usuario"" 
                           ,""U_Password""
                           ,""U_UserWSCL""
                           ,""U_PassWSCL""
                           ,IFNULL(""U_TipoDif"",'M') ""U_TipoDif""
                      from ""@VID_FEPARAM"" 
                     group by ""U_Usuario"" 
                             ,""U_Password""
                             ,""U_UserWSCL""
                             ,""U_PassWSCL""
                             ,IFNULL(""U_TipoDif"",'M') ";
                }
                oRecordSet.DoQuery(s);
                if ((System.Int32)(oRecordSet.Fields.Item("CANT").Value) > 0)
                {
                    Param       = new TFunctions();
                    Param.SBO_f = FSBOf;

                    oForm.SupportedModes = 1;
                    oForm.Mode           = BoFormMode.fm_UPDATE_MODE;
                    oDBDSHeader.Query(null);

                    s = Param.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_Usuario").Value).ToString().Trim());
                    oDBDSHeader.SetValue("U_Usuario", 0, s);

                    s = Param.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_Password").Value).ToString().Trim());
                    oDBDSHeader.SetValue("U_Password", 0, s);

                    s = Param.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_UserWSCL").Value).ToString().Trim());
                    oDBDSHeader.SetValue("U_UserWSCL", 0, s);

                    s = Param.DesEncriptar((System.String)(oRecordSet.Fields.Item("U_PassWSCL").Value).ToString().Trim());
                    oDBDSHeader.SetValue("U_PassWSCL", 0, s);

                    oForm.PaneLevel = 101;

                    if (((System.String)oDBDSHeader.GetValue("U_MultiSoc", 0)).Trim() == "Y")
                    {
                        oForm.Items.Item("chkDistrib").Visible = false;
                        oForm.Items.Item("AbrirDoc").Visible   = true;
                    }
                    else if (((System.String)oDBDSHeader.GetValue("U_MultiSoc", 0)).Trim() == "N")
                    {
                        oForm.Items.Item("chkDistrib").Visible = true;
                        oForm.Items.Item("AbrirDoc").Visible   = false;
                    }

                    oForm.Freeze(false);
                    if (((System.String)oRecordSet.Fields.Item("U_TipoDif").Value).Trim() == "M")
                    {
                        DSOpDif.Value = "2";
                    }
                    //((OptionBtn)oForm.Items.Item("opDifMon").Specific).Selected = true;
                    else
                    {
                        DSOpDif.Value = "1";
                    }
                    //((OptionBtn)oForm.Items.Item("opDifPor").Specific).Selected = true;
                }
                else
                {
                    oForm.SupportedModes = 3;
                    oForm.Mode           = BoFormMode.fm_ADD_MODE;
                    oForm.PaneLevel      = 101;
                    ((OptionBtn)oForm.Items.Item("opDifMon").Specific).Selected = true;
                }
            }
            catch (Exception e)
            {
                OutLog("InitForm: " + e.Message + " ** Trace: " + e.StackTrace);
                FSBOApp.MessageBox(e.Message + " ** Trace: " + e.StackTrace, 1, "Ok", "", "");
            }
            finally
            {
                oForm.Freeze(false);
            }


            return(Result);
        }//fin InitForm