### Setup Queue with Redis Defaults Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL/AdvPL - Classes/Componentes/Não Visual/Classe TQueueSvc/Classe TQueueSvc - Métodos/TQueueSvc_Setup.md This example demonstrates setting up a queue using TQueueSvc with default Redis parameters. It initializes a queue object, then calls the Setup method with only the host and port. Error handling is included to report setup failures. ```advpl #include 'protheus.ch' // Setup Redis Static cRedisHost := "tec-clima" Static nRedisPort := 6379 User Function FilStp() Local nRet := 0 // Nome da Fila Local cQueueName := "Fila_TQLS" // Objeto de Fila Local oTQLS := Nil // Cria um novo objeto de Fila oTQLS := TQueueSvc():New(cQueueName) If(oTQLS == Nil) ConOut("### ERRO ### " + "Erro na criacao da Fila - " + cQueueName) Return .F. Else ConOut("Criacao da Fila OK - " + oTQLS:cName) EndIf // Configurando a Fila nRet := oTQLS:Setup(cRedisHost, nRedisPort) If nRet != 0 ConOut("### ERRO ### " + "Erro ao fazer o Setup" + " Erro: " + AllTrim(Str(nRet))) Return .F. Else ConOut("Setup de Fila OK - " + oTQLS:cName + " nMsgRetPer: " + AllTrim(Str(oTQLS:nMsgRetPer)) + " nVisTimeOut: " + AllTrim(Str(oTQLS:nVisTimeOut))) EndIf Return .T. ``` -------------------------------- ### Setup Queue with Redis Authentication and Custom Timeouts Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL/AdvPL - Classes/Componentes/Não Visual/Classe TQueueSvc/Classe TQueueSvc - Métodos/TQueueSvc_Setup.md This example shows how to set up a queue with TQueueSvc, including Redis authentication and custom message retention and visibility timeouts. It defines Redis credentials and timeout values, then passes them to the Setup method. Error handling is provided for the setup process. ```advpl #include 'protheus.ch' // Setup Redis Static cRedisHost := "tec-clima" Static nRedisPort := 6379 Static cRedisAuth := "abc" User Function FilStpB() Local nRet := 0 // Nome da Fila Local cQueueName := "Fila_TQLS" // Tempo de espera de tratamento de mensagem Local nVisibTimeOut := 32 // segundos // 0 usa o default // -1 recupara o valor // Tempo de armazenamento da mensagem Local nMsgRetPeriod := (7 * 24 * 60 * 60) // 7 dias (em segundos) // 0 usa o default // -1 recupara o valor // Objeto de Fila Local oTQLS := Nil // Cria um novo objeto de Fila oTQLS := TQueueSvc():New(cQueueName) If(oTQLS == Nil) ConOut("### ERRO ### " + "Erro na criacao da Fila - " + cQueueName) Return .F. Else ConOut("Criacao da Fila OK - " + oTQLS:cName) EndIf // Configurando a Fila nRet := oTQLS:Setup(cRedisHost, nRedisPort, cRedisAuth, nMsgRetPeriod, nVisibTimeOut) If nRet != 0 ConOut("### ERRO ### " + "Erro ao fazer o Setup" + " Erro: " + AllTrim(Str(nRet))) Return .F. Else ConOut("Setup de Fila OK - " + oTQLS:cName + " nMsgRetPer: " + AllTrim(Str(oTQLS:nMsgRetPer)) + " nVisTimeOut: " + AllTrim(Str(oTQLS:nVisTimeOut))) EndIf Return .T. ``` -------------------------------- ### FWIPCWait Class Example - Demonstrating IPC Usage Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL - Classes/Classe FWIPCWait.md This example demonstrates the usage of the FWIPCWait class for inter-process communication. It includes setting up the IPC environment, starting threads, sending data, and stopping the process. The example requires specific Protheus includes. ```advpl #INCLUDE "protheus.ch" #INCLUDE "parmtype.ch" #Include "fwipcwait.ch" //--------------------------------------------------------------------- /*/{Protheus.doc} IPCTeste Função para exemplo de uso da classe FWIPCWait @author FRAMEWORK @since 11/09/2024 @version 1.0 */ //--------------------------------------------------------------------- User Function IPCTeste() Local oIPC as object Local nX as numeric RpcSetEnv("99","01") oIPC := FWIPCWait():New("TESTE",10000) oIPC:SetThreads(1) oIPC:SetEnvironment(cEmpAnt,cFilAnt) oIPC:Start("U_IPCTEST2") For nX := 1 To 1000 oIPC:Go(nX) Next nX oIPC:Stop() FreeObj(oIPC) oIPC := Nil Return //--------------------------------------------------------------------- /*/{Protheus.doc} IPCTEST2 Função que será executada nas threads de exemplo da FWIpcWait @author FRAMEWORK @since 11/09/2024 @version 1.0 */ //--------------------------------------------------------------------- User Function IPCTEST2(nX as numeric) ConOut("Entrei...", nX, Time()) Sleep(2000) ConOut("Saindo...", nX, Time()) Return ``` -------------------------------- ### REST Server (tlppCore) - Hello World Example Source: https://context7.com/gomesad/doc-advpl-tlpp/llms.txt Demonstrates how to create a simple 'Hello World' REST API endpoint using the @Get annotation with both functions and classes in TLPP. ```APIDOC ## POST /test/helloWorld ### Description Creates a simple REST endpoint that returns a "Hello World" message. ### Method GET ### Endpoint /test/helloWorld ### Parameters None ### Request Example GET http://localhost:9995/test/helloWorld ### Response #### Success Response (200) - **string** - A greeting message. #### Response Example "Meu primeiro REST em TL++ " ``` -------------------------------- ### Basic TDialog Initialization Example - ADVPL Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL/AdvPL - Classes/Janelas/Diálogo/TDialog/Classe TDialog - Construtores/Construtor TDialog_New.md Provides a straightforward example of initializing a TDialog object using the TDialog:New constructor. This code snippet demonstrates setting essential parameters such as top, left, bottom, right coordinates, the window caption, and background/text colors. It serves as a starting point for creating basic dialog windows. ```advpl oDlg := TDialog():New(180,180,550,700,'Exemplo TDialog',,,,,CLR_BLACK,CLR_WHITE,,,.T.) ``` -------------------------------- ### Example Usage of DBCommitAll - ADvPL/TL++ Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL/AdvPL - Functions/Banco de Dados/Acesso a Banco de Dados - Funções genéricas/DBCommitAll.md This example demonstrates the practical application of DBCommitAll. It involves creating and opening tables, appending data, and then committing all changes using DBCommitAll. It also shows the necessary setup and cleanup functions like TCLink, DBUseArea, DBCloseArea, and TCUnlink. ```advpl FUNCTION Example() Local cT1 := "T1" Local cT2 := "T2" TCLink() DBCreate("T1", {{"FIELD_NAME", "C", 10, 0},; {"FIELD_TYPE", "C", 10, 0}}, "TOPCONN") DBCreate("T2", {{"FIELD_NAME", "C", 10, 0}, ; {"FIELD_TYPE", "C", 10, 0}}, "TOPCONN") DBUseArea(.F., 'TOPCONN', cT1, (cT1), .F., .F.) (cT1)->( DBAppend( .F. ) ) (cT1)->FIELD_NAME := "name" (cT1)->FIELD_TYPE := "string" // Deve abrir a tabela com parametro de nova area como Verdadeiro (.T.) ver documentação DBUseArea DBUseArea(.T., 'TOPCONN', cT2, (cT2), .F., .F.) (cT2)->( DBAppend( .F. ) ) (cT2)->FIELD_NAME := "name" (cT2)->FIELD_TYPE := "string" DBCommitAll() DBCloseArea() DBCloseArea() TCUnlink() RETURN ``` -------------------------------- ### ADvPL TLPP: Redis List Management Example Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL/AdvPL - Classes/Componentes/Não Visual/Classe TListSvc.md This example demonstrates how to use the TListSvc class in ADvPL TLPP to interact with Redis lists. It covers setup, message putting, getting, and deleting. Dependencies include 'protheus.ch'. It takes Redis connection details and message data as input and outputs status messages to the console. ```advpl #include "protheus.ch" // Setup Redis Static cRedisHost := "tec-clima" Static nRedisPort := 6379 User Function LstPut() Local nRet := 0 // ID da mensagem Local cMsgId1 := "id1" // Mensagem a enviar Local cMsg := '{"inteiro":100,"double":10.32,"OK":true,"NOK":false,"NULO":null,"VAZIO":"","ROWS":[{"Valor":5000,"OBJ":{"x":2},"Data":"2014-08-29"}, "ricardo"], "VETOR":[1,2,3,4]}' // Nome da Lista Local cListName := "Lista_TQLS" // Objeto de Lista Local oTQLS := Nil Local cMsgGet := "" // Cria um novo objeto de Lista oTQLS := TListSvc():New(cListName) If(oTQLS == Nil) ConOut("### ERRO ### " + "Erro na criacao da Lista - " + cListName) Return .F. Else ConOut("Criacao da Lista OK - " + oTQLS:cName) EndIf // Configurando a Lista nRet := oTQLS:Setup(cRedisHost, nRedisPort) If nRet != 0 ConOut("### ERRO ### " + "Erro ao fazer o Setup" + " Erro: " + AllTrim(Str(nRet))) Return .F. Else ConOut("Setup de Lista OK - " + oTQLS:cName + " nMsgRetPer: " + AllTrim(Str(oTQLS:nMsgRetPer))) EndIf // Gravando uma mensagem nRet := oTQLS:PutMsg( cMsgId1, cMsg ) If nRet != 0 ConOut("### ERRO ### " + "Erro ao enviar mensagem" + " Erro: " + AllTrim(Str(nRet))) Return .F. Else ConOut("Enviou msg Lista OK - " + oTQLS:cName + " com ID: " + cMsgId1 + " Tamanho: " + AllTrim(Str(Len(cMsg)))) EndIf // Obtem uma mensagem nRet := oTQLS:GetMsg( cMsgId1, @cMsgGet ) If nRet != 0 ConOut("### ERRO ### " + "Erro ao receber mensagem" + " Erro: " + AllTrim(Str(nRet))) Return .F. Else ConOut("Recebeu msg Lista OK - " + oTQLS:cName + " com ID: " + cMsgId1 + " Tamanho: " + AllTrim(Str(Len(cMsgGet)))) EndIf // Removendo uma mensagem nRet := oTQLS:DelMsg( cMsgId1 ) If nRet != 0 ConOut("### ERRO ### " + "Erro ao remover mensagem" + " Erro: " + AllTrim(Str(nRet))) Return .F. Else ConOut("Removeu msg Lista OK - " + oTQLS:cName + " com ID: " + cMsgId1) EndIf Return .T. ``` -------------------------------- ### Handle GET Request with Query String in Function (ADvPL/TLPP) Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/TLPP/TlppCore - Ferramentas e Módulos/REST/2 - Configurações Avançadas/A - Verbos_Métodos disponíveis (@annotation)/@GET().md This example demonstrates a function designed to handle HTTP GET requests and extract parameters from the query string. It uses the @Get annotation and the oRest:getQueryRequest() method. Include 'tlpp-core.th' and 'tlpp-rest.th'. ```ADvPL/TLPP #include "tlpp-core.th" #include "tlpp-rest.th" /* --------------------------------------- */ @Get("examples/function/get/query/user") User Function examplesFunctionGetQuery() Local cJson := "" Local jQuery jQuery := JsonObject():New() jQuery := oRest:getQueryRequest() If (jQuery <> Nil) cJson := '[ {"description": "examplesFunctionGetQuery successfully executed, parameter received: ' + jQuery['user'] + '"} ]' Endif Return oRest:setResponse(cJson) ``` -------------------------------- ### GET Request Example for PergunteService Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/Framework _ REST e SOAP/PergunteService - Serviço de Perguntas do Protheus.md Example of how to make a GET request to the PergunteService API to retrieve question data. This demonstrates the base URL and the service endpoint. ```http http://localhost:3000/rest/api/framework/v1/pergunteservice/FINR917 ``` -------------------------------- ### Setup and Connect to a Queue (TQueueSvc) in ADVP/TLPP Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL/AdvPL - Classes/Componentes/Não Visual/Classe TListSvc.md Initializes and sets up a queue service using TQueueSvc. It configures connection parameters and handles successful setup or connection failures. Returns the queue object on success or Nil on failure. ```advpl Static Function conFila(cNome) Local oFila := Nil Local nRet := 0 Local nMsgRetPeriod := 60 Local nVisibTimeOut := 5 If(oFila == Nil) oFila := TQueueSvc():New(cNome) // Configurando a Fila nRet := oFila:Setup(cFlLsServer, nFlLsPort, cFlLsAuth, nMsgRetPeriod, nVisibTimeOut) If (nRet == 0) PRT_MSG("Setup de Fila OK: " + oFila:cName) Return oFila Else PRT_ERROR("Falha de conexao com a Fila: " + oFila:cName + " Erro: " + cValToChar(nRet)) oFila := Nil EndIf Else Return oFila EndIf Return Nil ``` -------------------------------- ### GET /sampleMigrateRestTlpp Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/TLPP/TlppCore - Ferramentas e Módulos/REST/7 - Exemplos práticos/Migração WsRESTful para REST tlppCore.md Example of a GET request using annotation-based approach for TLPP. ```APIDOC ## GET /sampleMigrateRestTlpp ### Description Handles GET requests using annotations, retrieving data by ID from query parameters. ### Method GET ### Endpoint /sampleMigrateRestTlpp ### Parameters #### Query Parameters - **id** (CHARACTER) - Optional - The identifier for the data to retrieve. ### Request Example ```json { "METHOD": "GET", "id": "" } ``` ### Response #### Success Response (200) - **METHOD** (CHARACTER) - Indicates the HTTP method. - **id** (CHARACTER) - The ID retrieved from the query parameters. #### Response Example ```json { "METHOD": "GET", "id": "456" } ``` ``` -------------------------------- ### Start() - Start Execution Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL - Classes/Classe FWIPCWait.md Initiates the queue execution. ```APIDOC ## Start() ### Description Initiates the queue execution. ### Method Start(cFunction) ### Parameters #### Path Parameters - **cFunction** (Character) - Required - The function that starts the execution threads. ### Returns Does not have an explicit return value. ``` -------------------------------- ### GET /sampleMigrateRestProtheus Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/TLPP/TlppCore - Ferramentas e Módulos/REST/7 - Exemplos práticos/Migração WsRESTful para REST tlppCore.md Example of a GET request using FWREST framework for Protheus. ```APIDOC ## GET /sampleMigrateRestProtheus ### Description Handles GET requests to retrieve data, optionally by an ID. ### Method GET ### Endpoint /sampleMigrateRestProtheus ### Parameters #### Query Parameters - **id** (CHARACTER) - Optional - The identifier for the data to retrieve. ### Request Example ```json { "METHOD": "GET", "id": "" } ``` ### Response #### Success Response (200) - **METHOD** (CHARACTER) - Indicates the HTTP method. - **id** (CHARACTER) - The ID passed in the request. #### Response Example ```json { "METHOD": "GET", "id": "123" } ``` ``` -------------------------------- ### Example: Create and Activate FWMarkBrowse (AdvPL) Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL - Classes/FWMarkBrowse.md A comprehensive AdvPL example demonstrating the creation of a FWMarkBrowse object, defining columns, setting a data query, and activating the browse interface. It showcases dynamic column definition and data retrieval. ```AdvPL User Function MontaBrowse() Local nContFlds As Numeric Local cAlias As Character Local aFields As Array Local aColumns As Array Local oMark As Object cAlias := GetNextAlias() aFields := {} aColumns := {} oMark := FWMarkBrowse():New() aAdd( aFields, {"B1_COD", "Código"} ) aAdd( aFields, {"B1_DESC", "Descrição"} ) For nContFlds := 1 To Len( aFields ) AAdd( aColumns, FWBrwColumn():New() ) aColumns[Len(aColumns)]:SetData( &("{ || " + aFields[nContFlds][1] + " }") ) aColumns[Len(aColumns)]:SetTitle( aFields[nContFlds][2] ) aColumns[Len(aColumns)]:SetSize( 15 ) aColumns[Len(aColumns)]:SetID( aFields[nContFlds] ) Next nContFlds oMark:SetColumns( aColumns ) oMark:SetDataQuery() oMark:SetQuery( "SELECT B1_OK,B1_COD,B1_DESC FROM SB1010 WHERE B1_COD = '000001'" ) oMark:SetAlias( cAlias ) oMark:SetMenuDef('') oMark:SetFieldMark( 'B1_OK' ) oMark:Activate() Return ``` -------------------------------- ### Get Profile (GET) - API Example Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/Framework _ REST e SOAP/APIs Rest Framework/ProfileService.md Provides an example of how to retrieve a Profile using the ProfileService API. The programName, task, and type are part of the URL. The 'branch' parameter can be used for company-specific lookups, and 'defaultValue' can be provided if the profile is not found. ```http GET /api/framework/v1/profileService/xisto/xpto/etc?branch=true&defaultValue=default HTTP/1.1 ``` -------------------------------- ### Example Usage of FWGridProcess (AdvPL) Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL - Classes/FWGridProcess.md Demonstrates the usage of the FWGridProcess class, including setting parameters, activating the grid, and checking its finished status. It also shows how to handle user interruptions within the processing loop. ```AdvPL User Function testeba() RpcSetEnv("99","01") __cInterNet := Nil oGrid:=FWGridProcess():New("MATA330","teste","teste do processamento",{|lEnd| u_testeba1(oGrid,@lEnd)},"MTA330","u_testeba2") oGrid:SetMeters(2) oGrid:SetThreadGrid(5) oGrid:Activate() If oGrid:IsFinished() alert("fim") Else alert("fim com erro") EndIf Return User Function Testeba1(oGrid,lEnd) Local nX,nY oGrid:SetMaxMeter(4,1,"teste1") For nX := 1 To 4 oGrid:SetMaxMeter(10,2,"teste2") For nY := 1 To 10 If !oGrid:CallExecute("callexecute is load",Iif(nX==5.And.nY==10,0,1)) lEnd := .T. EndIf oGrid:SetIncMeter(2) If lEnd Exit EndIf Next nY If lEnd Exit EndIf oGrid:SetIncMeter(1) Next nX Return //Exemplo de uso de sem Grid User Function Testebc2(oGrid,lEnd) Local nX,nY oGrid:SetMaxMeter(4,1,"teste1") For nX := 1 To 4 oGrid:SetMaxMeter(10,2,"teste2") For nY := 1 To 10 oGrid:SetIncMeter(2) If lEnd Exit EndIf Sleep(1000) Next nY If lEnd Exit EndIf oGrid:SetIncMeter(1) Next nX Return User Function Testeba2(cParm,lErro) Sleep(10000) Return(.T.) ``` -------------------------------- ### Get Logged-in User ID Response (JSON) Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/Framework _ REST e SOAP/APIs Rest Framework/_users - implementação do protocolo SCIM sobre o cadastro de usuários do Protheus.md Example JSON response for the GET /users/GetUserId endpoint, indicating the ID of the logged-in user. ```json { "userID": "000000" } ``` -------------------------------- ### Example: Creating and Configuring MsSelBr Browse in AdvPL Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL/AdvPL - Classes/Componentes/Visual/MsSelBr.md This AdvPL code example shows how to instantiate and configure the MsSelBr class to create a browse dialog. It includes setting up columns, enabling the 'mark all' option, and defining a custom action for clicking the header. ```AdvPL #include "TOTVS.CH" User Function MsSelBr() DEFINE DIALOG oDlg TITLE "Exemplo MsSelBr" FROM 180,180 TO 550,700 PIXEL DbSelectArea('SA1') oBrowse := MsSelBr():New( 1,1,260,184,,,,oDlg,,,,,,,,,,,,.F.,'SA1',.T.,,.F.,,,,.F.,) oBrowse:AddColumn(TCColumn():New('Codigo',{||SA1->A1_COD },,,,'LEFT',,.F.,.F.,,,,.F.,)) oBrowse:AddColumn(TCColumn():New('Loja' ,{||SA1->A1_LOJA},,,,'LEFT',,.F.,.F.,,,,.F.,)) oBrowse:AddColumn(TCColumn():New('Nome' ,{||SA1->A1_NOME},,,,'LEFT',,.F.,.F.,,,,.F.,)) oBrowse:lHasMark := .T. oBrowse:bAllMark := {|| alert('Click no header da browse') } ACTIVATE DIALOG oDlg CENTERED Return ``` -------------------------------- ### AdvPL HTTP GET Request Examples Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL/AdvPL - Functions/Interface HTTP/HTTPGet.md Demonstrates how to use the HTTPGet function in AdvPL to fetch web pages. Includes examples for basic GET requests, passing parameters in the URL, and using the Escape function for proper URI encoding. ```AdvPL #INCLUDE "TOTVS.CH" User Function tstGet() Local cHtmlPage // Buscar página cHtmlPage := Httpget('http://www.servidor.com.br/pageteste.htm') conout("WebPage", cHtmlPage) // Chamar página passando parâmetros cHtmlPage := Httpget('http://www.servidor.com.br/funteste.asp?Id=123&Nome=Teste') conout("WebPage", cHtmlPage) // ou cHtmlPage := Httpget('http://www.servidor.com.br/funteste.asp','Id=123&Nome=Teste') conout("WebPage", cHtmlPage) // ou utilizando a função Escape (recomendado) cHtmlPage := Httpget('http://www.servidor.com.br/funteste.asp','Id=' + Escape('123') + '&Nome=' + Escape('Ana Silva')) conout("WebPage", cHtmlPage) Return ``` -------------------------------- ### FWBmpRep Class Constructor and Repository Management Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL - Classes/FWBmpRep.md Demonstrates the instantiation of the FWBmpRep class and the basic operations of opening and closing the image repository. It also shows how to check the record count within the repository. ```advpl #include "protheus.ch" #define C_GRUPO "99" #define C_FILIAL "01" user function imgReposit() local oImgRepo as object local lInluiu as logical local cEntry as char RpcSetEnv(C_GRUPO, C_FILIAL) oImgRepo := FWBmpRep():New() if oImgRepo:OpenRepository() lInluiu := .F. ConOut("Quantidade de registros: ", oImgRepo:RecordCount()) // ... other operations ... oImgRepo:CloseRepository() endif FreeObj(oImgRepo) RpcClearEnv() return ``` -------------------------------- ### GET Request with Query Parameter (Class Method) Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/TLPP/TlppCore - Ferramentas e Módulos/REST/2 - Configurações Avançadas/A - Verbos_Métodos disponíveis (@annotation)/@GET().md This class method handles a GET request with a parameter in the query string. The 'user' parameter is accessed via oRest:getQueryRequest(). ```APIDOC ## GET /examples/class/get/query/user ### Description Handles a GET request within a class and retrieves a 'user' parameter from the query string. ### Method GET ### Endpoint /examples/class/get/query/user ### Parameters #### Query Parameters - **user** (string) - Required - The user identifier provided in the query string. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **description** (string) - A message indicating successful execution and the received parameter. ``` -------------------------------- ### Setup and Connect to a List (TListSvc) in ADVP/TLPP Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL/AdvPL - Classes/Componentes/Não Visual/Classe TListSvc.md Initializes and sets up a list service using TListSvc. It configures connection parameters and handles successful setup or connection failures. Returns true on success or false on failure. ```advpl Static Function conLista(oList, cNome) Local nRet := 0 Local nMsgRetPeriod := 60 If(oList == Nil) oList := TListSvc():New(cNome) // Configurando a Lista nRet := oList:Setup(cFlLsServer, nFlLsPort, cFlLsAuth, nMsgRetPeriod) //nRet := oList:Setup(cFlLsServer, nFlLsPort, nMsgRetPeriod) If (nRet == 0) PRT_MSG("Setup de Lista OK: " + oList:cName) Return .T. Else PRT_ERROR("Falha de conexao com a Lista: " + oList:cName + " Erro: " + cValToChar(nRet)) oList := Nil EndIf Else Return .T. EndIf Return .F. ``` -------------------------------- ### GET Request with Path Parameter (Class Method) Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/TLPP/TlppCore - Ferramentas e Módulos/REST/2 - Configurações Avançadas/A - Verbos_Métodos disponíveis (@annotation)/@GET().md This class method handles a GET request with a parameter in the URL path. The 'user' parameter is accessed via oRest:getPathParamsRequest(). ```APIDOC ## GET /examples/class/get/path/user/:user ### Description Handles a GET request within a class and retrieves a 'user' parameter from the URL path. ### Method GET ### Endpoint /examples/class/get/path/user/:user ### Parameters #### Path Parameters - **user** (string) - Required - The user identifier provided in the URL path. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **description** (string) - A message indicating successful execution and the received parameter. ``` -------------------------------- ### Setup Redis Queue in ADVP/TLPP Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL/AdvPL - Classes/Componentes/Não Visual/Classe TQueueSvc/Classe TQueueSvc - Métodos/TQueueSvc_Setup.md This code snippet demonstrates how to initialize and configure a Redis queue using the TQueueSvc service in ADVP/TLPP. It includes setting the Redis host, port, queue name, and message visibility timeout. Error handling is included for queue creation and setup operations. ```advpl #include 'protheus.ch' // Setup Redis Static cRedisHost := "tec-clima" Static nRedisPort := 6379 User Function FilStpC() Local nRet := 0 // Nome da Fila Local cQueueName := "Fila_TQLS" // Tempo de espera de tratamento de mensagem Local nVisibTimeOut := 33 // segundos // 0 usa o default // -1 recupara o valor // Objeto de Fila Local oTQLS := Nil // Cria um novo objeto de Fila oTQLS := TQueueSvc():New(cQueueName) If(oTQLS == Nil) ConOut("### ERRO ### " + "Erro na criacao da Fila - " + cQueueName) Return .F. Else ConOut("Criacao da Fila OK - " + oTQLS:cName) EndIf // Configurando a Fila nRet := oTQLS:Setup(cRedisHost, nRedisPort, , , nVisibTimeOut) If nRet != 0 ConOut("### ERRO ### " + "Erro ao fazer o Setup" + " Erro: " + AllTrim(Str(nRet))) Return .F. Else ConOut("Setup de Fila OK - " + oTQLS:cName + " nMsgRetPer: " + AllTrim(Str(oTQLS:nMsgRetPer)) + " nVisTimeOut: " + AllTrim(Str(oTQLS:nVisTimeOut))) EndIf Return .T. ``` -------------------------------- ### GET Request with Query Parameter (Function) Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/TLPP/TlppCore - Ferramentas e Módulos/REST/2 - Configurações Avançadas/A - Verbos_Métodos disponíveis (@annotation)/@GET().md This endpoint shows how to handle a GET request where a parameter is provided in the query string. The parameter 'user' is extracted using oRest:getQueryRequest(). ```APIDOC ## GET /examples/function/get/query/user ### Description Handles a GET request and retrieves a 'user' parameter from the query string. ### Method GET ### Endpoint /examples/function/get/query/user ### Parameters #### Query Parameters - **user** (string) - Required - The user identifier provided in the query string. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **description** (string) - A message indicating successful execution and the received parameter. ``` -------------------------------- ### ADVPL TLPP Grid Initialization and Usage Example Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL/AdvPL - Classes/Componentes/Visual/TGrid.md This code snippet shows a practical example of how to initialize and use the 'MyGrid' component within a dialog. It includes setting up grid appearance via CSS, populating it with data, and adding buttons for user interaction like clearing rows and updating data. ```ADVPL // U_TSTGRID ( Executa Grid ) //------------------------------------------------------------------ USER FUNCTION EXEMPLO() Local oDlg, aData:={}, i, oGridLocal, oEdit, nEdit:= 0 Local oBtnAdd, oBtnClr, oBtnLoa // configura pintura da TGridLocal cCSS:= "QTableView{ alternate-background-color: red; background: yellow; selection-background-color: #669966 }" // configura pintura do Header da TGrid cCSS+= "QHeaderView::section { background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #616161, stop: 0.5 #505050, stop: 0.6 #434343, stop:1 #656565); color: white; padding-left: 4px; border: 1px solid #6c6c6c; }" // Dados for i:=1 to 10000 cCodProd:= StrZero(i,6) if i<3 // inserindo imagem nas 2 primeiras linhas cProd:= "RPO_IMAGE=OK.BMP" else cProd:= 'Produto '+cCodProd endif cVal = Transform( 10.50, "@E 99999999.99" ) AADD( aData, { cCodProd, cProd, cVal } ) next DEFINE DIALOG oDlg FROM 0,0 TO 500,500 PIXEL oGrid:= MyGrid():New(oDlg,aData) oGrid:SetFreeze(2) oGrid:SetCSS(cCSS) //oGrid:SetHScrollState(GRID_HSCROLL_ALWAYSON) // Somente build superior a 131227A // Aplica configuração de pintura via CSSoGrid:SetCSS(cCSS) @ 210, 10 GET oEdit VAR nEdit OF oDlg PIXEL PICTURE "99999" @ 210, 70 BUTTON oBtnAdd PROMPT "Go" OF oDlg PIXEL ACTION oGrid:SelectRow(nEdit) @ 210, 100 BUTTON oBtnClr PROMPT "Clear" OF oDlg PIXEL ACTION oGrid:ClearRows() @ 210, 150 BUTTON oBtnLoa PROMPT "Update" OF oDlg PIXEL ACTION oGrid:DoUpdate() ``` -------------------------------- ### Start and Test REST Server in ADVPL TLPP Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/TLPP/TlppCore - Ferramentas e Módulos/REST/1 - Primeiros Passos/A - Configuração básica/Via JSON ( código fonte ).md This snippet initiates the REST server and provides URLs for testing. It calls the `Start` method of the `oVdrCtrl` object with the configured JSON object `jo`. If the server starts successfully (returns 0), it outputs the server port and test URLs to the console. Error handling is included for failed startup. ```ADVPL ConOut("Starting rest server on port: " + cValToChar(jo[sSS_ServerName]['Port'])) nResult := oVdrCtrl:Start(jo) If(ValType(nResult) == 'N' .AND. nResult == 0) ConOut("Rest server started") cURLTest += "localhost:" cURLTest += cValToChar(jo[sSS_ServerName]['Port']) cURLTest += jo[sSS_Location]['Path'] cURLTest2 := cURLTest cURLTest3 := cURLTest cURLTest += "/tlpp/environment" cURLTest2 += "/test" cURLTest3 += cGetPath ConOut("To test try on browser: ") ConOut(cURLTest) ConOut(cURLTest2) ConOut(cURLTest3) ConOut("") Return .T. Else // Falhou ConOut("Fail to start rest server [" + cValToChar(nResult) + "] - " + cValToChar(oVdrCtrl:nErr) + " - " + cValToChar(oVdrCtrl:cErr)) Return .F. EndIf Return .F. ``` -------------------------------- ### GET Request with Path Parameter (Function) Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/TLPP/TlppCore - Ferramentas e Módulos/REST/2 - Configurações Avançadas/A - Verbos_Métodos disponíveis (@annotation)/@GET().md This endpoint demonstrates how to handle a GET request with a parameter specified in the URL path. The parameter 'user' is extracted using oRest:getPathParamsRequest(). ```APIDOC ## GET /examples/function/get/path/user/:user ### Description Handles a GET request and retrieves a 'user' parameter from the URL path. ### Method GET ### Endpoint /examples/function/get/path/user/:user ### Parameters #### Path Parameters - **user** (string) - Required - The user identifier provided in the URL path. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **description** (string) - A message indicating successful execution and the received parameter. ``` -------------------------------- ### TTrackMenu Class Initialization and Usage Example Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/AdvPL/AdvPL - Deprecated/AdvPL - Deprecated classes/TTrackMenu (descontinuado).md This AdvPL code demonstrates how to initialize and use the TTrackMenu class. It includes defining dialog properties, creating a TTrackMenu instance, adding buttons with various configurations, and handling user interactions through a callback function. ```AdvPL #include "TOTVS.CH" //------------------------------------------------- Function u_TrackMenu() //------------------------------------------------- local nX local switch := .T. DEFINE MSDIALOG oDlg TITLE "TTrackMenu" FROM 0,0 TO 650,400 COLORS 0, 13945799 PIXEL nTop := 05 nLeft := 05 nWidth := 150 nHeight := 306 oPanel := tPanel():New(nTop,nLeft,,oDlg,,,,,,nWidth,nHeight) // Estilo iPhone ® oPanel:SetCss( " QLabel { background-color: white; border-radius: 12px ; border: 2px solid gray;}" ) cColorBackGround := "#FFFFFF" cColorSeparator := "#C0C0C0" cGradientTop := "#57A2EE" // Gradiente inicial do botao selecionado cGradientBottom := "#2BD0F7" // Gradiente final do botao selecionado cColorText := "#000000" // Estilo Android ® /* oPanel:SetCss( " QLabel { background-color: black; border-radius: 12px ; border: 2px solid gray;}" ) cColorBackGround := "#000000" cColorSeparator := "#FFFFFF" cGradientTop := "#087BA6" // Gradiente inicial do botao selecionado cGradientBottom := "#087BA6" // Gradiente final do botao selecionado cColorText := "#C0C0C0" */ cHeigthBtn := 40 oFont := TFont():New('Arial',,12,,.T.,,,,,.F.,.F.) oTrackMenu := TTrackMenu():New( oPanel, 3, 2, nWidth-4, nHeight-6, {|o,cID| MyAction(o, cId, @switch) }, cHeigthBtn, cColorBackGround, cColorSeparator,; cGradientTop, cGradientBottom, oFont, cColorText ) // Insere botoes oTrackMenu:Add("ID001", "Item Menu 1", "afastamento", ) oTrackMenu:Add("ID002", "Item Menu 2", "agenda" , "switch_on" ) oTrackMenu:Add("ID003", "Item Menu 3", "aviao" , "dummy.png" ) oTrackMenu:Add("ID004", "Item Menu 4", "bahead" , "arrow" ) oTrackMenu:Add("ID005", "Item Menu 5", , "arrow" ) for nX := 6 to 100 oTrackMenu:Add("ID"+StrZero(nX,3), "Item Menu "+cValToChar(nX)) next nX ACTIVATE MSDIALOG oDlg CENTERED Return //------------------------------------------------- Static Function MyAction(oTrackMenu, cId, switch) //------------------------------------------------- local nX // Similação de Switch (Liga-Desliga) if cId == "ID002" switch = !switch oTrackMenu:SetImage( "ID002", iif(switch, "switch_on", "switch_off") ) endif // Simulação de barra de progresso if cId == "ID003" oTrackMenu:lReadOnly := .T. for nX := 1 to 5 oTrackMenu:SetImage( "ID003", "bar0"+cValToChar(nX) ) ProcessMessages() sleep(500) next oTrackMenu:lReadOnly := .F. endif // Exibe item selecionado Conout("Item Selecionado: "+cID) Return ``` -------------------------------- ### AdvPL TLPP POST: Function with Path Parameter Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/TLPP/TlppCore - Ferramentas e Módulos/REST/2 - Configurações Avançadas/A - Verbos_Métodos disponíveis (@annotation)/@POST().md This example demonstrates how to use the @Post() annotation with a function to handle POST requests and retrieve parameters from the URL path. It utilizes `oRest:getPathParamsRequest()` to get path parameters and `oRest:getBodyRequest()` to get the request body. ```advpl #include "tlpp-core.th" #include "tlpp-rest.th" /* ----------------------------------------- */ @Post("examples/function/post/path/user/:user") User Function examplesFunctionPostPath() Local cJson := "" Local jPath Local cBody := "" jPath := JsonObject():New() jPath := oRest:getPathParamsRequest() cBody := oRest:getBodyRequest() If (jPath <> Nil) cJson := '[ { "description": "examplesFunctionPostPath successfully executed, parameter received: ' + jPath['user'] + '" , "body received":"'+ cBody + '"} ]' Endif Return oRest:setResponse(cJson) ``` -------------------------------- ### Handle GET Requests in Class Methods (ADvPL/TLPP) Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/TLPP/TlppCore - Ferramentas e Módulos/REST/2 - Configurações Avançadas/A - Verbos_Métodos disponíveis (@annotation)/@GET().md This snippet illustrates how to define a class with methods that handle HTTP GET requests, supporting both path parameters and query strings. It uses the @Get annotation on individual methods. Ensure 'tlpp-core.th' and 'tlpp-rest.th' are included. ```ADvPL/TLPP #include "tlpp-core.th" #include "tlpp-rest.th" Class classGetExamples Public Method New() @Get("examples/class/get/path/user/:user") Public Method metodExamplesGetPath() @Get("examples/class/get/query/user") Public Method metodExamplesGetQuery() EndClass Method New() class classGetExamples Return self /* --------------------------------------- */ Method methodExamplesGetPath() class classGetExamples Local cJson := "" Local jPath jPath := JsonObject():New() jPath := oRest:getPathParamsRequest() If (jPath <> Nil) cJson := '[ {"description": "methodExamplesGetPath successfully executed, parameter received: ' + jPath['user'] + '"} ]' Endif Return oRest:setResponse(cJson) /* --------------------------------------- */ Method methodExamplesGetQuery() class classGetExamples Local cJson := "" Local jQuery jQuery := JsonObject():New() jQuery := oRest:getQueryRequest() If (jQuery <> Nil) cJson := '[ {"description": "methodExamplesGetQuery successfully executed, parameter received: ' + jQuery['user'] + '"} ]' Endif Return oRest:setResponse(cJson) ``` -------------------------------- ### Start REST Service with Configuration - ADVPL Source: https://github.com/gomesad/doc-advpl-tlpp/blob/main/DOC/TLPP/TlppCore - Ferramentas e Módulos/REST/4 - Entendendo o objeto oREST/E - Todas as funções/wsRestfulStart.md This ADVPL code snippet demonstrates how to configure and start a RESTful web service using the wsRestfulStart function. It involves creating a JsonObject with detailed configurations for the HTTP server, specific server instances, application locations, thread pools, and content types. The function is then called with the configuration object and an optional virtual path. ```ADVPL function u_doc_wsRestfulStart() local nResult := 0 local jo := Nil local cEnv := getenvserver() local _Port_ := 40011 local _Charset_ := "UTF-8" local _Server_ := "HTTP_SRV" local _Location_ := "HTTP_APP" local _ContentTypes_ := "APP_CONTENTTYPES" local _ThreadPool_ := "TP_APP" // HTTP Config // ----------- jo := JsonObject():new() jo['HTTPSERVER'] := JsonObject():new() jo['HTTPSERVER']['Log'] := .F. jo['HTTPSERVER']['Charset'] := _Charset_ jo['HTTPSERVER']['Servers'] := {_Server_} jo['HTTPSERVER']['LoadJSON'] := .F. jo['HTTPSERVER']['OldUrns'] := .F. // Server Config // ------------- jo[_Server_] := JsonObject():new() jo[_Server_]['HostName'] := "TOTVS_HTTP_SERVER" jo[_Server_]['Port'] := _Port_ jo[_Server_]['ContentTypes'] := _ContentTypes_ jo[_Server_]['Locations'] := { _Location_ } // Aplicativo // ---------- jo[_Location_] := JsonObject():new() jo[_Location_]['Path'] := '/' jo[_Location_]['RootPath'] := "root/web" jo[_Location_]['DefaultPage'] := {"index.html"} jo[_Location_]['ThreadPool'] := _ThreadPool_ // Configuração básica de Thread Pool jo[_ThreadPool_] := JsonObject():new() jo[_ThreadPool_]['Environment'] := cEnv jo[_ThreadPool_]['MinThreads'] := 1 jo[_ThreadPool_]['MaxThreads'] := 4 jo[_ThreadPool_]['MinFreeThreads'] := 1 jo[_ThreadPool_]['GrowthFactor'] := 1 jo[_ThreadPool_]['InactiveTimeout'] := 30000 jo[_ThreadPool_]['AcceptTimeout'] := 10000 // ContentTypes // ------------ jo[_ContentTypes_] := JsonObject():new() jo[_ContentTypes_]['htm'] := "text/html" jo[_ContentTypes_]['html'] := "text/html" jo[_ContentTypes_]['js'] := "application/x-javascript" jo[_ContentTypes_]['css'] := "text/css" jo[_ContentTypes_]['txt'] := "text/plain" jo[_ContentTypes_]['json'] := "application/json" jo[_ContentTypes_]['stm'] := "text/html" jo[_ContentTypes_]['tsp'] := "text/html" // Inicializa serviço HTTP // ----------------------- nResult := tlpp.rest.wsRestfulStart( jo, '/myrest' ) return nResult ```