Fotos del duatlon cross de Motril (posicion 25 general / 4 categoría)
lunes, 1 de diciembre de 2014
viernes, 10 de octubre de 2014
viernes, 12 de septiembre de 2014
Derrapando / skidding...
La vida no debería ser un viaje hacia la tumba con la intención de llegar a salvo con un cuerpo bonito y bién conservado, sino más bién llegar derrapando de lado, entre una nube de humo, completamente desgastado y destrozado, y proclamar en voz alta: ¡Uf!, ¡Vaya viajecito!
Life should not be a journey to your grave with the aim to arrive with a beautiful and well conserved body, but rather arrive skidding in a cloud of dust, completely worn and destroyed, and screaming loud: Wow!, What a trip!
Hunter S. Thompson
domingo, 7 de septiembre de 2014
miércoles, 27 de agosto de 2014
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();
Etiquetas:
jasmine,
javaScript,
sinon,
TDD,
testing
jueves, 12 de junio de 2014
Subida a Lentegí desde Almuñecar
Lugar: Costa Tropical, Almuñecar, Granada, España.
Tipo de Ruta: Carretera. Montaña.
Ruta de montaña de poco kilometraje, 42km pero exigente. La salida se hace desde la localidad de Almuñecar, a la que retornaremos una vez alcanzada la locaidad de Lentegí. El punto mínimo de altura es el nivel del mar mientras que el punto mas alto alcanzado es de 694m. El acumulado de desnivel es de 780m.
Esta ruta tiene tres zonas claramente diferenciadas, la primera de ella desde la salida hasta el km 8 es practicamente llana, con algún repecho poco reseñable mientras transitamos por el valle del rio guadalfeo entre campos de aguacates.
Una vez alcanzado el km 8 comienza la segunda parte con una suave ascensión hasta el cruce de Lentegí en el Km 15, atravesando las localidades de Jete primero y Otivar después.
De vez en cuando encontramos alguna rampa mas pronunciada, pero la subida es sencilla. A medida que discurran los kilómetros el porcentaje de las ascensión irá incrementando hasta alcanzar el cruce mencionado.
Comienza aquí la tercera parte de la subida girando a la derecha para comenzar la ascensión a Lentegí. Mientras subimos entre pinos podremos contemplar enfrente la subida al mirador de la cabra.
Sobre Lentegí y la Cabra y la Sierra de Almijara y Tejeda al fondo |
En el km 18 encontraremos un cruce tomando el desvio hacia la derecha en dirección a la piscina, vienen ahora las últimas rampas que nos dejan en la parte superior del pueblo.
Una vez alcanzado este bajaremos en dirección al centro del pueblo para retornar por la misma carretera que subimos. Cuidado con el primer km de bajada que es bastante pronunciado.
lunes, 19 de mayo de 2014
Ext.JS and Visual Studio: HTTP Error 404 file not found when loading json file
I have the following store defined, loading data from a json file:
Ext.define('Uge.store.Articles', {
extend: 'Ext.data.Store',
model: 'Uge.model.Article',
proxy: {
type: 'ajax',
url: 'data/articles.json',
reader: {
type: 'json',
root: 'articles',
successProperty: 'success'
}
},
autoLoad: true
});
Data to load is inside the file data/articles.json, but when trying to load data we get an error pointing that file could not be found.
To avoid this error you need to set your project to accept json file types. You can do this setting the following configuration into web.config file:
Ext.define('Uge.store.Articles', {
extend: 'Ext.data.Store',
model: 'Uge.model.Article',
proxy: {
type: 'ajax',
url: 'data/articles.json',
reader: {
type: 'json',
root: 'articles',
successProperty: 'success'
}
},
autoLoad: true
});
Data to load is inside the file data/articles.json, but when trying to load data we get an error pointing that file could not be found.
To avoid this error you need to set your project to accept json file types. You can do this setting the following configuration into web.config file:
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.
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.
Etiquetas:
Ajax,
C#,
Ext.NET,
googlemaps,
javaScript
miércoles, 16 de abril de 2014
Ext.NET ComboBox samples
Combobox loading data from store which uses an SqldataSource. It shows Name field, and returns SportID field value:
The method in code behind could be as follows:
protected void Store2_ReadData(object sender, StoreReadDataEventArgs e)
{
using (var db = new ClubSiteContext())
{
Store store = this.cbxDeportes.GetStore();
store.DataSource = from s in db.Sports select new { s.SportID, s.Name };
store.DataBind();
}
}
In this case is important to perform an initial load for the data when the page is loaded.
Other way to load data is using a SqlDataSource like this:
Once we have data loaded into the combobox, we could select an item, or select the empty item described using the tag EmptyText as follows:
if (aRaceType.SportID == 0)
cbxDeportes.Value = "";
else
{
object SportID = aRaceType.SportID;
cbxDeportes.Select(SportID);
}
If we want to perform some kind of action when user selects a value from combobox we could use Direct Events an a method in code behind like this:
And this is the method implemented in code behind:
protected void cbRaceTypesChangeValue(object sender, DirectEventArgs e)
{
txbxPoints.Text = "Escribe algo";
}
More combobox samples here http://examples.ext.net/#/Form/ComboBox/Overview/
The method in code behind could be as follows:
protected void Store2_ReadData(object sender, StoreReadDataEventArgs e)
{
using (var db = new ClubSiteContext())
{
Store store = this.cbxDeportes.GetStore();
store.DataSource = from s in db.Sports select new { s.SportID, s.Name };
store.DataBind();
}
}
In this case is important to perform an initial load for the data when the page is loaded.
Other way to load data is using a SqlDataSource like this:
Once we have data loaded into the combobox, we could select an item, or select the empty item described using the tag EmptyText as follows:
if (aRaceType.SportID == 0)
cbxDeportes.Value = "";
else
{
object SportID = aRaceType.SportID;
cbxDeportes.Select(SportID);
}
If we want to perform some kind of action when user selects a value from combobox we could use Direct Events an a method in code behind like this:
And this is the method implemented in code behind:
protected void cbRaceTypesChangeValue(object sender, DirectEventArgs e)
{
txbxPoints.Text = "Escribe algo";
}
More combobox samples here http://examples.ext.net/#/Form/ComboBox/Overview/
sábado, 12 de abril de 2014
Y ahora ya sí.... por fin el buen tiempo
jueves, 3 de abril de 2014
Entity Framework, Code First and Inheritance
We have the following classes structure:
These are the classes code:
These are the classes code:
We are going to use the TPH (Table Per Hierarchy) way, which means we are going to have only one table for an Hierarchy. In this case we are going to have one table for both Customers and Employees.
In the Data Base Context I need to add all the classes that represent an entity, but when I´m using inheritance and TPH, I do not need to add the classes which inherits from a main class. I´m going to add only the base class. So the Data Base Context would be as follows:
So, when EF creates the data base from the model this is the table that I´m going to have including Customer and Employees. Note that EF adds a field called Discrimator, which is a string field used by EF to discriminate to which entity does the data belong. In our case this field could contains values like "Customer" or "Employe".
But, what happen when I need to query data from this table?, well I could made queries for the parent object, person, or queries to child objects, customer or employee.
This is an example of ASP.NET Web Forms GridView component using EF and LINQ to access data for Employees:
The GridView in a browser showing data for employees |
The aspx code for the GridView |
The code for the GridView´s SelecMethod |
Note that we can query for a child object, but in this case we need to use OfType to indicate EF to retrieve only the data from the People table belonging to the Employee Entity.
Etiquetas:
ASP.Net,
C#,
Code First,
Entity Framework,
Programming,
Visual Studio
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
Etiquetas:
ASP.Net,
C#,
javaScript,
jQuery,
MVC,
Programming,
Visual Studio
jueves, 27 de marzo de 2014
ASP:NET MVC More than one model in the same view
In this case I have two models that I need to pass to the view because I need data from both classes. The first one is associated to the class UserProfile which manages the userName, userID, email, and all the data for a given user:
The second model manages the passwords for the user name. These data are stored encrypted into a different file in order to prevent access to see the password. Both classes have Data Annotations to describe label fields,keys, required data, etc. In this link you could find info about regular expressions to validate data entered in data fields.
In my example I need to use data from both classes(models) when a new user is being registered, that is, enter username, password and all the other data, so I need to pass both models to the same view, in which data could be entered. This is the code for the view, using data from both models:
An this is how this view is showed in the browser:
MVC allows you to pass only one model to a View, but you can use different ways to pass more than one. The way I do it, is using an auxiliary class in which you can put all the models you want to pass to the view. So this is the additional class including the two classes mentioned above:
And this is the method associated with the view, saving data for both models:
The second model manages the passwords for the user name. These data are stored encrypted into a different file in order to prevent access to see the password. Both classes have Data Annotations to describe label fields,keys, required data, etc. In this link you could find info about regular expressions to validate data entered in data fields.
In my example I need to use data from both classes(models) when a new user is being registered, that is, enter username, password and all the other data, so I need to pass both models to the same view, in which data could be entered. This is the code for the view, using data from both models:
An this is how this view is showed in the browser:
MVC allows you to pass only one model to a View, but you can use different ways to pass more than one. The way I do it, is using an auxiliary class in which you can put all the models you want to pass to the view. So this is the additional class including the two classes mentioned above:
And this is the method associated with the view, saving data for both models:
Etiquetas:
ASP.Net,
C#,
Entity Framework,
MVC,
Programming,
Visual Studio
lunes, 3 de marzo de 2014
ASP.NET Setting and reading a cookie
The first method creates an instance of a Cookie for the user "agivenuser", for this example, we want to store the name, second name, and date of creation. Also we need to set the expiration date for the cookie, in this case only three days. This means that after three days without the user entering the system the cookie will be deleted.
protected void btnSetcookie_Click(object sender, EventArgs e)
{
//Create an instance of a cookie.
HttpCookie userCookie = new HttpCookie("agivenuser");
//Store data
userCookie["Name"] = txbxName.Text;
userCookie["SecondName"]= txbxApellidos.Text;
userCookie["Date"]=DateTime.Now.ToShortDateString();
//Set expiration dates.
userCookie.Expires = DateTime.Now.AddDays(3);
//Store the cookie in the user machine.
Response.Cookies.Add(userCookie);
}
And this method is used to read the cookie for the user
protected void btnGetCookieData_Click(object sender, EventArgs e)
{
if (Request.Cookies["USER"] == null)
{
Response.Write("USER has no cookies");
}
else
{
HttpCookie aCookie=Request.Cookies["USER"];
Response.Write("Cookie stored :" + aCookie["Name"] + " " + aCookie["SecondName"]
+ " " + aCookie["Date"] + " Expires :" + aCookie.Expires.ToString() );
}
}
domingo, 2 de marzo de 2014
sábado, 1 de marzo de 2014
C# Reflection: How to obtain fields, properties, etc.. from a Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Clases
{
class AClassExample
{
private int _Id;
private string _Name;
private DateTime _Date;
public int Id
{
get { return _Id; }
set { _Id = value; }
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public DateTime Date
{
get { return _Date; }
set { _Date = value; }
}
public AClassExample(int anId, string aName, DateTime aDate)
{
_Id = anId;
_Name = aName;
_Date = aDate;
}
}
class Program
{
public static void printObject(AClassExample aClass)
{
Type myObjectType = typeof(AClassExample);
//Get Fields from object
System.Reflection.FieldInfo[] fieldInfo = myObjectType.GetFields(System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public );
//The Binding flags allows to show the private fields
foreach (System.Reflection.FieldInfo field in fieldInfo)
Console.WriteLine(field.Name + ':' + field.GetValue(aClass));
//Getting Properties from object
System.Reflection.PropertyInfo[] propInfo = myObjectType.GetProperties();
foreach (System.Reflection.PropertyInfo prop in propInfo)
Console.WriteLine(prop.Name + ':' + prop.GetValue(aClass));
}
static void Main(string[] args)
{
AClassExample example = new AClassExample(2,"Un nombre",DateTime.Now);
printObject(example);
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Clases
{
class AClassExample
{
private int _Id;
private string _Name;
private DateTime _Date;
public int Id
{
get { return _Id; }
set { _Id = value; }
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public DateTime Date
{
get { return _Date; }
set { _Date = value; }
}
public AClassExample(int anId, string aName, DateTime aDate)
{
_Id = anId;
_Name = aName;
_Date = aDate;
}
}
class Program
{
public static void printObject(AClassExample aClass)
{
Type myObjectType = typeof(AClassExample);
//Get Fields from object
System.Reflection.FieldInfo[] fieldInfo = myObjectType.GetFields(System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public );
//The Binding flags allows to show the private fields
foreach (System.Reflection.FieldInfo field in fieldInfo)
Console.WriteLine(field.Name + ':' + field.GetValue(aClass));
//Getting Properties from object
System.Reflection.PropertyInfo[] propInfo = myObjectType.GetProperties();
foreach (System.Reflection.PropertyInfo prop in propInfo)
Console.WriteLine(prop.Name + ':' + prop.GetValue(aClass));
}
static void Main(string[] args)
{
AClassExample example = new AClassExample(2,"Un nombre",DateTime.Now);
printObject(example);
Console.ReadLine();
}
}
}
Suscribirse a:
Entradas (Atom)