Translate

Mostrando entradas con la etiqueta javaScript. Mostrar todas las entradas
Mostrando entradas con la etiqueta javaScript. Mostrar todas las entradas

jueves, 29 de octubre de 2015

Cookies with ExtJS




In this case we are going to use a cookie to store the username logged into de system in case the checkbox “Recordar usario” is checked.

To set the cookie we are going to use this function called when clicked the button “Entrar”, and after success to log :



In this function the cookie is created with the id 'accessCookie' and with the username 'user', and also with an expiration delay of 30 days. In case the user select not to remember the username then the delay is set for one milisec which causes to delete the cookie.


To load the user stored in the cookie we use the afterrender event for the login view, which tries to read the cookie and if it exists then the username is loaded into the user name field, and the  “Recordar usuario” check box is checked.


lunes, 28 de septiembre de 2015

Instalación de Sencha Cmd 6 en MacOS(Yosemite)

1- Ver si java está presente con:

java –versión

Si no lo está se necesitará un java JDK (Java Development Kit), descargarlo de la web de Oracle e instalar. 

Al instalarlo se guarda en :

Library/Java/JavaVirtualMachines
Library/Internet Plug-Ins en el fichero JavaApplePlugin.plugin




2- Ruby solo se usará si usamos ExtJS 5 y Sencha Cmd 5. De todas formas en macOS viene instalado ya (Yosemite). Para ver que está :

ruby –version

3- Instalamos sencha. Ántes podemos ver si ya existe con:

sencha which (debe devolver la versión instalada y el path)

Descargamos Sencha Cmd y lanzamos el ejecutable. Hay dos versiones en la web, con y sin Java JRE. Yo he usado la versión con JRE.

Se instala en /Users/ugeHidalgo/bin/Sencha/Cmd/6.0.1.76 y a la misma vez se añade esto al path. 



Para ver si se añadió el path correctamente podemos usar el comando:

echo $PATH

Si no aparece entonces podemos añadir el path con el comando:

export ~/bin/Sencha/Cmd/6.0.1.76/:$PATH

Para generar la aplicación, descargamos la versión GPL de ExtJS 6 de la web de Sencha, la descomprimimos y ponemos en alguna carpeta, y generamos la aplicación con Sencha Cmd con el comando :

sudo sencha –sdk /path/a/extjs generate app NombreApp /path/a/donde/poner/app

Con el comando sudo evitamos problemas de permisos.

Una vez generada la aplicación y compilada obtendremos esto:



Para ver la aplicación no necesitamos instalar ningún servidor web, podemos usar el propio de Sencha, y para ello vamos a la carpeta de la aplicación generada y ejecutaremos el comando:

sencha app watch 

La aplicación se compila y se puede acceder a ella a través de http://localhost:1841 



A veces podemos encontrar algún fallo del tipo:



Esto es debido a problemas de permisos al acceder a la carpeta donde se ha instalado Sencha Cmd, en concreto la carpeta repo. Podemos dar permisos de acceso total al grupo Users, o bien ejecutar:

sudo sencha app watch 

El servidor se queda esperando cualquier cambio. En este punto podemos hacer modificaciones en los ficheros javascript del código, salvarlos, vaciar el buffer del navegador, recargarlo, y los cambios se verán al momento.



Para terminar el servidor basta con hacer Ctrl+C

martes, 5 de agosto de 2014

Testing javascript with jasmine/sinon


Spy

Un spy es un objeto usado para registrar toda interacción con otros objetos, es una función usada para registrar si se ha llamado y cuantas veces, con qué argumentos, los valores devueltos, el valor de this, y cualquier excepción si la hay para cada una de las llamadas a esa función.

Puede ser una función anónima, o envolver a otra función existente controlando así lo anteriormente descrito. En este último caso la función a la que envuelve sigue funcionando igual. 

Los datos guardados por el spy se guardan en un array args[][] de manera que args[0] serán los argumentos recibidos en la primera llamada, args[1] en la segunda y así consecutivamente.

Los valores devueltos se guardan también en un array returnValues[], donde returnValues[0] sería el valor devuelto en la primera llamada Si no devuelve valor alguno será undefined.

El valor de this se devuelve igual que los valores devueltos pero con el array thisValues[].
Igual con las excepciones que irán en el array exceptions[].

Los spies son útiles para controlar llamadas a una función, que se llame con los argumentos adecuados, que devuelva el valor correcto, etc…

Ejemplo de definición de un spy que registrará todas las operaciones de Extjs.ajax sin interferir en su normal funcionamiento:

sinon.spy (jQuery,’ajax’);
jQuery.getJSON(‘/some/data’);

El spy no interferirá en el normal funcionamiento de jQuery.ajax, pero registrará los datos asociados.

Los métodos más ususales para spy suelen ser:

  •          calledOnce: si se ha llamado una sola vez.
  •          called: al menos una.
  •          calledTwice: dos veces.
  •          calledThrice: tres veces
  •          callCount:  el nº de veces llamado
  •     calledWith(arg1, arg2,…): llamado con los argumentos indicados(puede incluir otros distintos).
  •          calledWithExactly(arg1, arg2,..): llamado con los argumentos indicados y ninguno más.
  •          Threw(): devolvió excepción.


Algunos ejemplos de spies:

Así se define un spy para que actúe cobre el objeto controller.behaviourStore cuando se llame al método load:

storeLoadSpy = U4.testframework.spy(controller.behaviourStore, 'load');

Una vez definido llamaremos a cualquier otro método que queramos saber si hace una llamada a load, y controlaremos por ejemplo que se ha llamado y con los argumentos correctos

expect(storeLoadSpy.called).toBeTruthy();
expect(storeLoadSpy.args[0][0].listNodes).toBe(nodesList.toString());


Stub

Es un sustituto de la función a la que envuelve, o un sustituto de una función que no existe. Permite definir un comportamiento dado al llamar a esa función stub, es decir fijar unos parámetros y que devuelva un valor fijo determinado. Stub implementa la interface spy, por lo que también puede ser usado un stub a modo de spy.

Las dos principales razones para usar stubs es enmascarar comportamientos, por ejemplo evitar la necesidad de tener que hacer peticiones a un servidor, o evitar que una pantalla de confirmación aparezca, etc.. y por otro lado proveer a los test de datos que normalmente son suministrados por otras funciones sin tener que usarlas. Con esto aislamos el test para evitar que otros aspectos externos al test puedan influir.

Los stubs se crean de las siguientes formas:

·        sinon.stub()  crea stub function anónima.
·        sinon.stub(object,”method”) crea un stub para el método object.method
·       sinon.stub(object,”method”,func) crea un stub para el método object.method sustituyéndolo por la función func
·        
Los métodos más usuales para stub son:

  •           returns(value) hace que el stub devuelva siempre ese valor.
  •      throws(exception) lanza una excepción, si exception es un string puede ser el tipo de excepción
  •          withArgs (arg1, arg2,…)


Algunos ejemplos de stubs

Crea stub de función anónima, y lo define de manera que si se llama con el parámetro 42 devuelve 1, si se llama con el 1 devuelve un error, y si no se usa argumento alguno entonces no devuelve nada.

var callback = sinon.stub();
    callback.withArgs(42).returns(1);
    callback.withArgs(1).throws("TypeError");

    callback(); // No return value, no exception
    callback(42); // Returns 1
    callback(1); // Throws TypeError


En el siguiente ejemplo de crea un stub para el método getSelection del objeto behaviourView.grid.getSelectionModel(), que devolverá siempre un array con un record, es decir cada vez que se haga una selección del grid se devuelve el mismo objeto

U4.testframework.stub(behaviourView.grid.getSelectionModel(), 'getSelection').returns([record]);
expect(behaviourView.fireEvent.calledWithExactly('inheritbehaviourmodified',record, behaviourSelected.originalValue)).toBeFalsy();

En este otro ejemplo usaremos un stub para evitar que se haga la llamada al servidor, y como si fuera un spy controlaremos que se ha hecho un POST sobre la url correcta, y con los datos correctos:

saveChanges: function (config) {
        var me = this,
            client,
            jsonData = me.fillJSONData(config.treeStore, config.behaviourStore, config.evidenceStore),
            competenceGroupsPath = 'hrms/competence/competencegroups/';
       
        U4.Ajax.setAccessId(me.accessId);
        client = U4.util.Path.encodeSegment(me.client);
       
        return U4.Ajax.promise({
            url: U4.util.Path.getApiPath(competenceGroupsPath + client),
            method: 'POST',
            jsonData: Ext.JSON.encode(jsonData)
        });
    },
promiseStub = U4.testframework.stub(U4.Ajax, 'promise');
saveProxy.saveChanges(config);
expect(promiseStub.calledOnce).toBeTruthy();
expect(promiseStub.args[0][0].method).toBe('POST');
expect(promiseStub.args[0][0].url).toBe('hrms/competence/competencegroups/XX');
expect(promiseStub.args[0][0].jsonData).toBe(jsonDataExpected);

Ejemplo de crear un FakeServer que simule un servidor que devuelva los datos a una petición de un store.load (response debe ser un array con los elementos a devolver), igualmente se usa un spy asociado a Ext.Ajax sobre el método ‘request’ para controlar si se hizo una llamada

fakeServer = U4.testframework.createFakeServer();
fakeServer.respondWith('GET', new RegExp('.*hrms/competence/competencegroups/.*'),
                [200, { 'Content-Type': 'application/json' },
                    response]);

spyAjaxRequest = U4.testframework.spy(Ext.Ajax, 'request');

store.load({ listNodes: '' });
fakeServer.respond();
expect(spyAjaxRequest.calledOnce).toBeTruthy();


Otro ejemplo de stub para evitar que se muestre un mensaje de confirmación y comprobar que se ha llamado a dicho mensaje.

stubOnShow = U4.testframework.stub(U4.Msg, 'show').yieldsTo('fn', 'ok');


expect(stubOnShow.called).toBeTruthy();

domingo, 20 de abril de 2014

Googlemaps javaScript API with Ext.NET and Web Forms

Googlemaps API is a desktop and mobile web mapping service application and technology provided by Google, offering satellite imagery, street maps, and Street View perspectives, as well as functions such as a route planner for traveling by foot, car, bicycle (beta test), or with public transportation.

You can use it embed in your web pages. Here you can find some documentation on how-to register for use and some examples: https://developers.google.com/maps/documentation/javascript/tutorial

This is an example showing a map with the localization for a given shop:


The first step to use is to obtain a key.

Next you need to add a script in web page in order to allow access to googlemap, using the key previously obtained:



Next step is to add a script to the page used to load the map with the position needed. in my case I use a marker to mark the desired position:

In the aps.net page we need to include an element, could be a div, or a panel, with the name map_canvas to draw the map on it.


In my page I am using a TabPanel, and I use the Panel map_canvas to draw the map. To access this element inside the DOM is important to take care about the real name used. For this a launch the pagem and then using Inspect Element a obtain the real name. In my case was 'cpMainContent_map_canvas-body'. This is becacuse I  am using Masterpages, and then the panel is nested with another panels, and ContentPlaceHolder.

 To load the correct map a use a Listener associated to the loading of the tab page having the map. This listener use initializeMap taking the longitude, latitude and name parameter from text fields inside the page.



Also I have added a few functionalities to the map, allowing to reposition the marker doing click over the map and reloading latitude and longitude data to web fields. And finally you could also make click over the marker to make zoom and center the position to this marker.









domingo, 30 de marzo de 2014

jQuery Date Picker en español en ASP.NET MVC


Esta seria la configuración del componente datePicker para que aparezca en Español, permita escoger mes y año y con animación de scroll hacia abajo.


Esta sería la forma de usarlo en ASP.NET  MVC asociando el resultado a un campo de una tabla, y asignando dicho campo para que al editar muestre la fecha guardada.

Ojo que el dato devuelto por el datePicker es DateTime2, y no olvidar incluir en el view referencia al fichero del script definido anteriormente. A modo de ejemplo, esto sería el código de un view que usa el datePicker

jueves, 9 de enero de 2014

ASP.NET: Server Side vs Client Side

This is en example showing how to call a javascript piece of code at the client side, and the equivalent in the server side, but this time using the code behind of the page in C#:

The example consists on a web form in which you have to provide a name using a text box, choose a date using a calendar component, and finally select a flight company using a dropdown list component.

Clicking over the Alert button the forms will show two messages indicating the name, date and flight company, using client side and server side.


Once we have enter the name and choosed the date and flight company we obtained two messages, the first one produced by the client side :



And the second one produced from the server side just at the top of the page:



This is the markup for the web form showing the javascript code for the client side, and the button used to calls the client side method "sayMessage()" defined in the javascript, and the method "Button3_Click" for the server side defined in the code behind file.


This is the code behind implementing the Button3_Click method:



viernes, 13 de diciembre de 2013

JQuery over a Table

Shows a table with alternate colors, and putting in yellow color the field which has the cursor on it. Also when you click over the first title it grows and one second later back to its original size.




martes, 10 de diciembre de 2013

ASP.Net: Validation

There are six components in Visual Studio you can use for user validation:

This first four are used to validate data in the client side:

  • RequiredFieldValidator: verify if any given field is present or not.
  • Rangevalidator: verify if data is between a given range.
  • RegularExpressionValidator: verify data from a mask string, for example, to verify if a strinf is a correct email.
  • Comparevalidator: used to compares two fields.
The last two are valids also to validate data in the server side in adittion to client side, which is more important, because users can disable javascript in their browsers disabling then the client side validation. So is important not to rely only in client side validation adding also server side validation.


  • CustomValidator: enables to write javaScript code associated to a validation action over a component.
  • ValidationSummary: show the errors that validator component raises.

This could be an example of a form showing a form to leave a commet in our site:


Here we have a few text boxes for we can add validator. For example, for the first one, then text box for the name I had added a RequiredFieldValidator, to avoid a missing name. The most important properties you must set for this control are:


  • ControlToValidate: The name of the control you are going to validate , the name of the text box.
  • CssClass: Class on the CSS file that define for example the color of the text when an error raises.
  • ErrorMessage: The string that shows the error.



For the second one I have added to Validation controls, a RequiredFieldValidator, configured similarliy to previous one, and also a RegularExpressionValidator. For this one is important to set the property ValidationExpression choosing between the different Expressions Visual Studio offers. In this case email expression.



For the third one, I have added another two control validations, a RequireFieldValidator, an also a CompareValidator, to compare if both eMails are equal.


For the last field, the comment I have added only a RequireFieldValidator.

And finally at the end of the form I have added a ValidationSummary  to shows all the errors made by the users during the form filling:




I have added also a CustomValidator for the telephone number, which calls a javaScript function used to verify that the telephone numer is not missing. is the same task as a RequireFieldValidator, but this time this validation is on the server side. For this you have to write a javaScript function, for the client Side, an also a C# function for the server Side. The first one is implemented in the same html file, while the C# code is implemented in the code behind file associated to the form, and into the Server_Validate event.

This is the code into the HTML with the CustomValidator, which references the two functions needed, validatePhoneNumber and CustomValidator1_ServerValidate:


This is the code also into the HTML with the javaScript function validatePhoneNumber:


This is the code behind with the function CustomValidator1_ServerValidate:


This is an example of the form showing a few errors: