EDX in QlikView: What are, what for and how it does ?

In several places in QlikView documentation are references to EDX. There are many entries in the community of QlikView and others bolgs, but for someone new to the topic is a little complex clarified the concepts necessary to work with this functionality.
First I will give some definitions based on my own experience of using it.
What is an EDX? In short clear and simple  words is a task that is scheduled for QlikView server side (through one of the two consoles QlikView Server) to be fired to an external event. This external event is neither more nor less than programmatic invocation of the service using HTTP Post.
Now when we say «a task from the server side» what we are talking about exactly? Well, it depends on whether your server is licensed to Publisher or not.
If you do not have Publisher the only job that will run will be the load of one (or more) qvw’s scheduled server side to be fired as an external event, such as the click of a button on the application by a user .
On the other hand if you have Publisher additionally the above functionallity  the task can be anything that can be executed by SO: eg a isql command to modify a SQL Server database, SendMail program or a command type «cmd» with any operating system command: copy, delete, ftp, etc..
For those who do not have Publisher is a comfort and alternative pathway that involves the qvw tell which is recharged with a script and within it there are one or more instructions EXECUTE with which we can run anything, such as display   QlikView.HLP such instruction (something old ….):

  • Execute C: \ MSOffice95 \ Excel \ Excel.exe;
  • Execute winword macro.doc;
  • Execute cmd.exe / C C: \ BatFiles \ Log.bat

The example I will show and especially the screens are a QVS (QlikView Server) with Publisher, but also applicable to a server that does not.
First we create the server-side task to recharge on-demand programmatically.
To do this go to the Enterprise Management Console and under «Source Documents» look for the task (qvw file) you want to become an EDX (if anyone knows what does the acronym grateful!) And rather than schedule it to run on certain day / time or after the execution of a previous task (chained execution) indicated to be executed «On External Event»:

Or it can be presented as:

If we have our console Publisher have a flap over where we create tasks based on the execution of anything, not just a reload of a file qvw:

It is important to note the name that gets the job EDX: in the above case the name of the task it can give us in the edit box with the arrow pointed in the picture above. But if you want to convert it into EDX is a document qvw (Source Document if you have Publisher or User Document otherwise) we can not assign the name to the task and we must take the QlikView gives. Here’s a little secret: this name is the full string (usually very large) that appears at the beginning of the tab «Status» that is in the Management Console (NOT Enterprise):

In this case the task is called «Aplicaciones / Monitoreo Servidor / WebServerPerformance.qvw» literally.
Once the EDX is created on the server side we can work on the side of the client application to trigger this task.

To do this we will create a button (Reload) in the application and associate a macro as follows:

  • First create the button and then go to properties,
  • Then select the tab «Actions»
  •  Select the type of action «External» and right to choose «Run Macro»
  •  Complete the box «Macro Name» with the name that will give the sub code entry point.
  •  Finally, accept the creation of the action and click on «Module Editor» where we will copy the code below, adapted as required for each case:


Here’s the complete code needed to invoke the macro recharge «Applications / Server Monitoring / WebServerPerformance.qvw». Pay attention to the comments:
Sub CargoEDX()

	url = "http://SERVIDOR _QLIKVIEW:4720/qtxs.asmx"     'QV Server Address and URL EDX's service
	userID = "LOGIN"				'User login in target system. It must belongs to  "QlikView Administrators"
	pass = "PASSWORD" 				'User Password
	doc = "Aplicaciones/Monitoreo Servidor/WebServerPerformance.qvw" 'Task name that it wants execute

	MsgBox "The reload starts. Please press "Accept" and wait for a minute"
MsgBox ReloadEDX(url, doc, userID, pass) 'Call to the EDX execution

End Sub

Function ReloadEDX(dsURL, document, userID, pass)

  ' Here get a ticket to call the EDX. It's because a security scheme based in double request
  Dim requestKey, xmlhttp, requestData, httpResult
  Set xmlhttp = CreateObject("msxml2.xmlhttp.3.0")
  xmlhttp.Open "post", dsURL, False, userID, pass
  requestData = "<Global method=""GetTimeLimitedRequestKey"" />" '& vbCrLf
  xmlhttp.send requestData
  Set oDOM = CreateObject("MSXML2.DOMDocument.3.0")
  oDOM.LoadXML xmlhttp.responseText

  ' Takes ticket hash from the response
  requestKey = oDOM.SelectSingleNode("//GetTimeLimitedRequestKeyResult").Text

  ' Call task (EDX) for execute
  rtaExec =  CallTask(requestKey, document, dsURL, userID, pass)
  If rtaExec = Null Then
    ReloadEDX = httpResult
  Else
    If rtaExec = "Success" Then
        ReloadEDX = "The reload has finished."
    Else
        ReloadEDX = httpResult
    End If
  End If

End Function

'EDX call thru a HTTP POST
Function CallTask(key,task,url, usr, pasw)

  Set xmlhttp2 = CreateObject("msxml2.xmlhttp.3.0")
  requestData = "<Global method=""RequestEDX"" key=""" & key& """><i_TaskIDOrTaskName>" & task& "</i_TaskIDOrTaskName><i_Password /><i_VariableName /><i_VariableValueList /></Global>" & vbCrLf
  xmlhttp2.Open "post", url, False, usr, pasw
  xmlhttp2.send requestData ' Send XML with service qtxs.asmx required data 
  Set oDOM2 = CreateObject("MSXML2.DOMDocument.3.0")
  oDOM2.LoadXML xmlhttp2.responseText

  set CallTask2 = oDOM2.SelectSingleNode("//TaskStartResult")
  CallTask = "Success"

End Function
For this script (VBS) function must setting some security features in the right way:
1-In Module Editor (macro) must be set «Required Security Module: Access to theSystem» and «Local Security Now: Allow Access to the System.»
2 – Before running the qvw from the access point must be opened locally on the server and a pop-up warning that the document contains macros that must be answered»Allow Any Macro (only to trustED documents)»:
3 – If the user is presented with an error message indicating that it attempted to execute an instruction «Activex.xxxx» or similar, which is due to a security issue, especially if you’re running from the ActiveXplugin for IExplorer or in «Open in Server», then must simultaneously press CTRL + Shift +M and pop-up that appears to answer «Allow in the System Access ModuleScript»:
Finally: What is for  this complex technique? Is it worth it?
Yes, definitely worth it because it extends the scope of QlikView to almost anything we want to do. Here are some scenarios where I have used:
– Proccess and P&L : In the monthly accounting close process companies accounting, controls, corrects and repeats this process until everything fits and then prepares the P & L (Profit and looses) . This activity has two characteristics: it is only once a month (though several times for a few days) and then correcting accounting can not be expected to recharge by QlikView «Schedule». On the other hand it is continuing to schedule a reload all the time when this activity is performed only once a month. By this method the user corrects the accounting and press a button to reload and assemble QV P & L and after a few seconds you can see the result.
– Another case is to send mails with attachments QV data from the server and not from the user’s PC, either for reasons of security, auditing, completeness and / or robustness of the application. This is making available to the user a button «Send Mail» and then the client saves the attachments QV server side (I’ll explain this in future post) and fires a server-side task that collects data and sends them mail.
– Another little widespread use is closely linked to what is called Enterprise Performance Management where the best example is the company’s budgeting process where each participant responsible for reading certain data (current goals, projections, historical data, etc.) and enter the new objectives proposed for the current year. Data entry is done through «INPUT FIELD» (again subject of future post), but then these data should be recorded on the server and users often require data to arrive immediately to the next actor in the process, for which we force on-demand recharging the data typed by the user.
As such there are many other scenarios that can arise where tasks need to run server side, whether charged or are other programs / commands.
I hope you find this usefull.
Greetings!

Trabajar con EDX: Qué son, para que sirven y como se hacen?

En varios lugares de la documentación de QlikView se encuentran referencias a los EDX. También hay muchas entradas en la comunidad de QlikView y otras pero para alguien novato en el tema es bastante complejo aclararse los conceptos necesarios para trabajar con esta funcionalidad.

En primer lugar les voy a dar algunas definiciones en base a mi propia experiencia de haber usado esto.

¿Que es un EDX? En pocas palabras claras y simples es una tarea que está programada del lado del servidor de QlikView (a través de alguna de las dos consolas del Servidor de QlikView) para ser disparada ante un Evento Externo. Este evento externo es ni mas ni menos que la invocación programática de dicho servicio haciendo uso del protocolo HTTP Post.

Ahora bien, cuando decimos «una tarea del lado del servidor» ¿ de que estamos hablando exáctamente ? Bueno esto depende de si nuestro servidor cuenta con la licencia de Publisher o no.

Si no contamos con Publisher la única tarea que se podrá ejecutar será la recarga de un (o varios) qvw’s programada del lado del server para ser disparada ante un evento externo, por ejemplo el click de un botón de la aplicación por parte de un usuario.

Por otro lado en caso de tener Publisher a lo anterior dicho  se suma que la tarea puede ser cualquier cosa que se pueda ejecutar: por ejemplo un comando isql de SQL Server para operar una base de datos, un programa de SendMail, o un comando del tipo «cmd» con cualquier comando del sistema operativo: copy, delete, ftp, etc.

Para aquellos que no cuentan con Publisher hay un consuelo y camino alternativo que consiste en que el qvw que se recarga cuente con un script y dentro de él una o más instrucciones EXECUTE con las cuales podremos ejecutar cualquier cosa, tal como muestra la ayuda  (algo antigua….) de dicha instrucción en QlikView.HLP:

Execute C:\MSOffice95\Excel\Excel.exe;

Execute winword macro.doc;

Execute cmd.exe /C C:\BatFiles\Log.bat

El ejemplo que les voy a mostrar y especialmente las pantallas son de un QVS (QlikView Server) con Publisher, pero también aplicables a un server que no lo tiene.

Primero vamos a crear la tarea del lado del servidor que recargaremos programaticamente on-demand.

Para ello vamos a la Enterprise Management Console y dentro de «Source Documents» buscamos la tarea (archivo qvw) que queremos convertir en un  EDX (si alguien sabe que significa el acrónimo lo agradeceré!) y en lugar de programarlo para que se ejecute en determinado día/hora o luego de la ejecución de una tarea previa (ejecución encadenada) indicamos que será ejecutada «On External Event»:

O también puede presentarse como:

Si contamos con Publisher nuestra consola tendrá una solapa mas donde podremos crear tareas basadas en la ejecución de cualquier cosa y no solo una recarga de un archivo qvw:

Es importante notar el nombre que obtiene la tarea EDX: en este último caso el nombre de la tarea se la podemos dar nosotros en el edit box señalado con la flecha en la imagen anterior. Pero en el caso que lo que queramos convertir en EDX sea un documento qvw (Source Document si tenemos Publisher o User Document en caso contrario) no podemos asignarle el nombre a la tarea y debemos tomar el que le da QlikView. Aqui va un pequeño secreto: este nombre es la cadena completa (generalmente muy extensa) que aparece al comienzo de la solapa «Status» que está en la Management Console (NO Enterprise):

En este caso la tarea se va a llamar «Aplicaciones/Monitoreo Servidor/WebServerPerformance.qvw» literalmente.

Una vez que el EDX está creado del lado del servidor podemos trabajar del lado de la aplicación cliente para disparar esta tarea.

Para ello vamos a crear un botón (Recargar) en la aplicación y asociarle una macro del siguiente modo:

– Primero crear el botón y luego ir a propiedades del mismo,

– Luego seleccionar el tab «Acciones»

– Seleccionar el tipo de acción «Externa» y a la derecha elegir «Ejecutar Macro»

– Completar el cuadro de «Nombre de Macro» con el nombre del Sub que le daremos al punto de entrada del código.

– Finalmente aceptar la creación de la acción y cliquear el botón «Editor de Módulo» donde copiaremos el código de más abajo, con las adaptaciones que se requieran para cada caso:

Aquí va el código completo de la macro necesaria para invocar la recarga de «Aplicaciones/Monitoreo Servidor/WebServerPerformance.qvw«. Prestar atención a los comentarios:

Sub CargoEDX()

	url = "http://SERVIDOR _QLIKVIEW:4720/qtxs.asmx"     'Direccion del servidor de QV y URL del servicio de EDX
	userID = "LOGIN"				'login del usuario en el systema destino. Debe pertenecer al grupo "QlikView Administrators"
	pass = "PASSWORD" 				'clave del usuario
	doc = "Aplicaciones/Monitoreo Servidor/WebServerPerformance.qvw" 'Nombre de la tarea que se quiere ejecutar

	MsgBox "La recarga/ejecución comenzó. Por favor presione <Aceptar> y espere un par de minutos"
	MsgBox ReloadEDX(url, doc, userID, pass) 'Se invoca la ejecucución

End Sub

Function ReloadEDX(dsURL, document, userID, pass)

  ' Obtiene un ticket para invocar al EDX debido a un esquema de doble request
  ' implementado a partir de QV 8.6 por cuestiones de seguridad
  Dim requestKey, xmlhttp, requestData, httpResult
  Set xmlhttp = CreateObject("msxml2.xmlhttp.3.0")
  xmlhttp.Open "post", dsURL, False, userID, pass
  requestData = "<Global method=""GetTimeLimitedRequestKey"" />" '& vbCrLf
  xmlhttp.send requestData
  Set oDOM = CreateObject("MSXML2.DOMDocument.3.0")
  oDOM.LoadXML xmlhttp.responseText

  ' Extrae el ticket de la respuesta
  requestKey = oDOM.SelectSingleNode("//GetTimeLimitedRequestKeyResult").Text

  ' Llama a la tarea (EDX) que queremos ejecutar
  rtaExec =  CallTask(requestKey, document, dsURL, userID, pass)
  If rtaExec = Null Then
    ReloadEDX = httpResult
  Else
    If rtaExec = "Success" Then
        ReloadEDX = "La recarga finalizó."
    Else
        ReloadEDX = httpResult
    End If
  End If

End Function

'Llama al EDX mediante un HTTP POST
Function CallTask(llave,tarea,url, usr, pasw)

  Set xmlhttp2 = CreateObject("msxml2.xmlhttp.3.0")
  requestData = "<Global method=""RequestEDX"" key=""" & llave & """><i_TaskIDOrTaskName>" & tarea & "</i_TaskIDOrTaskName><i_Password /><i_VariableName /><i_VariableValueList /></Global>" & vbCrLf
  xmlhttp2.Open "post", url, False, usr, pasw
  xmlhttp2.send requestData ' Envía el XML con los datos requeridos por el servicio qtxs.asmx
  Set oDOM2 = CreateObject("MSXML2.DOMDocument.3.0")
  oDOM2.LoadXML xmlhttp2.responseText

  set CallTask2 = oDOM2.SelectSingleNode("//TaskStartResult")
  CallTask = "Success"

End Function


Para que este script (VBS) funcione deben setearse algunas configuraciones de seguridad de la forma adecuada: 1-En el Editor del Módulo (macro) se debe setear " Seguridad del Módulo Requerida: Acceso al Sistema" y "Seguridad Local Actual: Permitir Acceso al Sistema".

2- Antes de ejecutar el QVW desde el access point se debe abrir localmente en el servidor y aparecerá un pop-up advirtiendo que el documento contiene macros a lo que se debe contestar «Permitir Cualquier Macro (solo para documentos de confianza)»

3- En caso que al usuario se le presente un mensaje de error indicando que se intentó ejecutar una instrucción «Activex.xxxx» u otro similar, lo que se debe a un problema de seguridad especialmente si se está ejecutando desde el plugin Activex de IExplorer, o en modo «Open in Server» se deben pulsar simultáneamente las teclas CTRL+ Shift + M y en el pop-up que aparecerá contestar «Permitir Acceso al Sistema en el Script de Módulo»:

Por último: ¿Para qué sirve y/o se usa esta compleja técnica?¿Vale la pena?

Definitivamente SÍ vale la pena porque extiende el campo de acción de QlikView a casi cualquier cosa que querramos hacer. A continuación menciono algunos escenarios donde yo lo he usado:

– Armado de Cuadro de Resultados: En el cierre contable mensual de las empresas se procesa la contabilidad, se controla, se corrige y se repite éste proceso hasta que todo cuadre y entonces se prepara el cuadro de resultados (P&L). Esta actividad tiene dos características: se hace solo una vez al mes (aunque varias veces durante pocos días) y luego que se corrige la contabilidad no se puede esperar a que QlikView recargue por «Schedule». Por otro lado no es conveniente programar una recarga continua todo el tiempo cuando esta actividad se realiza solo una vez al mes. Mediante este método el usuario corrige la contabilidad y presiona un botón para que QV recargue y arme el Cuadro de Resultados (P&L) y al cabo de pocos segundos ya puede ver el resultado.

– Otro caso es el envío de mails con datos de QV adjuntos desde el servidor y no desde la PC del usuario, ya sea por razones de seguridad, auditoría, completitud y/o robustez de la aplicación. Para ello se pone a disposición del usuario un botón de «Enviar Mail» y entonces el cliente de QV graba los datos adjuntos del lado del servidor (explicaré esto en futuro post) y dispara una tarea del lado del server que recoge dichos datos y envía el correo.

– Otro uso poco difundido está muy ligado a lo que se llama Enterprise Performance Management donde el mejor ejemplo es el proceso presupuestario de la empresa donde cada participante responsable lee ciertos datos (metas actuales, proyecciones, datos históricos, etc) e ingresa los nuevos objetivos propuestos para el ejercicio en curso. El ingreso de datos se hace mediante «INPUT FIELD» (nuevamente tema de futuro post), pero luego estos datos se deben grabar en el servidor y muchas veces los usuarios requieren que los datos lleguen inmediatamente al siguiente actor del proceso, para lo cual forzamos una recarga on-demand con los datos tipeados por el usuario.

Como estos hay muchos otros escenarios que pueden presentarse donde sea necesario ejecutar tareas del lado del servidor, sean de recarga o sean otros programas / comandos.

Espero les sirva.

Saludos !!!