ADS Local Server and simultaneous requests

Avatar de Usuario
ricardo arraes
Mensajes: 77
Registered for: 5 months
Brazil

Mensaje por ricardo arraes »

METHOD 1

Código: Seleccionar todo

METHOD method1(oController) CLASS WS    	
local hData := {=>},hResponse := {=>}
LOCAL cDirDbf:= AP_GetEnv( "PATH_DBF" ),cDirAds:= AP_GetEnv( "PATH_ADS" )
local aRows,  wncod, nConn:=0, cAdsSerial:="",nAdsConn:=0, lForcaAds:=.F.,nCons:=0
local hCookies := oController:oRequest:GetHeader( 'Authorization' ),nQte,nHandle, lError:=.F.,;
		  calias,,caliasflag,lOpen:=.T.,nTime,ctxt:="",oBDFlag, oQry, nT:=0, lcon:=.f.,hAds,caliast
   
 SET EPOCH TO 2000
	SET CENTURY ON
	SET DATE BRITISH
	
	hData:=oController:oRequest:PostAll()	
   
	oBDFlag:= TMySQl():New("MARIA","localhost","root","psw","flag_db",3306)

	caliasflag:= "AG"+hData['field1']+"01"
	nTime:=Seconds()			

	DO WHILE lOpen .AND. (Seconds()-nTime) < 30 

		oQry:=NIL

		oQry:=oBDFlag:Query("SELECT data, cflag, time FROM flag WHERE data='PARAM01' ",{Trans(Dtos(Date()),"@R 9999-99-99")})

		IF oQry = NIL .OR. oQry:Count()<=0  			

			IF (nT:=oBDFlag:Exec({"INSERT INTO flag (data, cflag, time) VALUES('PARAM01','PARAM02','PARAM03')"},;
						{{Trans(Dtos(Date()),"@R 9999-99-99"),caliasflag,Time()}})) < 0			
								
				lOpen:=.T.						
			ELSE 				

				WaitPeriod(100)

				DO WHILE WaitPeriod()
					
				ENDDO

				oQryV:=NIL
				oQryV:=oBDFlag:Query("SELECT cflag FROM flag WHERE data='PARAM01'",{Trans(Dtos(Date()),"@R 9999-99-99")})
				oQryV:First()

				IF oQryV:FieldGet("cflag")=caliasflag					
					lOpen:=.F.				
				ELSE 
					lOpen:=.T.														
				ENDIF
				
			ENDIF								

		ELSE
			oQry:First()
			
			IF (Seconds()-Secs(oQry:FieldGet("time")))>=20
				
				
				oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})	
				
				IF (oBDFlag:Exec({"INSERT INTO flag (data, cflag, time) VALUES('PARAM01','PARAM02','PARAM03')"},;
					{{Trans(Dtos(Date()),"@R 9999-99-99"),caliasflag,Time()}})) < 0			
					
					lOpen:=.T.
				ELSE 

					WaitPeriod(100)

					DO WHILE WaitPeriod()
				
					ENDDO

					oQryV:=NIL
					oQryV:=oBDFlag:Query("SELECT cflag FROM flag WHERE data='PARAM01'",{Trans(Dtos(Date()),"@R 9999-99-99")})
					oQryV:First()

					IF oQryV:FieldGet("cflag")=caliasflag
						lOpen:=.F.	
											
					ELSE 
						lOpen:=.T.

					ENDIF
					
				ENDIF	

			ELSE 				
				lOpen:=.T.
				
			ENDIF
		ENDIF	

		
		WaitPeriod(100)
	
		DO WHILE WaitPeriod()
				
		ENDDO					
		
	ENDDO

	IF lOpen
		
		hResponse[ 'success' ] := .F.
		oController:oResponse:SendJson( hResponse)			
		RETURN NIL
	
	ENDIF

	DO WHILE .T.

		IF AdsIsServerLoaded( Left(cDirAds,2), @nConn ) = ADS_REMOTE_SERVER
			AdsSetServerType(2)
			AdsSetFileType( 2 )
			AdsMgConnect( Left(cDirAds,2),,,@nConn )
			aTemp := AdsMgGetInstallInfo()
			cAdsSerial := IF(Len(aTemp)>=8,aTemp[8],"")
			aTemp := NIL
			nAdsConn := nConn			
			EXIT
		ELSEIF .NOT. lForcaAds
			RddRegister("ADS",1)
			RddSetDefault( "ADS" )
			AdsSetServerType(1)
			AdsSetFileType( 2 )
			
			lcon:=ADSConnect60( cDirDbf, 1, "", "",,@hAds)
			
			IF .NOT. lcon 
				hResponse[ 'success' ] := .F.
							
				oController:oResponse:SetHeader("Authorization",hCookies)
				oController:oResponse:SendJson( hResponse)
				RETURN NIL
			ENDIF
			
			EXIT
		ELSEIF n = 1
			n := 2			
		ELSE
			
			hResponse[ 'success' ] := .F.

			oController:oResponse:SetHeader("Authorization",hCookies)
			oController:oResponse:SendJson( hResponse )
			RETURN NIL
		ENDIF
	ENDDO

	caliast:= NewAlias("PS"+hData['field1'])

	
	nTry:=0
	DO WHILE nTry < 10				
		TRY 					

			USE (  cDirDbf+ "\TABLE.DBF" ) INDEX "TABLE" ALIAS caliast VIA "ADS" SHARED NEW
				
			IF NetErr()
				lError:=.T.
				hResponse[ 'success' ] := .F.

			ENDIF

			nTry:=10
		CATCH oError
		
			lError:=.T.
			nTry++
				
			WaitPeriod(100)
			DO WHILE WaitPeriod()

			ENDDO
		END 
	ENDDO

	IF lError
		oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})			
		
		hResponse[ 'success' ] := .F.
			
		oController:oResponse:SetHeader("Authorization",hCookies)
		oController:oResponse:SendJson( hResponse )	
		AdsDisconnect(hAds)
		RETURN NIL
	ENDIF 
	
	calias:=Alias(Select(caliast))	
	
	(calias)->(DbSetOrder(3))
	(calias)->(AdsSetAof("FIELD1 = ["+ hData['field1]+"] AND (FIELD2 <> [C] AND EMPTY(FIELD3)) AND DTOS(FIELD4) >= ["+Dtos(Date())+"]"))   	

	(calias)->(DbGoTop())
	DO WHILE .NOT. (calias)->(Eof())

		IF (calias)->field2 = hData['field2']
					
			hResponse['success'] 	:= .T.
			hResponse['resp'] 	:= (calias)->field1

			(calias)->(AdsClearAof())
			(calias)->(DbSetOrder(0))
			(calias)->(dbCloseArea())
			
			oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})			
						
			oController:oResponse:SetHeader("Authorization",hCookies)
			oController:oResponse:SendJson( hResponse )
			AdsDisconnect(hAds)
			RETURN NIL

		ENDIF

		n++		

		IF n >= 3

			hResponse[ 'success' ] := .F.
			hResponse['cod'] := "6"								

			(calias)->(AdsClearAof())
			(calias)->(DbSetOrder(0))
			(calias)->(dbCloseArea())

			oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})			
			
			oController:oResponse:SetHeader("Authorization",hCookies)
			oController:oResponse:SendJson( hResponse )
			AdsDisconnect(hAds)
			RETURN NIL
		ENDIF
	
		(calias)->(DbSkip())
		
	ENDDO
	
	(calias)->(AdsClearAof())
	
	(calias)->(DbSetOrder(1))
	(calias)->(dbGoBottom())
	IF (calias)->(Eof())
		wncod:="0001"		
	ELSE
		wncod:=(calias)->field1		
		DO WHILE (calias)->(DbSeek(wncod))
			wncod:=IncSequenc(wncod,4)    		
		ENDDO
	ENDIF	

	nQte:=Seconds()   
	nLOop:=.T.
		
	(calias)->(DbSetOrder(2))
	(calias)->( DbSeek(hData['field2']+Dtos(Ctod(hData['field3']))+StrTran(hData['field4'],":")) )
			
	DO WHILE .NOT. (calias)->(Eof()) .AND. (calias)->field3=Ctod(hData['field3']) .AND. (calias)->field5=hData['field5'] .AND. (calias)->hora=StrTran(hData['field6'],":")
		
		IF (calias)->field7="N" 

			hResponse['cod']     :="2"
			hResponse['success'] := .T.       			

			(calias)->(DbSetOrder(0))
			(calias)->(dbCloseArea())

			oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})			
			
			oController:oResponse:SetHeader("Authorization",hCookies)
			oController:oResponse:SendJson( hResponse )
			AdsDisconnect(hAds)
			RETURN NIL
		ENDIF			

		(calias)->(DbSkip())
				
	ENDDO		
	
	(calias)->(DbSetOrder(0))
	(calias)->(dbAppend())
	IF  NetErr()
					
		nLoop:=.F.
		hResponse[ 'success' ] := .F.
		
	ELSE 
		
		if (calias)->(DbRLock())
			
			(calias)->field1   := wncod
			(calias)->field2     := Ctod(hData[ 'field2' ])
			(calias)->(DbUnLock())
			
			hResponse[ 'success' ] 	:= .T.			
			
		ENDIF
	ENDIF
	
	(calias)->(dbCloseArea())	

	oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})			
	
	oController:oResponse:SetHeader("Authorization",hCookies)
	oController:oResponse:SendJson( hResponse )
	AdsDisconnect(hAds)
	 
RETURN nil

METHOD 2

Código: Seleccionar todo

METHOD carregarDados(oController) CLASS WS 
LOCAL hData:={=>},hResponse:={=>},hReg:={=>},hRegCrypt:={=>},cDirDbf:= AP_GetEnv( "PATH_DBF" ),cDirAds:= AP_GetEnv( "PATH_ADS" ),;
	  nConn:=0, cAdsSerial:="",nAdsConn:=0, lForcaAds:=.F.,nCons:=0,cUrl:= AP_GetEnv("WSCT")+"updbase", hToken,hCookies,lsend:=.f. ,;
	  hRegAux:={=>},wcmed:="",wnomemed:="",wespdesc:="",lsite:=.F.,;
	  calias,calias1,calias2,calias3,calias4,calias11,calias22,calias33,calias44,caliasflag,nTime,;
	  lOpen:=.T.,cSalt:="",nChar:=0,oBDFlag,oQry,oQryV,hAds, lcon:=.F.

	hData:=oController:oRequest:PostAll()

	FOR N=1 TO 2
		nChar:=HB_RandomInt( 65, 90 )
		cSalt+=Chr(nChar)
	NEXT N

	caliasflag:= StrTran(Time(),":")+cSalt+"01"
	nTime:=Seconds()			
	
	oBDFlag:= TMySQl():New("MARIA","localhost","root","psw","flag_db",3306)

	DO WHILE lOpen .AND. (Seconds()-nTime) < 30 

		oQry:=NIL

		oQry:=oBDFlag:Query("SELECT data, cflag, time FROM flag WHERE data='PARAM01'",{Trans(Dtos(Date()),"@R 9999-99-99")})

		IF oQry = NIL .OR. oQry:Count()<=0  			

			IF (nT:=oBDFlag:Exec({"INSERT INTO flag (data, cflag, time) VALUES('PARAM01','PARAM02','PARAM03')"},;
						{{Trans(Dtos(Date()),"@R 9999-99-99"),caliasflag,Time()}})) < 0			
								
				lOpen:=.T.						
			ELSE 				

				WaitPeriod(100)

				DO WHILE WaitPeriod()
					
				ENDDO

				oQryV:=NIL
				oQryV:=oBDFlag:Query("SELECT cflag FROM flag WHERE data='PARAM01'",{Trans(Dtos(Date()),"@R 9999-99-99")})
				oQryV:First()

				IF oQryV:FieldGet("cflag")=caliasflag					
					lOpen:=.F.				
				ELSE 
					lOpen:=.T.														
				ENDIF
				
			ENDIF								

		ELSE
			oQry:First()
			
			IF (Seconds()-Secs(oQry:FieldGet("time")))>=20
				
				
				oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})	
				
				IF (oBDFlag:Exec({"INSERT INTO flag (data, cflag, time) VALUES('PARAM01','PARAM02','PARAM03')"},;
					{{Trans(Dtos(Date()),"@R 9999-99-99"),caliasflag,Time()}})) < 0			
					
					lOpen:=.T.
				ELSE 

					WaitPeriod(100)

					DO WHILE WaitPeriod()
				
					ENDDO

					oQryV:=NIL
					oQryV:=oBDFlag:Query("SELECT cflag FROM flag WHERE data='PARAM01'",{Trans(Dtos(Date()),"@R 9999-99-99")})
					oQryV:First()

					IF oQryV:FieldGet("cflag")=caliasflag
						lOpen:=.F.	
											
					ELSE 
						lOpen:=.T.

					ENDIF
					
				ENDIF	

			ELSE 				
				lOpen:=.T.
				
			ENDIF
		ENDIF	

		
		WaitPeriod(100)
	
		DO WHILE WaitPeriod()
				
		ENDDO					
		
	ENDDO

	IF lOpen
		hResponse[ 'success' ] := .T.

		oController:oResponse:SendJson( hResponse )	
		RETURN NIL
	
	ENDIF

	DO WHILE .T.

		IF AdsIsServerLoaded( Left(cDirAds,2), @nConn ) = ADS_REMOTE_SERVER
			
			AdsSetServerType(2)
			AdsSetFileType( 2 )
			AdsMgConnect( Left(cDirAds,2),,,@nConn )
			aTemp := AdsMgGetInstallInfo()
			cAdsSerial := IF(Len(aTemp)>=8,aTemp[8],"")
			aTemp := NIL
			nAdsConn := nConn
			
			EXIT

		ELSEIF .NOT. lForcaAds
			RddRegister("ADS",1)
		 	RddSetDefault( "ADS" )
			AdsSetServerType(1)
			AdsSetFileType( 2 )
			lcon:=ADSConnect60( cDirDbf, 1, "", "",,@hAds)
			
			EXIT

		ELSEIF n = 1
			n := 2
		ELSE
			//NAO FOI ENCONTRADO O ADS
			hResponse[ 'success' ] := .F.
				
			oController:oResponse:SendJson( hResponse )
			RETURN NIL
		ENDIF
		
	ENDDO	

									
			IF hData['op'] # "I"
				hReg['success'] 	:= .T.
				hReg['op'] 	:= "R"

				lsend:=.t.
			ELSE				
				
				calias11:=NewAlias("HC"+StrTran(Time(),":"))				
				
				calias22:=NewAlias("EC"+StrTran(Time(),":"))				
				
				calias33:= NewAlias("DC"+StrTran(Time(),":"))				
								
				calias44:= NewAlias("MC"+StrTran(Time(),":"))			
		
		DO CASE
			
			CASE X=X					
				TRY 
					USE (  cDirDbf+ "\TABLE1.DBF" ) INDEX "TABLE1"   ALIAS calias11 VIA "ADS" SHARED NEW
					IF NetErr()
						lsend:=.F.
						QUIT
					ENDIF
				CATCH oError 
										
					lsend:=.F.
					QUIT
				END 

				calias1:=Alias(Select(calias11))
								
				(calias1)->(DbSetOrder(1))	
							
				IF (calias1)->(dbSeek(hData['reg'])) 
					
					wdesc:=(calias1)->field1
					lsite:=(calias1)->field2

					(calias1)->(dbsetorder(0))
					(calias1)->(dbCloseArea())
					
					hReg['cod'] 	:= 'cod'	
														
					IF lsite 
						hReg['op'] 	:= hData['op']	
						hReg['teste']:={}
					
						TRY 
							USE (  cDirDbf+ "\TABLE2.DBF" ) INDEX "TABLE2"   ALIAS calias22 VIA "ADS" SHARED NEW				
							IF NetErr()
								lsend:=.F.
								QUIT
							ENDIF
						CATCH oError 
						
							lsend:=.F.
							QUIT
						END 

						calias2:= Alias(Select(calias22))
																
						(calias2)->(DbSetOrder(2))
						
						IF (calias2)->(dbSeek(hData['reg']))

							TRY 
								USE (  cDirDbf+ "\TABLE3.DBF" ) INDEX "TABLE3"  ALIAS calias33 VIA "ADS" SHARED NEW			
								IF NetErr()
									lsend:=.F.
									QUIT
								ENDIF

								calias3:=Alias(Select(calias33))

								USE (  cDirDbf+ "\TABLE4.DBF" ) INDEX "TABLE4"  ALIAS calias44 VIA "ADS" SHARED NEW
								IF NetErr()
									lsend:=.F.
									QUIT
								ENDIF
								
								calias4:=Alias(Select(calias4))
							CATCH oError 
								
								lsend:=.F.
								QUIT
							END 
								
							(calias3)->(DbSetOrder(1))
							(calias4)->(DbSetOrder(1))

							DO WHILE (calias3)->cod=hData['reg'] .AND. .NOT. (calias3)->(Eof())
							
								hRegAux:={=>}
								
								IF (calias4)->(dbSeek((calias3)->cod)) .AND. (calias4)->field3 # "I" .AND. (calias4)->(dbSeek((calias3)->cod))
																											
									hRegAux['teste1'] 		:= (calias4)->test1
									hRegAux['teste2'] 		:= (calias4)->test2

									hRegAux['test3']:={}
									hItem:={=>}

									hItem['item1'] 		:= (calias4)->item1
									hItem['item2'] 		:= (calias4)->item2

									aadd( hRegAux['test3'], hItem )

									hRegAux['test4']:={}			
																							
									DO WHILE (calias3)->cod=(calias3)->cod .AND. .NOT. (calias3)->(Eof())									
									
										IF (calias3)->interval > 0 
											hItem:={=>}

											hItem['cod1'] 		:= (calias3)->cod2
											hItem['cod2'] 		:= (calias3)->cod1
									
											aadd( hRegAux['test4'], hItem )
										ENDIF

										(calias3)->(dbSkip())
									ENDDO

									IF Len(hRegAux['test4'])<=0
										(calias3)->(DbSkip())
										LOOP 
									ELSE 
										Aadd(hReg['test2'],hRegAux)
									ENDIF
																										
								ENDIF
								
								(calias3)->(dbSkip())
							ENDDO
								
							(calias2)->(DbSetOrder(0))
							(calias2)->(dbCloseArea())

							(calias3)->(DbSetOrder(0))
							(calias3)->(dbCloseArea())

							(calias4)->(DbSetOrder(0))
							(calias4)->(dbCloseArea())								

							IF Len(hReg['test2'])<=0
								lsend:=.F.							
							ELSE 
								lsend:=.T.
							ENDIF

						
						ELSE	
							(calias3)->(DbSetOrder(0))
							(calias3)->(dbCloseArea())
							lsend:=.F.						
						ENDIF
						
					ELSE 
						hReg['op'] 	:= "E"					
						lsend:=.t.
					ENDIF
									
					
				ELSE 
					(calias1)->(DbSetOrder(0))
					(calias1)->(dbCloseArea())
					lsend:=.F.
				ENDIF
			ENDIF
			
		CASE ...
		
		...
		
					
	END CASE
	AdsDisconnect(hAds)

	IF lsend
		
		hToken := { 'in' => time(), 'teste1' => '000001', 'teste2' => 'WS' }                        
		hCookies := oController:oMiddleware:SetAutenticationToken( hToken ) 
				
		hResponse := sendHttp("POST",cUrl,hCookies,hReg)	
		hResponse['cod']:=1
		
	ELSE 
		hResponse['success']:=.F.

	ENDIF	
								
	oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})				
	
	oController:oResponse:SendJson(hResponse)

RETURN NIL

*Don't pay much attention to the code inside loops and processing blocks, I changed the variable names, so it's probably not making a lot of sense... I want you guys to pay attention to the structure of the methods and the blocks I mentioned in the last post. This is just to illustrate better what I told you in the last post
The work always comes before the belief

Avatar de Usuario
ricardo arraes
Mensajes: 77
Registered for: 5 months
Brazil

Mensaje por ricardo arraes »

ricardo arraes escribió: Mié Mar 31, 2021 1:31 am METHOD 1

Código: Seleccionar todo

METHOD method1(oController) CLASS WS    	
local hData := {=>},hResponse := {=>}
LOCAL cDirDbf:= AP_GetEnv( "PATH_DBF" ),cDirAds:= AP_GetEnv( "PATH_ADS" )
local aRows,  wncod, nConn:=0, cAdsSerial:="",nAdsConn:=0, lForcaAds:=.F.,nCons:=0
local hCookies := oController:oRequest:GetHeader( 'Authorization' ),nQte,nHandle, lError:=.F.,;
		  calias,,caliasflag,lOpen:=.T.,nTime,ctxt:="",oBDFlag, oQry, nT:=0, lcon:=.f.,hAds,caliast
   
 SET EPOCH TO 2000
	SET CENTURY ON
	SET DATE BRITISH
	
	hData:=oController:oRequest:PostAll()	
   
	oBDFlag:= TMySQl():New("MARIA","localhost","root","psw","flag_db",3306)

	caliasflag:= "AG"+hData['field1']+"01"
	nTime:=Seconds()			

	DO WHILE lOpen .AND. (Seconds()-nTime) < 30 

		oQry:=NIL

		oQry:=oBDFlag:Query("SELECT data, cflag, time FROM flag WHERE data='PARAM01' ",{Trans(Dtos(Date()),"@R 9999-99-99")})

		IF oQry = NIL .OR. oQry:Count()<=0  			

			IF (nT:=oBDFlag:Exec({"INSERT INTO flag (data, cflag, time) VALUES('PARAM01','PARAM02','PARAM03')"},;
						{{Trans(Dtos(Date()),"@R 9999-99-99"),caliasflag,Time()}})) < 0			
								
				lOpen:=.T.						
			ELSE 				

				WaitPeriod(100)

				DO WHILE WaitPeriod()
					
				ENDDO

				oQryV:=NIL
				oQryV:=oBDFlag:Query("SELECT cflag FROM flag WHERE data='PARAM01'",{Trans(Dtos(Date()),"@R 9999-99-99")})
				oQryV:First()

				IF oQryV:FieldGet("cflag")=caliasflag					
					lOpen:=.F.				
				ELSE 
					lOpen:=.T.														
				ENDIF
				
			ENDIF								

		ELSE
			oQry:First()
			
			IF (Seconds()-Secs(oQry:FieldGet("time")))>=20
				
				
				oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})	
				
				IF (oBDFlag:Exec({"INSERT INTO flag (data, cflag, time) VALUES('PARAM01','PARAM02','PARAM03')"},;
					{{Trans(Dtos(Date()),"@R 9999-99-99"),caliasflag,Time()}})) < 0			
					
					lOpen:=.T.
				ELSE 

					WaitPeriod(100)

					DO WHILE WaitPeriod()
				
					ENDDO

					oQryV:=NIL
					oQryV:=oBDFlag:Query("SELECT cflag FROM flag WHERE data='PARAM01'",{Trans(Dtos(Date()),"@R 9999-99-99")})
					oQryV:First()

					IF oQryV:FieldGet("cflag")=caliasflag
						lOpen:=.F.	
											
					ELSE 
						lOpen:=.T.

					ENDIF
					
				ENDIF	

			ELSE 				
				lOpen:=.T.
				
			ENDIF
		ENDIF	

		
		WaitPeriod(100)
	
		DO WHILE WaitPeriod()
				
		ENDDO					
		
	ENDDO

	IF lOpen
		
		hResponse[ 'success' ] := .F.
		oController:oResponse:SendJson( hResponse)			
		RETURN NIL
	
	ENDIF

	DO WHILE .T.

		IF AdsIsServerLoaded( Left(cDirAds,2), @nConn ) = ADS_REMOTE_SERVER
			AdsSetServerType(2)
			AdsSetFileType( 2 )
			AdsMgConnect( Left(cDirAds,2),,,@nConn )
			aTemp := AdsMgGetInstallInfo()
			cAdsSerial := IF(Len(aTemp)>=8,aTemp[8],"")
			aTemp := NIL
			nAdsConn := nConn			
			EXIT
		ELSEIF .NOT. lForcaAds
			RddRegister("ADS",1)
			RddSetDefault( "ADS" )
			AdsSetServerType(1)
			AdsSetFileType( 2 )
			
			lcon:=ADSConnect60( cDirDbf, 1, "", "",,@hAds)
			
			IF .NOT. lcon 
				hResponse[ 'success' ] := .F.
							
				oController:oResponse:SetHeader("Authorization",hCookies)
				oController:oResponse:SendJson( hResponse)
				RETURN NIL
			ENDIF
			
			EXIT
		ELSEIF n = 1
			n := 2			
		ELSE
			
			hResponse[ 'success' ] := .F.

			oController:oResponse:SetHeader("Authorization",hCookies)
			oController:oResponse:SendJson( hResponse )
			RETURN NIL
		ENDIF
	ENDDO

	caliast:= NewAlias("PS"+hData['field1'])

	
	nTry:=0
	DO WHILE nTry < 10				
		TRY 					

			USE (  cDirDbf+ "\TABLE.DBF" ) INDEX "TABLE" ALIAS caliast VIA "ADS" SHARED NEW
				
			IF NetErr()
				lError:=.T.
				hResponse[ 'success' ] := .F.

			ENDIF

			nTry:=10
		CATCH oError
		
			lError:=.T.
			nTry++
				
			WaitPeriod(100)
			DO WHILE WaitPeriod()

			ENDDO
		END 
	ENDDO

	IF lError
		oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})			
		
		hResponse[ 'success' ] := .F.
			
		oController:oResponse:SetHeader("Authorization",hCookies)
		oController:oResponse:SendJson( hResponse )	
		AdsDisconnect(hAds)
		RETURN NIL
	ENDIF 
	
	calias:=Alias(Select(caliast))	
	
	(calias)->(DbSetOrder(3))
	(calias)->(AdsSetAof("FIELD1 = ["+ hData['field1]+"] AND (FIELD2 <> [C] AND EMPTY(FIELD3)) AND DTOS(FIELD4) >= ["+Dtos(Date())+"]"))   	

	(calias)->(DbGoTop())
	DO WHILE .NOT. (calias)->(Eof())

		IF (calias)->field2 = hData['field2']
					
			hResponse['success'] 	:= .T.
			hResponse['resp'] 	:= (calias)->field1

			(calias)->(AdsClearAof())
			(calias)->(DbSetOrder(0))
			(calias)->(dbCloseArea())
			
			oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})			
						
			oController:oResponse:SetHeader("Authorization",hCookies)
			oController:oResponse:SendJson( hResponse )
			AdsDisconnect(hAds)
			RETURN NIL

		ENDIF

		n++		

		IF n >= 3

			hResponse[ 'success' ] := .F.
			hResponse['cod'] := "6"								

			(calias)->(AdsClearAof())
			(calias)->(DbSetOrder(0))
			(calias)->(dbCloseArea())

			oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})			
			
			oController:oResponse:SetHeader("Authorization",hCookies)
			oController:oResponse:SendJson( hResponse )
			AdsDisconnect(hAds)
			RETURN NIL
		ENDIF
	
		(calias)->(DbSkip())
		
	ENDDO
	
	(calias)->(AdsClearAof())
	
	(calias)->(DbSetOrder(1))
	(calias)->(dbGoBottom())
	IF (calias)->(Eof())
		wncod:="0001"		
	ELSE
		wncod:=(calias)->field1		
		DO WHILE (calias)->(DbSeek(wncod))
			wncod:=IncSequenc(wncod,4)    		
		ENDDO
	ENDIF	

	nQte:=Seconds()   
	nLOop:=.T.
		
	(calias)->(DbSetOrder(2))
	(calias)->( DbSeek(hData['field2']+Dtos(Ctod(hData['field3']))+StrTran(hData['field4'],":")) )
			
	DO WHILE .NOT. (calias)->(Eof()) .AND. (calias)->field3=Ctod(hData['field3']) .AND. (calias)->field5=hData['field5'] .AND. (calias)->hora=StrTran(hData['field6'],":")
		
		IF (calias)->field7="N" 

			hResponse['cod']     :="2"
			hResponse['success'] := .T.       			

			(calias)->(DbSetOrder(0))
			(calias)->(dbCloseArea())

			oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})			
			
			oController:oResponse:SetHeader("Authorization",hCookies)
			oController:oResponse:SendJson( hResponse )
			AdsDisconnect(hAds)
			RETURN NIL
		ENDIF			

		(calias)->(DbSkip())
				
	ENDDO		
	
	(calias)->(DbSetOrder(0))
	(calias)->(dbAppend())
	IF  NetErr()
					
		nLoop:=.F.
		hResponse[ 'success' ] := .F.
		
	ELSE 
		
		if (calias)->(DbRLock())
			
			(calias)->field1   := wncod
			(calias)->field2     := Ctod(hData[ 'field2' ])
			(calias)->(DbUnLock())
			
			hResponse[ 'success' ] 	:= .T.			
			
		ENDIF
	ENDIF
	
	(calias)->(dbCloseArea())	

	oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})			
	
	oController:oResponse:SetHeader("Authorization",hCookies)
	oController:oResponse:SendJson( hResponse )
	AdsDisconnect(hAds)
	 
RETURN nil

METHOD 2

Código: Seleccionar todo

METHOD method2(oController) CLASS WS 
LOCAL hData:={=>},hResponse:={=>},hReg:={=>},hRegCrypt:={=>},cDirDbf:= AP_GetEnv( "PATH_DBF" ),cDirAds:= AP_GetEnv( "PATH_ADS" ),;
	  nConn:=0, cAdsSerial:="",nAdsConn:=0, lForcaAds:=.F.,nCons:=0,cUrl:= AP_GetEnv("WSCT")+"updbase", hToken,hCookies,lsend:=.f. ,;
	  hRegAux:={=>},wcmed:="",wnomemed:="",wespdesc:="",lsite:=.F.,;
	  calias,calias1,calias2,calias3,calias4,calias11,calias22,calias33,calias44,caliasflag,nTime,;
	  lOpen:=.T.,cSalt:="",nChar:=0,oBDFlag,oQry,oQryV,hAds, lcon:=.F.

	hData:=oController:oRequest:PostAll()

	FOR N=1 TO 2
		nChar:=HB_RandomInt( 65, 90 )
		cSalt+=Chr(nChar)
	NEXT N

	caliasflag:= StrTran(Time(),":")+cSalt+"01"
	nTime:=Seconds()			
	
	oBDFlag:= TMySQl():New("MARIA","localhost","root","psw","flag_db",3306)

	DO WHILE lOpen .AND. (Seconds()-nTime) < 30 

		oQry:=NIL

		oQry:=oBDFlag:Query("SELECT data, cflag, time FROM flag WHERE data='PARAM01'",{Trans(Dtos(Date()),"@R 9999-99-99")})

		IF oQry = NIL .OR. oQry:Count()<=0  			

			IF (nT:=oBDFlag:Exec({"INSERT INTO flag (data, cflag, time) VALUES('PARAM01','PARAM02','PARAM03')"},;
						{{Trans(Dtos(Date()),"@R 9999-99-99"),caliasflag,Time()}})) < 0			
								
				lOpen:=.T.						
			ELSE 				

				WaitPeriod(100)

				DO WHILE WaitPeriod()
					
				ENDDO

				oQryV:=NIL
				oQryV:=oBDFlag:Query("SELECT cflag FROM flag WHERE data='PARAM01'",{Trans(Dtos(Date()),"@R 9999-99-99")})
				oQryV:First()

				IF oQryV:FieldGet("cflag")=caliasflag					
					lOpen:=.F.				
				ELSE 
					lOpen:=.T.														
				ENDIF
				
			ENDIF								

		ELSE
			oQry:First()
			
			IF (Seconds()-Secs(oQry:FieldGet("time")))>=20
				
				
				oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})	
				
				IF (oBDFlag:Exec({"INSERT INTO flag (data, cflag, time) VALUES('PARAM01','PARAM02','PARAM03')"},;
					{{Trans(Dtos(Date()),"@R 9999-99-99"),caliasflag,Time()}})) < 0			
					
					lOpen:=.T.
				ELSE 

					WaitPeriod(100)

					DO WHILE WaitPeriod()
				
					ENDDO

					oQryV:=NIL
					oQryV:=oBDFlag:Query("SELECT cflag FROM flag WHERE data='PARAM01'",{Trans(Dtos(Date()),"@R 9999-99-99")})
					oQryV:First()

					IF oQryV:FieldGet("cflag")=caliasflag
						lOpen:=.F.	
											
					ELSE 
						lOpen:=.T.

					ENDIF
					
				ENDIF	

			ELSE 				
				lOpen:=.T.
				
			ENDIF
		ENDIF	

		
		WaitPeriod(100)
	
		DO WHILE WaitPeriod()
				
		ENDDO					
		
	ENDDO

	IF lOpen
		hResponse[ 'success' ] := .T.

		oController:oResponse:SendJson( hResponse )	
		RETURN NIL
	
	ENDIF

	DO WHILE .T.

		IF AdsIsServerLoaded( Left(cDirAds,2), @nConn ) = ADS_REMOTE_SERVER
			
			AdsSetServerType(2)
			AdsSetFileType( 2 )
			AdsMgConnect( Left(cDirAds,2),,,@nConn )
			aTemp := AdsMgGetInstallInfo()
			cAdsSerial := IF(Len(aTemp)>=8,aTemp[8],"")
			aTemp := NIL
			nAdsConn := nConn
			
			EXIT

		ELSEIF .NOT. lForcaAds
			RddRegister("ADS",1)
		 	RddSetDefault( "ADS" )
			AdsSetServerType(1)
			AdsSetFileType( 2 )
			lcon:=ADSConnect60( cDirDbf, 1, "", "",,@hAds)
			
			EXIT

		ELSEIF n = 1
			n := 2
		ELSE
			//NAO FOI ENCONTRADO O ADS
			hResponse[ 'success' ] := .F.
				
			oController:oResponse:SendJson( hResponse )
			RETURN NIL
		ENDIF
		
	ENDDO	

									
			IF hData['op'] # "I"
				hReg['success'] 	:= .T.
				hReg['op'] 	:= "R"

				lsend:=.t.
			ELSE				
				
				calias11:=NewAlias("HC"+StrTran(Time(),":"))				
				
				calias22:=NewAlias("EC"+StrTran(Time(),":"))				
				
				calias33:= NewAlias("DC"+StrTran(Time(),":"))				
								
				calias44:= NewAlias("MC"+StrTran(Time(),":"))			
		
		DO CASE
			
			CASE X=X					
				TRY 
					USE (  cDirDbf+ "\TABLE1.DBF" ) INDEX "TABLE1"   ALIAS calias11 VIA "ADS" SHARED NEW
					IF NetErr()
						lsend:=.F.
						QUIT
					ENDIF
				CATCH oError 
										
					lsend:=.F.
					QUIT
				END 

				calias1:=Alias(Select(calias11))
								
				(calias1)->(DbSetOrder(1))	
							
				IF (calias1)->(dbSeek(hData['reg'])) 
					
					wdesc:=(calias1)->field1
					lsite:=(calias1)->field2

					(calias1)->(dbsetorder(0))
					(calias1)->(dbCloseArea())
					
					hReg['cod'] 	:= 'cod'	
														
					IF lsite 
						hReg['op'] 	:= hData['op']	
						hReg['teste']:={}
					
						TRY 
							USE (  cDirDbf+ "\TABLE2.DBF" ) INDEX "TABLE2"   ALIAS calias22 VIA "ADS" SHARED NEW				
							IF NetErr()
								lsend:=.F.
								QUIT
							ENDIF
						CATCH oError 
						
							lsend:=.F.
							QUIT
						END 

						calias2:= Alias(Select(calias22))
																
						(calias2)->(DbSetOrder(2))
						
						IF (calias2)->(dbSeek(hData['reg']))

							TRY 
								USE (  cDirDbf+ "\TABLE3.DBF" ) INDEX "TABLE3"  ALIAS calias33 VIA "ADS" SHARED NEW			
								IF NetErr()
									lsend:=.F.
									QUIT
								ENDIF

								calias3:=Alias(Select(calias33))

								USE (  cDirDbf+ "\TABLE4.DBF" ) INDEX "TABLE4"  ALIAS calias44 VIA "ADS" SHARED NEW
								IF NetErr()
									lsend:=.F.
									QUIT
								ENDIF
								
								calias4:=Alias(Select(calias4))
							CATCH oError 
								
								lsend:=.F.
								QUIT
							END 
								
							(calias3)->(DbSetOrder(1))
							(calias4)->(DbSetOrder(1))

							DO WHILE (calias3)->cod=hData['reg'] .AND. .NOT. (calias3)->(Eof())
							
								hRegAux:={=>}
								
								IF (calias4)->(dbSeek((calias3)->cod)) .AND. (calias4)->field3 # "I" .AND. (calias4)->(dbSeek((calias3)->cod))
																											
									hRegAux['teste1'] 		:= (calias4)->test1
									hRegAux['teste2'] 		:= (calias4)->test2

									hRegAux['test3']:={}
									hItem:={=>}

									hItem['item1'] 		:= (calias4)->item1
									hItem['item2'] 		:= (calias4)->item2

									aadd( hRegAux['test3'], hItem )

									hRegAux['test4']:={}			
																							
									DO WHILE (calias3)->cod=(calias3)->cod .AND. .NOT. (calias3)->(Eof())									
									
										IF (calias3)->interval > 0 
											hItem:={=>}

											hItem['cod1'] 		:= (calias3)->cod2
											hItem['cod2'] 		:= (calias3)->cod1
									
											aadd( hRegAux['test4'], hItem )
										ENDIF

										(calias3)->(dbSkip())
									ENDDO

									IF Len(hRegAux['test4'])<=0
										(calias3)->(DbSkip())
										LOOP 
									ELSE 
										Aadd(hReg['test2'],hRegAux)
									ENDIF
																										
								ENDIF
								
								(calias3)->(dbSkip())
							ENDDO
								
							(calias2)->(DbSetOrder(0))
							(calias2)->(dbCloseArea())

							(calias3)->(DbSetOrder(0))
							(calias3)->(dbCloseArea())

							(calias4)->(DbSetOrder(0))
							(calias4)->(dbCloseArea())								

							IF Len(hReg['test2'])<=0
								lsend:=.F.							
							ELSE 
								lsend:=.T.
							ENDIF

						
						ELSE	
							(calias3)->(DbSetOrder(0))
							(calias3)->(dbCloseArea())
							lsend:=.F.						
						ENDIF
						
					ELSE 
						hReg['op'] 	:= "E"					
						lsend:=.t.
					ENDIF
									
					
				ELSE 
					(calias1)->(DbSetOrder(0))
					(calias1)->(dbCloseArea())
					lsend:=.F.
				ENDIF
			ENDIF
			
		CASE ...
		
		...
		
					
	END CASE
	AdsDisconnect(hAds)

	IF lsend
		
		hToken := { 'in' => time(), 'teste1' => '000001', 'teste2' => 'WS' }                        
		hCookies := oController:oMiddleware:SetAutenticationToken( hToken ) 
				
		hResponse := sendHttp("POST",cUrl,hCookies,hReg)	
		hResponse['cod']:=1
		
	ELSE 
		hResponse['success']:=.F.

	ENDIF	
								
	oBDFlag:Exec({"DELETE FROM flag WHERE data='PARAM01'"},{{Trans(Dtos(Date()),"@R 9999-99-99")}})				
	
	oController:oResponse:SendJson(hResponse)

RETURN NIL

*Don't pay much attention to the code inside loops and processing blocks, I changed the variable names, so it's probably not making a lot of sense... I want you guys to pay attention to the structure of the methods and the blocks I mentioned in the last post. This is just to illustrate better what I told you in the last post
The work always comes before the belief

Avatar de Usuario
ricardo arraes
Mensajes: 77
Registered for: 5 months
Brazil

Mensaje por ricardo arraes »

UPDATE:

everything worked well with ADS Remote Server!
The work always comes before the belief

ramirezosvaldo
Mensajes: 27
Registered for: 5 months
Mexico

Mensaje por ramirezosvaldo »

Hola Ricardo

En pocas palabras, no procesas ningún otra petición hasta que terminal la petición actual ?

Saludos
Osvaldo Ramirez

Avatar de Usuario
charly
Mensajes: 76
Registered for: 5 months

Mensaje por charly »

Ricardo,

Me he mirado por encima lo que haces. en resumen es un semaforo básico, pero piensa que si un proceso te "casca", la cola de peticiones te van a llegar a la luna...

C.
Salutacions, saludos, regards.
Charly

"...programar es fácil, hacer programas es difícil..."

https://modharbour.app
https://modharbour.app/compass
https://forum.modharbour.app

Avatar de Usuario
ricardo arraes
Mensajes: 77
Registered for: 5 months
Brazil

Mensaje por ricardo arraes »

Hey Osvaldo and Charly!

Basically, yes, there's a flag which is controlling the whole "traffic" inside the application...

the first request to get to the application will be processed while the others will wait for it, for 30 secs AT MOST (in my real application I already decreased this timeout to 7 secs) as you can see here in the DO WHILE CLAUSE condition:

Código: Seleccionar todo


DO WHILE lOpen .AND. (Seconds()-nTime) < 30 

If any request get stuck, the flag will be unlocked as soon as the timeout expires and the next request will take place.
*the timeout starts to count when my webservice receives the request from the website and the whole data processing is done locally in the webservice. this means that the time the request takes to go from the website to the webservice is ignored and it doesn't count for the timeout. The time the response takes to go fom the webservice to the application is, also, ignored. It only counts the local data processing time.

I decided, in my real application, to use 7 secs as the timeout because:

1- it is a "acceptable" time for the user to wait (it's not a HUGE sacrifice waiting for it) and even if there's some connection problems adding more seconds, it won't be a huge problem...

2- testing with a huge amount of information, and analyzing exhaustively many scenarios I can said that with an optimized database (which is the case here), in the WORST CASE, the time a request can take to complete the whole processing is approximately 5 seconds (we are talking about the processing time, not the . So, with 7 seconds as the timeout, I still got a safety margin. But when we are talking about a regular daily basis, with medium and best cases, a request is taking less than 2 seconds to process (in fact, WAY less).
The work always comes before the belief

Avatar de Usuario
ricardo arraes
Mensajes: 77
Registered for: 5 months
Brazil

Mensaje por ricardo arraes »

Just for the record...

There are many other methods in my application that deal with the concurrency without a single problem.

These particular methods that I showed are opening DBF files throough ADS Local Server, and as I explained earlier, I was having some troubles when opening the same table at the same exact time by many users, that's why I created this flag control.

When it comes to MySQL and MariaDB, even when it comes to requests that doesn't require any database manipulation, there's no problem at all with concurrency
The work always comes before the belief

ramirezosvaldo
Mensajes: 27
Registered for: 5 months
Mexico

Mensaje por ramirezosvaldo »

Excelente Ricardo

Creo que tu solución nos servirá a mas de uno;
Sea o no sea perfecta y que posiblemente exista otro tipo de solución a nivel mod.

Gracias mi estimado por el esfuerzo de pasmar el problema y la solución.

Saludos
Osvaldo Ramirez

Avatar de Usuario
charly
Mensajes: 76
Registered for: 5 months

Mensaje por charly »

Hola,

lo q no entiendo es q solo pasa en local y no en el server?. :roll:
Salutacions, saludos, regards.
Charly

"...programar es fácil, hacer programas es difícil..."

https://modharbour.app
https://modharbour.app/compass
https://forum.modharbour.app

wilsongamboa
Mensajes: 7
Registered for: 5 months
Ecuador

Mensaje por wilsongamboa »

Ricardo buenas tardes
has pensado talvez en separar la parte de manipulación de ADS utilizando HBNETIO ?
me parece que con eso resolverías los problemas ya que en HBNETIO tu programas como si estuvieras en desktop
saludos
Wilson

Responder