Translate

martes, 24 de diciembre de 2013

Week #3 (09/12/13 - 15/12/13)



I´ve forgot to post the numbers for the last week. Here they are.

Total Time: 10:50:08
  • Swim: 1:59:24
  • Bike: 5:40:13
  • Run: 3:00:31
Total Distance: 182,90 km
  • Swim: 5,10km 
  • Bike: 143,50km 
  •  Run: 34,30km

ASP.Net Entity Framework Add, Insert, Edit, Delete and Select



Here you can see how to work with ADO.NET Entity Framework and hand-coded access to data.

This code is implemented in the code-behind of the page, and associated to the buttons added to create a new element, edit n existing, save, cancel and delete.

For simplicity I am supposing that data entered in text boxes is correct, otherwise you can control using validation controls associated to the text boxes.

Saving a New or Edited existing: (Associated to Save Button)

         using (TheClubBDEntities myEntities = new TheClubBDEntities())
        {
            RaceType aRaceType;
            if (_Id == -1) //Save new
            {
                aRaceType = new RaceType();
                myEntities.RaceTypes.AddObject(aRaceType);
            }
            else
            { //Update existing
                aRaceType = (from r in myEntities.RaceTypes
                                       where r.Id == _Id
                                       select r).Single();             
            }
            aRaceType.Name = txbxNombre.Text;
            aRaceType.PuntosPart = Int32.Parse(txbxPuntos.Text);
            aRaceType.Memo = txbxMemo.Text;
            LastPos = _Id;  // Used to control position in the data base.
            myEntities.SaveChanges();

            GridView1.DataBind();  // To refresh data into GridView

            setNormalMode();  //Disable save button and put textboxes in readonly mode.
        }

Deleting existing:

        using (TheClubBDEntities myEntities = new TheClubBDEntities())
        {
            var aRaceType = (from r in myEntities.RaceTypes
                             where r.Id == _Id
                             select r).Single();


            myEntities.RaceTypes.DeleteObject(aRaceType);
            myEntities.SaveChanges();
        }
        GridView1.DataBind();
        setNormalMode();

Cancel editing or adding a new:

        using (TheClubBDEntities myEnt = new TheClubBDEntities())
        {
            var aRaceType = (from rt in myEnt.RaceTypes
                                         orderby rt.Name ascending
                                        where rt.Id == LastPos
                                        select rt).SingleOrDefault();

            if (aRaceType == null)
            {
                _Id = -1;
                LastPos = -1;
            }
            else
            {
                _Id = aRaceType.Id;
                txbxNombre.Text = aRaceType.Name;
                txbxPuntos.Text = aRaceType.PuntosPart.ToString();
                txbxMemo.Text = aRaceType.Memo;
            }
            setNormalMode();
        }

Selecting from the GridView and putting data into textboxes:

        _Id = Int32.Parse(GridView1.SelectedRow.Cells[1].Text);
        LastPos = _Id;
        txbxNombre.Text = GridView1.SelectedRow.Cells[2].Text;
        txbxPuntos.Text = GridView1.SelectedRow.Cells[3].Text;
        txbxMemo.Text = GridView1.SelectedRow.Cells[4].Text;
        setNormalMode();

Moving to first:

        using (TheClubBDEntities myEnt = new TheClubBDEntities())
        {

            var aRaceType = (from rt in myEnt.RaceTypes
                                         orderby rt.Name ascending
                                         select rt).FirstOrDefault();

            if (aRaceType == null)
                _Id = -1;
            else
            {               
                _Id = aRaceType.Id;
                LastPos = _Id;
                txbxNombre.Text = aRaceType.Name;
                txbxPuntos.Text = aRaceType.PuntosPart.ToString();
                txbxMemo.Text = aRaceType.Memo;
            }
        }

Loading the page:

        using (TheClubBDEntities myEnt = new TheClubBDEntities())
        {
            if (!Page.IsPostBack)
            {
                var aRaceType = (from rt in myEnt.RaceTypes
                                             select rt).FirstOrDefault();

                if (aRaceType == null)
                {
                    _Id = -1;
                    LastPos = -1;
                }
                else
                {
                    _Id = aRaceType.Id;
                    LastPos = _Id;
                    txbxNombre.Text = aRaceType.Name;
                    txbxPuntos.Text = aRaceType.PuntosPart.ToString();
                    txbxMemo.Text = aRaceType.Memo;
                }
            }
        }



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.




jueves, 12 de diciembre de 2013

Week Number 2 (2/12/13 to 8/12/13)


Second week completed. Starting to feel well in the water, but there´s steel a lot of work to do. Very nice feeling over the bike,and also during running sessions, feeling faster and stronger. Need to improve in my swimming sessions.

Numbers are:

Total Time: 10:58:38
  • Swim: 1:38:59 
  • Bike: 6:54:39 
  • Run: 2:25:00 
Total Distance: 202,43km
  • Swim: 4,05km 
  • Bike: 168,88km 
  •  Run: 29,50km

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:



jueves, 5 de diciembre de 2013

In the middle of the storm

Place/Lugar: Valdevaqueros, Tarifa, Spain.
Board & Sail / Tabla y vela: JP 84l / HotSails 3,7m
 
 
 Only a few seconds, and you would have your board completely buried in the sand.  

This day the wind was very strong, with my anemometer I could measure peaks of about 40 knots. A few people in the beach only, the sand was been strongly carried by the wind, and it was imposible to stand there for a minute. 

Nor in the water the situation was comfortable, the sea appeared to be boiling...but this is it, pure state windsurfing, ... Tarifa in my mind!!

lunes, 2 de diciembre de 2013

ASP.Net: Habilitar Temas en un web Site

Supongamos que tenemos un sitio web al que queremos dotar de varias plantillas de visualización que permita al usuario cambiar de uno a otra de manera dinámica.

Para ello necesitaremos varios elementos:

  • Una Master Page de la que todas nuestras páginas cargen la distribución de la página.
  • Un CSS file para cada una de las plantillas o temas que queramos crear. 
  • Una carpeta de estilos, APP_Themes donde meteremos a su vez una carpeta para cada uno de los temas creados. Igualmente en cada una de estas carpetas meteremos el CSS correspondiente así como aquellas imágenes que queramos usar con el tema.
  • Una BasePage, es decir una clase que crearemos nosotros, que derivará de la clase genérica System.Web.UI.Page, y que será la Parent class de todos los Web Forms que creemos, de esta manera podremos añadir control a los WebForms a lo largo de su Life Cycle, por ejemplo controlando eventos como PreRender, PreInit, etc... Esta BasePage, la almacenaremos en la carpeta App_Code del Site


Una vez creado esto necesitaremos un DropDownList que muestre nuestros temas disponibles, y que al seleccionar uno, cree una Cookie, que guardará en el ordenador del browser cliente el dato del tema seleccionado para posteriores accesos.

El DropDownList los colocaremos en este caso en un sideBar de la MasterPage, de forma que todas las páginas lo etngan disponible. Para ello arrastramos un DropDownList de la ToolBar a la master page en Design Mode, y configuraremos su propiedad AutoPostBack a Enable, e igualmente en la lista de items, añadiremos nuestros temas.


El siguiente paso sería asociar código al envento SelectedIndexChanged del DropDownList para que cree una Cookie en el ordenador cliente que almacene el nombre del tema escogido. Para ello hacemos doble click sobre el componente y en el evento creado añadimos el siguiente código:


 De esta manera se crea una Cóokie, que es enviada al Server cada vez que el browser del equipo cliente hace una petición. Si no se usa se borrará a los tres meses.

Igualmente tenemos que crear código, que lea la Cookie, y asigne el valor guardado al DropDownList, para ello usaremos el evento asociado con la carga de la Página, Page_Load, al que le añadiremos:


En este punto tenemos implementado el poder escoger uno de los temas, guardar el tema escogido en una Cookie en el equipo cliente, y al cargar la página, que el DropDownList tenga seleccionado el tema escogido la última vez. Todavía no hemos hecho que se aplique el tema escogido al cargar la página.

Esto lo haremos usando el evento PreInit que nos permitirá cargar el tema escogido en la Master Page durante el proceso de carga de la página. Crearemos el código en el evento PreInit de la página que asigna el tema escogido, y además tendremos que añadir el evento al constructor de la página.


Y listo. Una última precaución. Si has fijado el tema en el archivo web.config y además del tema has fijado el StyleSheetThemes, puede ocurrir que al elegir un tema se mezceln dos. En ese caso elimina el StyleSheetThemes del fichero Web.Config: