### Basic FWRest GET Request Example Source: https://tdn.totvs.com/display/framework/FWRest?focusedCommentId=244741357 Demonstrates how to instantiate FWRest, set a path, and perform a GET request. It shows how to retrieve the result or the last error. ```AdvPL local oRestClient as object oRestClient := FWRest():New("http://code.google.com") oRestClient:setPath("/p/json-path/") if oRestClient:Get() ConOut(oRestClient:GetResult()) else ConOut(oRestClient:GetLastError()) endif ``` -------------------------------- ### FWRest GET Request Example Source: https://tdn.totvs.com/display/framework/FWRest Demonstrates how to instantiate FWRest, set the path, and perform a GET request. Handles success by outputting the result and failure by outputting the error. ```AdvPL user `function` `tstFwRestTest()``local oRestClient as object` `oRestClient := FWRest():New(``"http://code.google.com"``)``oRestClient:setPath(``"/p/json-path/"``)``if` `oRestClient:Get()``   ``ConOut(oRestClient:GetResult())``else``   ``ConOut(oRestClient:GetLastError())``endif` `return ``` -------------------------------- ### License Server Configuration Example Source: https://tdn.totvs.com/display/framework/License%2BServer%2BPims%2BMulticultivo Example configuration for the license.properties file in PIMS Multicultivo. Specify the host and modules according to your License Server setup. ```properties host=127.0.0.1 modules=modulo ``` -------------------------------- ### Manually Start TOTVS License Server on Linux Source: https://tdn.totvs.com/display/framework/TOTVS%2BLicense%2BServer%2BVirtual If the TOTVS License Server does not start automatically, navigate to the installation directory and execute these commands to set resource limits and start the application server. ```bash ulimit -s 1024 ulimit -n 65536 ./appsrvlinux ``` -------------------------------- ### Implement GET Method Service Source: https://tdn.totvs.com/display/framework/02.%2BCriando%2Buma%2Bclasse%2BREST?focusedCommentId=286736935 Implement the GET method using WSSERVICE. This example handles parameters from both URL path and QueryString, returning JSON responses. ```AdvPL WSMETHOD GET WSRECEIVE startIndex, count WSSERVICE sample Local i // define o tipo de retorno do método ::SetContentType("application/json") // verifica se recebeu parametro pela URL // exemplo: http://localhost:8080/sample/1 If Len(::aURLParms) > 0 // insira aqui o código para pesquisa do parametro recebido // exemplo de retorno de um objeto JSON ::SetResponse('{"id":' + ::aURLParms[1] + ', "name":"sample"}') Else // as propriedades da classe receberão os valores enviados por querystring // exemplo: http://localhost:8080/sample?startIndex=1&count=10 DEFAULT ::startIndex := 1, ::count := 5 // exemplo de retorno de uma lista de objetos JSON ::SetResponse('[' ) For i := ::startIndex To ::count + 1 If i > ::startIndex ::SetResponse(',') EndIf ::SetResponse('{"id":' + Str(i) + ', "name":"sample"}') Next ::SetResponse(']') EndIf Return .T. ``` -------------------------------- ### Implement GET Method Service Source: https://tdn.totvs.com/display/framework/02.%2BCriando%2Buma%2Bclasse%2BREST Implement the logic for the GET method. This example shows how to handle URL parameters and QueryString parameters, returning JSON data. ```AdvPL WSMETHOD GET WSRECEIVE startIndex, count WSSERVICE sample Local i // define o tipo de retorno do método ::SetContentType("application/json") // verifica se recebeu parametro pela URL // exemplo: http://localhost:8080/sample/1 If Len(::aURLParms) > 0 // insira aqui o código para pesquisa do parametro recebido // exemplo de retorno de um objeto JSON ::SetResponse('{"id":' + ::aURLParms[1] + ', "name":"sample"}') Else // as propriedades da classe receberão os valores enviados por querystring // exemplo: http://localhost:8080/sample?startIndex=1&count=10 DEFAULT ::startIndex := 1, ::count := 5 // exemplo de retorno de uma lista de objetos JSON ::SetResponse('[' ) For i := ::startIndex To ::count + 1 If i > ::startIndex ::SetResponse(',') EndIf ::SetResponse('{"id":' + Str(i) + ', "name":"sample"}') Next ::SetResponse(']') EndIf Return .T. ``` -------------------------------- ### Example Usage of FWIPCWait Class Source: https://tdn.totvs.com/display/framework/Classe%2BFWIPCWait Demonstrates the instantiation and usage of the FWIPCWait class for managing background threads. It includes setting up the environment, starting a process, iterating through tasks, and stopping the process. ```protheus #include "protheus.ch" #include "parmtype.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 //--------------------------------------------------------------------- /*/{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 ``` -------------------------------- ### Implement GET Method Service Source: https://tdn.totvs.com/display/framework/02.%2BCriando%2Buma%2Bclasse%2BREST?focusedCommentId=485856227 Implement the GET method using WSMETHOD and WSSERVICE. This example handles parameters from the URL path or QueryString and returns JSON data. ```AdvPL WSMETHOD GET WSRECEIVE startIndex, count WSSERVICE sample Local i // define o tipo de retorno do método ::SetContentType("application/json") // verifica se recebeu parametro pela URL // exemplo: http://localhost:8080/sample/1 If Len(::aURLParms) > 0 // insira aqui o código para pesquisa do parametro recebido // exemplo de retorno de um objeto JSON ::SetResponse('{"id":' + ::aURLParms[1] + ', "name":"sample"}') Else // as propriedades da classe receberão os valores enviados por querystring // exemplo: http://localhost:8080/sample?startIndex=1&count=10 DEFAULT ::startIndex := 1, ::count := 5 // exemplo de retorno de uma lista de objetos JSON ::SetResponse('[' ) For i := ::startIndex To ::count + 1 If i > ::startIndex ::SetResponse(',') EndIf ::SetResponse('{"id":' + Str(i) + ', "name":"sample"}') Next ::SetResponse(']') EndIf Return .T. ``` -------------------------------- ### FSeek Example: File Operations Source: https://tdn.totvs.com/display/framework/FSeek This example demonstrates how to use FSeek to get the file size, reset the pointer to the beginning, and close the file. Ensure the file exists and the path is correct. The fileio.ch header must be included for constants like FS_END. ```advpl #include 'fileio.ch'... User Function exemplo() IF (nHandle := FOPEN("c:\garbage\test.txt")) >= 0 // Posiciona no fim do arquivo, retornando o tamanho do mesmo nLength := FSEEK(nHandle, 0, FS_END) // Posiciona no início do arquivo FSEEK(nHandle, 0) // Fecha arquivo FCLOSE(nHandle) ELSE MsgStop( "File open error" ) ENDIF Return ``` -------------------------------- ### General Usage Example of FWBrwRelation Source: https://tdn.totvs.com/display/framework/FWBrwRelation This example demonstrates the complete setup and usage of the FWBrwRelation class to link two FWMBrowse instances. It includes initializing the dialog, creating layout panels, instantiating and configuring the browses, defining the relation, and activating the relationship. ```protheus //------------------------------------------------------------------- /*/{Protheus.doc} Função de exemplo de relacionamento entre browses @author Julio Teixeira @since 29/01/2024 @version 1.0 */ //------------------------------------------------------------------- User Function BrwRelat() Local aCoors AS ARRAY Local aRelation AS ARRAY Local oPanelUp AS OBJECT Local oFWLayer AS OBJECT Local oPanelDown AS OBJECT Local oDlgPrinc AS OBJECT Local oBrowseUp AS OBJECT Local oBrwDown AS OBJECT Local oRelation AS OBJECT aCoors := FWGetDialogSize( oMainWnd ) Define MsDialog oDlgPrinc Title "BrwRelat" From aCoors[1],aCoors[2] To aCoors[3],aCoors[4] Pixel // Cria o container onde serão colocados os browses oFWLayer := FWLayer():New() oFWLayer:Init( oDlgPrinc, .F., .T. ) // Define Painel Superior oFWLayer:AddLine( 'UPLINE', 55, .F. ) oFWLayer:AddCollumn( 'UPCOL', 100, .T., 'UPLINE' ) // Obtém objeto painel superior oPanelUp := oFWLayer:GetColPanel( 'UPCOL', 'UPLINE' ) // Painel Inferior oFWLayer:AddLine( 'DOWNLINE', 45, .F. ) oFWLayer:AddCollumn( 'DOWNCOL' , 100, .T., 'DOWNLINE' ) // Obtém objeto painel inferior oPanelDown := oFWLayer:GetColPanel( 'DOWNCOL' , 'DOWNLINE' ) // FWMBrowse superior oBrowseUp := FWMBrowse():New() oBrowseUp:SetOwner( oPanelUp ) oBrowseUp:SetDescription( "Cabeçalho" ) oBrowseUp:DisableDetails() oBrowseUp:SetAlias( 'SF1' ) oBrowseUp:Activate() // FWMBrowse inferior oBrwDown := FWMBrowse():New() oBrwDown:SetOwner( oPanelDown ) oBrwDown:SetDescription( "Itens" ) oBrwDown:DisableDetails() oBrwDown:SetAlias( 'SD1' ) oBrwDown:Activate() // Relacionamento entre os browses oRelation := FWBrwRelation():New() aRelation := { { 'D1_FILIAL', 'F1_FILIAL' }, { 'D1_DOC', 'F1_DOC' }, {'D1_SERIE','F1_SERIE'}, {'D1_FORNECE','F1_FORNECE'}, {'D1_LOJA','F1_LOJA'} } oRelation:AddRelation( oBrowseUp , oBrwDown , aRelation ) oRelation:Activate() Activate MsDialog oDlgPrinc Center oBrowseUp:DeActivate() oBrowseUp:Destroy() oBrwDown:DeActivate() oBrwDown:Destroy() FreeObj(oBrowseUp) FreeObj(oBrwDown) FreeObj(oRelation) FreeObj(oDlgPrinc) FreeObj(oPanelUp) FreeObj(oFWLayer) FreeObj(oPanelDown) Return ``` -------------------------------- ### Start TOTVS License Server Monitor Source: https://tdn.totvs.com/display/framework/TOTVS%2BLicense%2BServer%2BVirtual If the TOTVS License Server monitor does not start automatically, navigate to its directory and execute the 'smartclient' command to start it. ```bash ./smartclient ``` -------------------------------- ### Execute TOTVS License Server Install Script Source: https://tdn.totvs.com/display/framework/TOTVS%2BLicense%2BServer%2BVirtual Run the install script with different arguments to perform installation or updates. Use 'bash install 2' or 'bash install 3' for silent installations/updates, which require an installer.properties file. ```bash bash install ``` ```bash bash install 1 ``` ```bash bash install 2 ``` ```bash bash install 3 ``` -------------------------------- ### General Usage Example Source: https://tdn.totvs.com/display/framework/FWLegend Example demonstrating the general usage of the FWLegend class. ```APIDOC ```advpl //------------------------------------------------------------------- /*{Protheus.doc} u_legndTest Function example of FWLegend class usage @author Daniel Mendes @since 03/07/2020 @version 1.0 */ //------------------------------------------------------------------- function u_legndTest() local oLegend as object oLegend := FWLegend():New() oLegend:Add("", "BR_VERDE", "Verde") oLegend:Add("", "BR_AZUL", "Azul") oLegend:Add("", "BR_VERMELHO", "Vermelho") oLegend:Add("", "BR_AMARELO", "Amarelo") oLegend:Add("", "BR_BRANCO", "Branco") oLegend:Add("", "BR_CINZA", "Cinza") oLegend:Add("", "BR_LARANJA", "Laranja") oLegend:Add("", "BR_MARROM", "Marrom") oLegend:Activate() oLegend:View() oLegend:Deactivate() oLegend:SetNumber(.T.) oLegend:Activate() oLegend:View() oLegend:Deactivate() FreeObj(oLegend) return ``` ``` -------------------------------- ### Get Current Index Key Expression - AdvPL Source: https://tdn.totvs.com/display/framework/IndexKey This example demonstrates how to use the IndexKey function to retrieve the key expression of the current and a specified index order. It includes setup for creating and using indexes. ```AdvPL user function test() local cT1 := "T1" TCLink() if TcCanOpen(cT1) TCDelFile(cT1) endif DBCreate(cT1, {{ "T1_COD" , "C" , 2, 0}, ; {"T1_NAME" , "C" , 10, 0}}, "TOPCONN") DBUseArea(.T., "TOPCONN", cT1, (cT1), .F., .F.) DBCreateIndex("T1INDEX1", "T1_COD", {|| T1_COD }) DBCreateIndex("T1INDEX2", "T1_COD+T1_NAME", {|| T1_COD+T1_NAME }) (cT1)->( DBClearIndex() ) //Força o fechamento dos indices abertos dbSetIndex("T1INDEX1") //acrescenta a ordem de indice para a área aberta dbSetIndex("T1INDEX2") //acrescenta a ordem de indice para a área aberta dbSetOrder(2) msgInfo("Chave de índice ativo: "+ IndexKey(IndexOrd())) dbSetOrder(1) msgInfo("Chave de índice ativo: "+ IndexKey(IndexOrd())) DBCloseArea() tcUnLink() return ``` -------------------------------- ### Example: Preparing and Executing a Query Source: https://tdn.totvs.com/display/framework/FWPreparedStatement Demonstrates how to instantiate FWPreparedStatement, set a query with placeholders, bind string parameters, and retrieve the final query string with injected parameters. ```advpl User Function tPrepStat Local oStatement Local cQuery Local cFinalQuery Local cUser := "000001" Local cPassword := "testeFWPS" oStatement := FWPreparedStatement():New() cQuery := "SELECT * FROM users WHERE username=? AND password=?" //Define a consulta e os parâmetros oStatement:SetQuery(cQuery) oStatement:SetString(1,cUser) oStatement:SetString(2,cPassword) //Recupera a consulta já com os parâmetros injetados cFinalQuery := oStatement:GetFixQuery() ``` -------------------------------- ### Example: Inserting and Navigating Records with DBGoTop Source: https://tdn.totvs.com/display/framework/DBGoTop This example demonstrates how to create a table, insert records, and then use DBGoTop to navigate to the first record. It checks if the first record's 'FIELD_AGE' matches the expected value. ```advpl FUNCTION insert() Local cT1 := "T1" Local idx := 0 Local name := "" Local tp := "" Local age := "2" DBUseArea(.F., 'TOPCONN', cT1, (cT1), .F., .F.) WHILE (idx <= 5) name += "BA" tp += "T" age += "2" (cT1)->( DBAppend( .F. ) ) (cT1)->FIELD_NAME := name (cT1)->FIELD_TYPE := tp (cT1)->FIELD_AGE := age (cT1)->( DBCommit() ) idx++ ENDDO DBCloseArea() return FUNCTION Example() Local cT1 := "T1" TCLink() DBCreate("T1", {{ "FIELD_NAME", "C", 10, 0}, ; {"FIELD_TYPE", "C", 10, 0}, ; {"FIELD_AGE", "C", 10, 0}, ; {"FIELD_NICK", "C", 10, 0}, ; {"FIELD_COL", "C", 10, 0}}, "TOPCONN") U_insert() DBUseArea(.F., 'TOPCONN', cT1, (cT1), .F., .T.) (cT1)->(DBGoTop()) IF ((cT1)->FIELD_AGE == "22 ") conout("Found!") ENDIF DBCloseArea() TCUnlink() RETURN ``` -------------------------------- ### Get Field Count in Active Workspace - AdvPL Source: https://tdn.totvs.com/display/framework/FCount This example demonstrates how to use the FCount function to retrieve the number of fields in a database area. It includes setup for a temporary table, using the area, calling FCount, and verifying the result. ```AdvPL FUNCTION Example() Local cT1 := "T1" TCLink() DBCreate( "T1", {{ "FIELD_NAME", "C", 10, 0}, ; {"FIELD_TYPE", "C", 10, 0}, ; {"FIELD_AGE", "C", 10, 0}, ; {"FIELD_NICK", "C", 10, 0}, ; {"FIELD_COL", "C", 10, 0}}, "TOPCONN") DBUseArea(.F., 'TOPCONN', cT1, (cT1), .F., .T.) nRet := (cT1)->(FCount()) if nRet == 5 conout( "Existe 5 Colunas" ) endif DBCloseArea() TCUnlink() RETURN ``` -------------------------------- ### Typical BEGIN SEQUENCE Example Source: https://tdn.totvs.com/display/framework/BEGIN%2BSEQUENCE%2B...%2BEND Demonstrates the typical structure of the BEGIN SEQUENCE command, including error handling with a break and recovery. This example shows how to define an error block, execute code that might cause an error, and handle the recovery process. ```AdvPL user function Example() // Define um code block de tratamento de erro e guarda o code block atual Local oError := Errorblock({|e| Break(e) }) Begin Sequence var := var+1 // variavel não existe, logo, vai dar erro nesta linha conout( "Recover... Isto NÃO DEVE ser executado, de acordo com o break lançado no ErrorBlock" ) return .T. Recover conout("Isto DEVE ser executado... entrou no recover") End Sequence conout( "Isto DEVE ser executado" ) // Restaura o code block de tratamento de erro original ErrorBlock( oError ) Return 0 ``` -------------------------------- ### Consuming REST API with FWRest GET Source: https://tdn.totvs.com/display/framework/FWRest?focusedCommentId=494809702 Example of making a GET request using FWRest, including setting headers and path parameters. ```xBase Local oRestClient : = FWRest():New("http://localhost:7045") Local aHeader : = {} aadd(aHeader,'Authorization: BASIC Zmx1aWdjbG91ZDoxMjNAY2xvdWQ=') oRestClient:setPath("/sample/?startIndex=1&count=2") If oRestClient:Get(aHeader) ``` -------------------------------- ### Consuming REST API with FWRest GET Source: https://tdn.totvs.com/display/framework/FWRest?focusedCommentId=284352794 Example of making a GET request using FWRest, including setting headers and path parameters. ```AdvPL Local oRestClient := FWRest():New("http://localhost:7045") Local aHeader := {} aadd(aHeader,'Authorization: BASIC Zmx1aWdjbG91ZDoxMjNAY2xvdWQ=') oRestClient:setPath("/sample/?startIndex=1&count=2") If oRestClient:Get(aHeader) ``` -------------------------------- ### Full Example: Test FwQrCode Class Source: https://tdn.totvs.com/display/framework/FwQrCode This example demonstrates the complete usage of the FwQrCode class, including dialog creation, QR code instantiation, setting code, and refreshing the display. It requires PROTHEUS.CH and specific Protheus versions. ```advpl #INCLUDE "PROTHEUS.CH" //Consulte: http://tdn.totvs.com.br/display/mp/FwQrCode User Function TstQrCode() Local oDLG := Nil Local cCodigo := "http://www.totvs.com.br" + Space(60) Private oQrCode //Cria a Dialog DEFINE MSDIALOG oDlg TITLE "RDMAKE para teste da classe FwQrCode" FROM 0,0 TO 400,800 PIXEL //Cria o objeto FwQrCode oQrCode := FwQrCode():New({25,25,200,200},oDlg,cCodigo) //Get com o codigo exibido @25,150 GET oGet VAR cCodigo OF oDlg SIZE 200,10 PIXEL //Botao Gerar @45,150 BUTTON "Gerar" SIZE 30,20 PIXEL OF oDlg ACTION MsgRun("Gerando QRCode","Aguarde",{|| U_MyRefresh(cCodigo)}) PIXEL //Exibe a Dialog em Video ACTIVATE MSDIALOG oDlg CENTERED Return User Function MyRefresh(cNewCod) oQrCode:SetCodeBar(cNewCod) oQrCode:Refresh() Return ``` -------------------------------- ### Creating and Configuring a Browse Window Source: https://tdn.totvs.com/display/framework/FWFormBrowse This example demonstrates the complete process of defining a browse window, including table opening, dialog definition, browse configuration, adding columns, buttons, and legends, and finally activating the browse and dialog. ```xBase #INCLUDE "FWBROWSE.CH" User Function FormBrwTable() Local oBrowseLocal oButtonLocal oColumnLocal oDlg //------------------------------------------------------------------- // Abertura da tabela //------------------------------------------------------------------- DbUseArea(.T.,,"SX2990","SX2",.T.,.F.) DbSetOrder(1) //------------------------------------------------------------------- // Define a janela do Browse //------------------------------------------------------------------- DEFINE MSDIALOG oDlg FROM 0,0 TO 600,800 PIXEL //------------------------------------------------------------------- // Define o Browse //------------------------------------------------------------------- DEFINE FWFORMBROWSE oBrowse DATA TABLE ALIAS "SX2" OF oDlg //-------------------------------------------------------- // Cria uma coluna de marca/desmarca //-------------------------------------------------------- ADD MARKCOLUMN oColumn DATA { || If(.T./* Função com a regra*/,'LBOK','LBNO') } DOUBLECLICK { |oBrowse| /* Função que atualiza a regra*/ } HEADERCLICK { |oBrowse| /* Função executada no clique do header */ } OF oBrowse //-------------------------------------------------------- // Cria uma coluna de status //-------------------------------------------------------- ADD STATUSCOLUMN oColumn DATA { || If(.T./* Função com a regra*/,'BR_VERDE','BR_VERMELHO') } DOUBLECLICK { |oBrowse| /* Função executada no duplo clique na coluna*/ } OF oBrowse //-------------------------------------------------------- // Adiciona legenda no Browse //-------------------------------------------------------- ADD LEGEND DATA 'X2_CHAVE $ "AA1|AA2"' COLOR "GREEN" TITLE "Chave teste 1" OF oBrowse ADD LEGEND DATA '!(X2_CHAVE $ "AA1|AA2")' COLOR "RED" TITLE "Chave teste 2" OF oBrowse //------------------------------------------------------------------- // Adiciona as colunas do Browse //------------------------------------------------------------------- ADD BUTTON oButton TITLE "Botão 1" ACTION { || MsgAlert(oBrowse:At()) } OF oBrowse ADD BUTTON oButton TITLE "Botão 2" ACTION { || MsgAlert(oBrowse:At()) } OF oBrowse //------------------------------------------------------------------- // Adiciona as colunas do Browse //------------------------------------------------------------------- ADD COLUMN oColumn DATA { || X2_CHAVE } TITLE "Chave" SIZE 3 OF oBrowse ADD COLUMN oColumn DATA { || X2_ARQUIVO } TITLE "Arquivo" SIZE 10 OF oBrowse ADD COLUMN oColumn DATA { || X2_NOME } TITLE "Descrição" SIZE 40 OF oBrowse ADD COLUMN oColumn DATA { || X2_MODO } TITLE "Modo" SIZE 1 OF oBrowse //------------------------------------------------------------------- // Ativação do Browse //------------------------------------------------------------------- ACTIVATE FWFORMBROWSE oBrowse //------------------------------------------------------------------- // Ativação do janela //------------------------------------------------------------------- ACTIVATE MSDIALOG oDlg CENTERED Return ``` -------------------------------- ### Consuming REST API with FWRest GET Source: https://tdn.totvs.com/display/framework/FWRest?focusedCommentId=446697540 Example of making a GET request using FWRest, including setting headers and path with query parameters. ```xBase Local oRestClient := FWRest():New("http://localhost:7045") Local aHeader := {} aadd(aHeader,'Authorization: BASIC Zmx1aWdjbG91ZDoxMjNAY2xvdWQ=') oRestClient:setPath("/sample/?startIndex=1&count=2") If oRestClient:Get(aHeader) ``` -------------------------------- ### Setup Source: https://tdn.totvs.com/display/framework/FWMsPrinter Presents the printer configuration window. ```APIDOC ## Setup ### Description Presents the printer configuration window. ### Method FWMsPrinter():Setup() ### Remarks null ### Request Example ``` oPrinter:Setup() ``` ``` -------------------------------- ### Consuming REST API with FWRest GET Source: https://tdn.totvs.com/display/framework/FWRest?focusedCommentId=382560264 Example of making a GET request using FWRest, including setting headers and path with query parameters. ```AdvPL 1. Local oRestClient : = FWRest():New("http://localhost:7045") 2. Local aHeader : = {} 3. aadd(aHeader, 'Authorization: BASIC Zmx1aWdjbG91ZDoxMjNAY2xvdWQ=') 4. oRestClient:setPath("/sample/?startIndex=1&count=2") 5. If oRestClient:Get(aHeader) ``` -------------------------------- ### PREPARE ENVIRONMENT Example Usage Source: https://tdn.totvs.com/display/framework/Prepare%2BEnvironment Example of how to use the PREPARE ENVIRONMENT command to set a specific company, branch, user, password, tables, and module. The RESET ENVIRONMENT command is also shown. ```protheus PREPARE ENVIRONMENT EMPRESA '01' FILIAL '01' USER 'Administrador' PASSWORD '' TABLES 'SE1,SA1,SE2' MODULO ‘FAT’ /*******COMANDOS *********/ RESET ENVIRONMENT ``` -------------------------------- ### Create and Populate XTree Example Source: https://tdn.totvs.com/display/framework/XTree Demonstrates the creation of an XTree object and populating it with multiple levels of nodes using AddTree and AddTreeItem. Includes buttons for interacting with the tree. ```XBase #Include 'Protheus.ch' User Function tdnXtree() Local oGet Local cGet := Space(6) Local cDescri := Space(10) DEFINE DIALOG oDlg TITLE "Exemplo de XTree" FROM 0,0 TO 600,800 PIXEL //------------------- //Cria o objeto XTREE //------------------- oTree := xTree():New(000,000,300,300,oDlg,/*uChange*/,/*uRClick*/,/*bDblClick*/) //------- //Nível 1 //------- oTree:AddTree("01","folder5.png","folder6.png","01",/*bAction*/,/*bRClick*/,/*bDblClick") //------- //Nível 2 //------- oTree:AddTree("Teste","folder5.png","folder6.png","0101",/*bAction*/,/*bRClick*/,/*bDblClick") oTree:EndTree() oTree:AddTree("0101","folder5.png","folder6.png","0101",/*bAction*/,/*bRClick*/,/*bDblClick") //------- //Nível 3 //------- oTree:AddTreeItem("0102","folder5.png","0102",/*bAction*/,/*bRClick*/,/*bDblClick") oTree:EndTree() oTree:AddTree("0103","folder5.png","folder6.png","0103",/*bAction*/,/*bRClick*/,/*bDblClick") oTree:EndTree() oTree:EndTree() //--------------- //Funcionalidades //--------------- @ 000,340 GET oGet VAR cGet OF oDlg SIZE 40, 010 PIXEL TButton():New( 0,300 , "Seek Item", oDlg,{|| oTree:TreeSeek(AllTrim(cGet))},40,010,,,.F.,.T.,.F.,,.F.,,,.F. ) TButton():New( 010,300 , "Add Item", oDlg,{|| AddItem(oTree) },40,010,,,.F.,.T.,.F.,,.F.,,,.F. ) TButton():New( 020,300 , "Change BMP", oDlg,{|| oTree:ChangeBmp("LBNO","LBTIK","01") },40,010,,,.F.,.T.,.F.,,.F.,,,.F. ) @ 030,340 GET oGet1 VAR cDescri OF oDlg SIZE 40, 010 PIXEL TButton():New( 030,300 , "Altera Prompt", oDlg,{|| ChangePrompt(oTree,cDescri)},40,010,,,.F.,.T.,.F.,,.F.,,,.F. ) TButton():New( 040,300 , "Info Pai", oDlg,{|| ShowFatherInfo(oTree)},40,010,,,.F.,.T.,.F.,,.F.,,,.F. ) ACTIVATE DIALOG oDlg CENTERED Return Static Function ChangePrompt(oTree,cDescri) oTree:ChangePrompt(cDescri,oTree:GetCargo()) Return Static Function AddItem(oTree) If oTree:TreeSeek("0102") oTree:AddItem("Novo Item","0106","folder5.png","folder6.png",2,/*bAction*/,/*bRClick*/,/*bDblClick*/) EndIf Return Static Function ShowFatherInfo(oTree) Local aInfo := oTree:GetFatherNode() Local cMessage If Len(aInfo) > 0 cMessage := "ID do Pai : " + aInfo[1] + CRLF cMessage += "ID : " + aInfo[2] + CRLF cMessage += "É nó? : " + IIf(aInfo[3],".T.",".F.") + CRLF cMessage += "cCargo : " + aInfo[4] + CRLF cMessage += "cResource1: " + aInfo[5] + CRLF cMessage += "cResource2: " + aInfo[6] + CRLF MsgInfo(cMessage,"Info do nó pai") EndIf Return ``` -------------------------------- ### Consuming a REST API with FWRest GET Source: https://tdn.totvs.com/display/framework/FWRest?focusedCommentId=521652285 Example of making a GET request using FWRest, including setting headers and path parameters. Debugging the Get method might require inspecting headers separately. ```AdvPL Local oRestClient : New( "http://localhost:7045" ) Local aHeader : {} aadd(aHeader, 'Authorization: BASIC Zmx1aWdjbG91ZDoxMjNAY2xvdWQ=') oRestClient:setPath( "/sample/?startIndex=1&count=2" ) If oRestClient:Get(aHeader) ``` -------------------------------- ### GET Request for Specific User Source: https://tdn.totvs.com/display/framework/REST%2BADVPL Example of a GET request to retrieve a specific user resource by ID. Ensure the Host and Accept headers are correctly set. ```http GET /Users/2819c223 Host: example.com Accept: application/json ``` -------------------------------- ### Example Usage Source: https://tdn.totvs.com/display/framework/FwQrCode Demonstrates how to instantiate and use the FwQrCode class within a Protheus environment, including creating a dialog, setting the QR code content, and refreshing the display. ```APIDOC ## Example Usage ```protheus #INCLUDE "PROTHEUS.CH" User Function TstQrCode() Local oDLG := Nil Local cCodigo := "http://www.totvs.com.br" + Space(60) Private oQrCode // Create the Dialog DEFINE MSDIALOG oDlg TITLE "RDMAKE para teste da classe FwQrCode" FROM 0,0 TO 400,800 PIXEL // Create the FwQrCode object oQrCode := FwQrCode():New({25,25,200,200}, oDlg, cCodigo) // Get with the displayed code @25,150 GET oGet VAR cCodigo OF oDlg SIZE 200,10 PIXEL // Generate Button @45,150 BUTTON "Gerar" SIZE 30,20 PIXEL OF oDlg ACTION MsgRun("Gerando QRCode","Aguarde",{|| U_MyRefresh(cCodigo)}) // Display the Dialog on screen ACTIVATE MSDIALOG oDlg CENTERED Return User Function MyRefresh(cNewCod) oQrCode:SetCodeBar(cNewCod) oQrCode:Refresh() Return ``` ``` -------------------------------- ### FWBmpRep Image Repository Example Source: https://tdn.totvs.com/display/framework/FWBmpRep Demonstrates the usage of the FWBmpRep class to open, manipulate, and close an image repository. It includes inserting an image, extracting it, and handling potential errors. Ensure the image file exists before running. ```protheus #include "protheus.ch" #define C_GRUPO "99" #define C_FILIAL "01" //------------------------------------------------------------------- /*{Protheus.doc} imgReposit Exemplo de utilização da classe FWBmpRep, classe responsável pela manipulação do repositório de imagens @author Daniel Mendes @since 12/08/2020 @version 1.0 */ //------------------------------------------------------------------- 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()) if oImgRepo:ExistBmp("xisto") oImgRepo:DeleteBmp("xisto") endif cEntry := oImgRepo:InsertBmp("xisto.jpg", /*cEntry*/, @lInluiu) if lInluiu FErase("xisto.jpg") ConOut("Imagem " + cEntry + " inclusa") if oImgRepo:Extract(cEntry, "xisto.jpg") ConOut("Imagem " + cEntry + " recuperada") else ConErr("Erro ao recuperar a imagem " + cEntry) endif else ConErr("Erro ao incluir a imagem xisto.jpg") endif oImgRepo:CloseRepository() endif FreeObj(oImgRepo) RpcClearEnv() return ``` -------------------------------- ### Implementing GET Method Service Source: https://tdn.totvs.com/display/framework/02.%2BCriando%2Buma%2Bclasse%2BREST?focusedCommentId=286736935 Provides an example implementation for a GET method, handling both URL parameters and QueryString parameters, and setting the response content type. ```APIDOC ## GET Method Implementation ```advpl WSMETHOD GET WSRECEIVE startIndex, count WSSERVICE sample Local i // define o tipo de retorno do método ::SetContentType("application/json") // verifica se recebeu parametro pela URL // exemplo: http://localhost:8080/sample/1 If Len(::aURLParms) > 0 // insira aqui o código para pesquisa do parametro recebido // exemplo de retorno de um objeto JSON ::SetResponse('{"id":' + ::aURLParms[1] + ', "name":"sample"}') Else // as propriedades da classe receberão os valores enviados por querystring // exemplo: http://localhost:8080/sample?startIndex=1&count=10 DEFAULT ::startIndex := 1, ::count := 5 // exemplo de retorno de uma lista de objetos JSON ::SetResponse('[' ) For i := ::startIndex To ::count + 1 If i > ::startIndex ::SetResponse(',') EndIf ::SetResponse('{"id":' + Str(i) + ', "name":"sample"}') Next ::SetResponse(']') EndIf Return .T. ``` ``` -------------------------------- ### Example of MsNewProcess Usage Source: https://tdn.totvs.com/display/framework/MsNewProcess This example demonstrates how to initialize and activate MsNewProcess, including setting up callbacks for processing and cancellation. It also shows how to use SetRegua1 and SetRegua2 to update progress bars during routine execution. ```protheus #include "protheus.ch" //------------------------------------------------------------------- /*/{Protheus.doc} F114299 Exemplo de utilização da MsNewProcess @author Totvs @since 29/04/2024 //-----------------------------------------------------------------*/ Function U_F114299() Local oProcess //incluído o parâmetro lEnd para controlar o cancelamento da janela oProcess := MsNewProcess():New({|lEnd| T114299(@oProcess, @lEnd) }, "Teste MsNewProcess" , "Lendo Registros do Pedido de Vendas" ,.T.) oProcess:Activate() Return //------------------------------------------------------------------- /*/{Protheus.doc} T114299 Processamento @author Totvs @since 29/04/2024 //-----------------------------------------------------------------*/ static Function T114299(oProcess, lEnd) Local nCountC5 Local nCountC6 //inserido este bloco Default lEnd := .F. DbSelectArea( "SC5" ) DbSetOrder(1) DbGotop() nnCountC5 := SC5->(RecCount()) oProcess:SetRegua1(nCountC5) While SC5->(!Eof()) sleep(300) If lEnd //houve cancelamento do processo Exit EndIf oProcess:IncRegua1( "Lendo Pedido de Venda:" + SC5->C5_NUM) DbSelectArea( "SC6" ) DbSetOrder(1) DbClearFil() Set Filter to SC6->C6_FILIAL == xFilial( "SC5" ) .And. SC6->C6_NUM == SC5->C5_NUM COUNT to nCountC6 oProcess:SetRegua2(nCountC6) While SC6->(!Eof()) //inserido este bloco If lEnd //houve cancelamento do processo Exit EndIf oProcess:IncRegua2( "Pedido: "+SC5->C5_NUM+" - Item: "+SC6->C6_ITEM) sleep(300) conout( "Item: "+SC6->C6_ITEM) SC6->(DbSkip()) End SC5->(DbSkip()) End Return ``` -------------------------------- ### Initialize and Activate FWCarolWizard Source: https://tdn.totvs.com/display/framework/FWCarolWizard This snippet demonstrates the basic initialization and activation of the FWCarolWizard. It includes setting a welcome message, adding requirements, defining steps with their construction and validation logic, and adding a final processing function. It also shows how to configure trial mode and other wizard properties. ```protheus #include "protheus.ch" /*/{Protheus.doc} WizardTF Wizard para ativação da integração com a TechFin */ Main Function WizardTF() MsApp():New( "SIGAFIN" ) oApp:cInternet := Nil __cInterNet := NIL oApp:bMainInit := { || ( oApp:lFlat := .F. , TechFinWiz() , Final( "Encerramento Normal" , "" ) ) }//"Encerramento Normal" oApp:CreateEnv() OpenSM0() PtSetTheme( "TEMAP10" ) SetFunName( "UPDDISTR" ) oApp:lMessageBar := .T. oApp:Activate() Return /*/{Protheus.doc} FintechWiz Construção da Tela de Wizard @return Nil */ Static Function TechFinWiz() Local oWizard As Object Local cDescription As Character Local bConstruction As CodeBlock Local bNextAction As CodeBlock Local bPrevWhen As CodeBlock Local bCancelWhen As CodeBlock Local bProcess As CodeBlock Local aParam As Array Local cReqDes As Character Local cReqCont As Character Local bReqVld As CodeBlock Local cReqMsg As Character oWizard := FWCarolWizard():New() cDescription := "Novo Passo " //Passa o objeto para ser manipulado posteriormente nos steps adicionados bConstruction := { | oPanel | aParam := StepPage( oPanel , oWizard ) } bNextAction := { || VldStep( aParam ) } bPrevWhen := { || .F. } bCancelWhen := { || .T. } // bProcess := { | cGrpEmp, cMsg | FINTFWizPr( cGrpEmp, cMsg, aFinParam ) } bProcess := { | cGrpEmp, cMsg | ProcAnt( cGrpEmp, @cMsg, aParam ) } cReqDes := "Release do RPO cReqCont := GetRpoRelease() bReqVld := { || GetRpoRelease() >= "12.1.023" } cReqMsg := "Versão de RPO deve ser no mínimo 12.1.23" oWizard:SetWelcomeMessage( "Minha mensagem de boas vindas customizada" ) oWizard:AddRequirement( cReqDes, cReqCont, bReqVld, cReqMsg ) oWizard:AddStep( cDescription + "1", bConstruction, bNextAction, bPrevWhen, bCancelWhen ) oWizard:AddStep( cDescription + "2", bConstruction, bNextAction, bPrevWhen, bCancelWhen ) oWizard:AddStep( cDescription + "3", bConstruction, bNextAction, bPrevWhen, bCancelWhen ) // oWizard:AddStep( cDescription + "4", bConstruction, bNextAction, bPrevWhen, bCancelWhen ) oWizard:AddProcess( bProcess ) oWizard:SetTrialMode(.T.) //Default .F. // oWizard:SetExclusiveCompany(.F.) //Default .T. // oWizard:UsePlatformAccess(.F.) //Default .T. // oWizard:SetCountries( {"ARG", "BRA"} ) //Para permitir determinados países. // oWizard:SetCountries( {"ALL"} ) //Para permitir todos os países. // oWizard:SetErpCredentialsMode(.T.) //Default .F. oWizard:Activate() Return ```