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

lunes, 26 de diciembre de 2016

El Libro del Día: WebGL Programming Guide

El Libro del Día: 2016-12-26

Titulo: WebGL Programming Guide
Autor: Kouichi Matsuda, Rodger Lea
Editorial: Addison Wesley
Nro Paginas: 544

Capítulos:
1. Overview of WebGL
2. Your First Step with WebGL
3. Drawing and Transforming Triangles
4. More Transformations and Basic Animation
5. Using Colors and Texture Images
6. The OpenGL ES Shading Language (GLSL ES)
7. Toward the 3D World
8. Lighting Objects
9. Hierarchical Objects
10. Advanced Techniques
Anexos:
A. No Need to Swap Buffers in WebGL
B. Built-in Functions of GLSL ES 1.0
C. Projection Matrices
D. WebGL/OpenGL: Left or Right Handed
E. The Inverse Transpose Matrix
F. Load Shader Programs from Files
G. World Coordinate System Versus Local Coordinate System
H. Web Browser Settings for WebGL

Descarga:
WebGL_Programming_Guide

jueves, 13 de agosto de 2015

El Libro del Día: HTML5 Game Development by Example

El Libro del Día: 2015-08-13

Titulo: HTML5 Game Development by Example
Autor: Makzan
Editorial: Packt
Nro Paginas: 354

Capítulos:
Chapter 1: Introducing HTML5 Games
Chapter 2: Getting Started with DOM-based Game Development
Chapter 3: Building a Card-matching Game in CSS3
Chapter 4: Building the Untangle Game with Canvas and the Drawing API
Chapter 5: Building a Canvas Game's Masterclass
Chapter 6: Adding Sound Effects to Your Games
Chapter 7: Saving the Game's Progress
Chapter 8: Building a Multiplayer Draw-and-Guess Game with WebSockets
Chapter 9: Building a Physics Car Game with Box2D and Canvas
Chapter 10: Deploying HTML5 Games

Descarga:
HTML5_Game_Development_by_Example

martes, 11 de agosto de 2015

El Libro del Día: Learning ExtJS

El Libro del Día: 2015-08-11

Titulo: Learning ExtJS (Fourth Edition)
Autor: Carlos A. Méndez, Crysfel Villa, Armando Gonzalez
Editorial: Packt
Nro Paginas: 453

Capítulos:
Chapter 1: An Introduction to Ext JS 5
Chapter 2: The Core Concepts
Chapter 3: Components and Layouts
Chapter 4: It's All about the Data
Chapter 5: Buttons and Toolbars
Chapter 6: Doing It with Forms
Chapter 7: Give Me the Grid
Chapter 8: DataViews and Templates
Chapter 9: The Tree Panel
Chapter 10: Architecture
Chapter 11: The Look and Feel
Chapter 12: Responsive Configurations and Tablet Support
Chapter 13: From Drawing to Charting
Chapter 14: Finishing the Application
Chapter 15: What's Next?

Descarga:
Learning_ExtJS

lunes, 6 de julio de 2015

El Libro del Día: Advanced Game Design with HTML5 and JavaScript

El Libro del Día: 2015-07-06

Titulo: Advanced Game Design with HTML5 and JavaScript
Autor: Rex van der Spuy
Editorial: Apress
Nro Paginas: 540

Capítulos:
Chapter 1: Level Up
Chapter 2: The Canvas Drawing API
Chapter 3: Working with Game Assets
Chapter 4: Making Sprites and a Scene Graph
Chapter 5: Making Things Move
Chapter 6: Interactivity
Chapter 7: Collision Detection
Chapter 8: Juice It Up
Chapter 9: Sound with the Web Audio API
Chapter 10: Tweening
Chapter 11: Make Your Own Game Engine
Appendix A: Vectors for Movement and Collision Detection

Descarga:
Advanced_Game_Design_with_HTML5_and_JavaScript

martes, 24 de marzo de 2015

El Demo del Día: Graficar Datos en el Servidor en ASP.NET MVC

Graficar Datos en el Servidor en ASP.NET MVC con llamada asíncrona usando Ajax Form y Vista Parcial

Requerimiento

Se desea crear una aplicación web que permita consultar los productos por categoría y mostrar los datos mas gráficos de diferentes tipos: Barras, Columnas, Lineas y Pie, pero el requisito es que sea conectado o en línea, es decir, el filtro por categoría debe hacerse directo de la base de datos y el gráfico debe crearse dinámicamente en el servidor web.

Solución

- Crear una aplicación en ASP.NET MVC con un método de acción que se conecte a la BD para traer la lista de categorías mas los tipos de gráficos.
- Crear un formulario MVC Ajax que realice una llamada asíncrona cada vez que se selecciona una categoría que llama a una acción que haga la consulta en base de datos y que cree el gráfico dinámicamente devolviendo una vista parcial.
- Para crear los diferentes tipos de gráficos usaremos la librería System.Drawing y el gráfico lo almacenaremos en un MemoryStream, a partir del cual obtendremos su array de bytes y lo almacenaremos en un ViewBag llamado Imagen con el contenido de la imagen en formato base64.

Crear los Procedimientos Almacenados en la Base de Datos Northwind de SQL Server

Para el ejemplo usaremos la Base de Datos Northwind de SQL Server, en la cual crearemos los siguientes Procedimiento almacenado:

Create Procedure [dbo].[uspCategoriesListar]
As
Select CategoryID,CategoryName From Categories
Go

Create Procedure [dbo].[uspProductsListarPorCategoria]
@CategoryId int
As
Select ProductID,ProductName,SupplierID,
CategoryID,UnitPrice,UnitsInStock
From Products
Where CategoryId=@CategoryId

Crear la Librería de Clases de Entidades del Negocio

Crear la librería de clases llamada: "Northwind.Librerias.EntidadesNegocio" y agregar la clase "beCategoria.cs":

namespace Northwind.Librerias.EntidadesNegocio
{
    public class beCategoria
    {
        public int IdCategoria { get; set; }
        public string Nombre { get; set; }
    }
}

Agregar otra clase a la librería llamada "beProducto.cs":

namespace Northwind.Librerias.EntidadesNegocio
{
    public class beProducto
    {
        public int IdProducto { get; set; }
        public string Nombre { get; set; }
        public int IdProveedor { get; set; }
        public int IdCategoria { get; set; }
        public decimal PrecioUnitario { get; set; }
        public short Stock { get; set; }
    }
}

Grabar y compilar la Librería de Entidades del Negocio.

Crear la Librería de Acceso a Datos

Crear la librería de clases llamada: "Northwind.Librerias.AccesoDatos", referenciar a la librería de clases de entidades creada anteriormente y agregar la clase "daCategoria.cs" y escribir el siguiente código:

using System;
using System.Collections.Generic; //List
using System.Data; //CommandType, CommandBehavior
using System.Data.SqlClient; //SqlConnection, SqlCommand, SqlDataReader
using Northwind.Librerias.EntidadesNegocio; //beCategoria

namespace Northwind.Librerias.AccesoDatos
{
    public class daCategoria
    {
        public List<beCategoria> listar(SqlConnection con)
        {
            List<beCategoria> lbeCategoria = null;

            SqlCommand cmd = new SqlCommand("uspCategoriesListar", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataReader drd = cmd.ExecuteReader();
            if (drd != null)
            {
                lbeCategoria = new List<beCategoria>();
                beCategoria obeCategoria;
                int posIdCat = drd.GetOrdinal("CategoryID");
                int posNomCat = drd.GetOrdinal("CategoryName");
                while (drd.Read())
                {
                    obeCategoria = new beCategoria();
                    obeCategoria.IdCategoria = drd.GetInt32(posIdCat);
                    obeCategoria.Nombre = drd.GetString(posNomCat);
                    lbeCategoria.Add(obeCategoria);
                }
                drd.Close();
            }
            return (lbeCategoria);
        }
    }
}

Agregar una nueva clase a la librería llamada "daProducto.cs" y escribir el siguiente código:

using System;
using System.Collections.Generic; //List
using System.Data; //CommandType, CommandBehavior
using System.Data.SqlClient; //SqlConnection, SqlCommand, SqlDataReader
using Northwind.Librerias.EntidadesNegocio; //beProducto

namespace Northwind.Librerias.AccesoDatos
{
    public class daProducto
    {
        public List<beProducto> listarPorCategoria(SqlConnection con,int idCategoria)
        {
            List<beProducto> lbeProducto = null;

            SqlCommand cmd = new SqlCommand("uspProductsListarPorCategoria", con);
            cmd.CommandType = CommandType.StoredProcedure;

            SqlParameter par = cmd.Parameters.Add("@CategoryId", SqlDbType.Int);
            par.Direction = ParameterDirection.Input;
            par.Value = idCategoria;

            SqlDataReader drd = cmd.ExecuteReader(CommandBehavior.SingleResult);
            if (drd != null)
            {
                lbeProducto = new List<beProducto>();
                int posIdProducto = drd.GetOrdinal("ProductID");
                int posNombre = drd.GetOrdinal("ProductName");
                int posIdProveedor = drd.GetOrdinal("SupplierID");
                int posIdCategoria = drd.GetOrdinal("CategoryID");
                int posPrecioUnitario = drd.GetOrdinal("UnitPrice");
                int posStock = drd.GetOrdinal("UnitsInStock");
                beProducto obeProducto;
                while (drd.Read())
                {
                    obeProducto = new beProducto();
                    obeProducto.IdProducto = drd.GetInt32(posIdProducto);
                    obeProducto.Nombre = drd.GetString(posNombre);
                    obeProducto.IdProveedor = drd.GetInt32(posIdProveedor);
                    obeProducto.IdCategoria = drd.GetInt32(posIdCategoria);
                    obeProducto.PrecioUnitario = drd.GetDecimal(posPrecioUnitario);
                    obeProducto.Stock = drd.GetInt16(posStock);
                    lbeProducto.Add(obeProducto);
                }
                drd.Close();
            }

            return (lbeProducto);
        }
    }
}

Grabar y compilar la librería de acceso a datos creada.

Crear la Librería de Reglas del Negocio

Crear la librería de clases llamada: "Northwind.Librerias.ReglasNegocio", referenciar a la librería de clases de entidades y también a la de acceso a datos, luego agregar la clase "brCategoria.cs" y escribir el siguiente código:

using System;
using System.Data.SqlClient; //SqlConnection
using System.Collections.Generic; //List
using Northwind.Librerias.EntidadesNegocio; //beCategoria
using Northwind.Librerias.AccesoDatos; //daCategoria

namespace Northwind.Librerias.ReglasNegocio
{
    public class brCategoria
    {
        public List<beCategoria> listar()
        {
            List<beCategoria> lbeCategoria = null;
            string CadenaConexion = ConfigurationManager.ConnectionStrings["conNW"]
                                                     .ConnectionString;
            using (SqlConnection con = new SqlConnection(CadenaConexion))
            {
                try
                {
                    con.Open();
                    daCategoria odaCategoria = new daCategoria();
                    lbeCategoria = odaCategoria.listar(con);
                }
                catch (SqlException ex)
                {
                    //grabarLog(ex);
                }
                catch (Exception ex)
                {
                    //grabarLog(ex);
                }
            } //con.Close(); con.Dispose();
            return (lbeCategoria);
        }
    }
}

Agregar una nueva clase a la librería llamada "brProducto.cs" y escribir el siguiente código:

using System;
using System.Data.SqlClient; //SqlConnection
using System.Collections.Generic; //List
using Northwind.Librerias.EntidadesNegocio; //beProducto
using Northwind.Librerias.AccesoDatos; //daProducto

namespace Northwind.Librerias.ReglasNegocio
{
    public class brProducto
    {
        public List<beProducto> listarPorCategoria(int idCategoria)
        {
            List<beProducto> lbeProducto = null;
            string CadenaConexion = ConfigurationManager.ConnectionStrings["conNW"]
                                                     .ConnectionString;
            using (SqlConnection con = new SqlConnection(CadenaConexion))
            {
                try
                {
                    con.Open();
                    daProducto odaProducto = new daProducto();
                    lbeProducto = odaProducto.listarPorCategoria(con,idCategoria);
                }
                catch (SqlException ex)
                {
                    //grabarLog(ex);
                }
                catch (Exception ex)
                {
                    //grabarLog(ex);
                }
            } //con.Close(); con.Dispose();
            return (lbeProducto);
        }
    }
}

Nota: También es necesario hacer una referencia a la librería "System.Configuration" para leer la cadena de conexión definida en la aplicación.

Grabar la librería de reglas de negocio creada y compilarla.

Crear una Aplicación Web de ASP.NET MVC4 en C#

Seleccionar un nuevo proyecto de tipo: "Aplicación web de ASP.NET MVC4" y escribir como nombre "Demo10", luego seleccionar la opción "Vacio" y como motor de vista "Razor" y "Aceptar".

Nota: Antes de iniciar con el código hay que referenciar a las librerías creadas, sobre todo a la Regla de Negocio y las Entidades de Negocio.

Crear un Controlador para el Producto

Clic derecho a la carpeta Controllers y seleccionar "Agregar" y luego "Controlador", llamarle al archivo "ProductoController.cs" y en opciones de plantillas dejarlo en plantilla vacía (Vaciar Controlador MVC). Luego escribir el siguiente código:

using System;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Northwind.Librerias.EntidadesNegocio;
using Northwind.Librerias.ReglasNegocio;

namespace Demo10.Controllers
{
    public class ProductoController : Controller
    {        
        public ActionResult Lista()
        {
            brCategoria obrCategoria = new brCategoria();
            List<beCategoria> lbeCategoria = obrCategoria.listar();
            ViewBag.Categorias = lbeCategoria;
            List<string> tiposGrafico = new List<string>();
            tiposGrafico.Add("Barras");
            tiposGrafico.Add("Columnas");
            tiposGrafico.Add("Lineas");
            tiposGrafico.Add("Pie");
            ViewBag.TiposGrafico = tiposGrafico;
            return View();
        }

        public PartialViewResult ConsultaGrafico(int idCategoria,string tipoGrafico)
        {
            brProducto obrProducto = new brProducto();
            List<beProducto> lbeProducto = obrProducto.listarPorCategoria(idCategoria);
            int ancho = 800;
            int alto = 500;
            Bitmap bmp = new Bitmap(ancho, alto);
            Graphics grafico = Graphics.FromImage(bmp);
            Rectangle rect = new Rectangle(0, 0, ancho, alto);
            LinearGradientBrush degradado = new LinearGradientBrush
            (rect, Color.Aqua, Color.Blue, LinearGradientMode.BackwardDiagonal);
            grafico.FillRectangle(degradado, rect);
            int x, y;
            Font fuente=new Font("Arial",10);
            Pen lapiz=new Pen(Brushes.Yellow,5);
            StringFormat formato = new StringFormat(StringFormatFlags.DirectionVertical);
            switch (tipoGrafico)
            {
                case "Barras":
                    x = 20;
                    y=20;
                    foreach(beProducto obeProducto in lbeProducto)
                    {
                        x = 20;
                        grafico.DrawString(obeProducto.Nombre, fuente, 
                        Brushes.White, x, y);
                        x = 200;
                        rect = new Rectangle(x, y, obeProducto.Stock, 20);
                        grafico.FillRectangle(Brushes.Yellow, rect);
                        x = 220 + obeProducto.Stock;
                        grafico.DrawString(obeProducto.Stock.ToString(), fuente, 
                        Brushes.White, x, y);
                        y += (int)fuente.GetHeight() + 20;
                    }
                    break;
                case "Columnas":
                    x = 20;
                    y=350;
                    foreach(beProducto obeProducto in lbeProducto)
                    {
                        grafico.DrawString(obeProducto.Nombre, fuente, 
                        Brushes.White, x, y, formato);
                        alto = 340 - obeProducto.Stock;
                        rect = new Rectangle(x, alto, 20, obeProducto.Stock);
                        grafico.FillRectangle(Brushes.Yellow, rect);
                        grafico.DrawString(obeProducto.Stock.ToString(), fuente, 
                        Brushes.White, x, alto - 20);
                        x += 50;
                    }
                    break;
                case "Lineas":
                    x = 20;
                    y=350;
                    for(int i=0;i<lbeProducto.Count;i++)
                    {
                        grafico.DrawString(lbeProducto[i].Nombre, fuente, 
                        Brushes.White, x, y, formato);
                        if (i < lbeProducto.Count - 1)
                        {
                            grafico.DrawLine(lapiz, new Point(x, 340 - lbeProducto[i].Stock), 
                            new Point(x + 50, 340 - lbeProducto[i + 1].Stock));
                        }
                        grafico.DrawString(lbeProducto[i].Stock.ToString(), fuente, 
                        Brushes.White, x, 320 - lbeProducto[i].Stock);
                        x += 50;
                    }
                    break;
                case "Pie":
                    decimal total = lbeProducto.Sum(obj => obj.Stock);
                    float anguloInicio = 00.0F;
                    float anguloFin;
                    rect = new Rectangle(100, 10, ancho-200, alto - 20);
                    int R, G, B;
                    Color color;
                    Random oAzar = new Random();
                    for (int i = 0; i < lbeProducto.Count; i++)
                    {
                        R = oAzar.Next(255);
                        G = oAzar.Next(255);
                        B = oAzar.Next(255);
                        color = Color.FromArgb(R, G, B);
                        anguloFin = (float)((lbeProducto[i].Stock * 360) / total);
                        grafico.FillPie(new SolidBrush(color), rect, anguloInicio, anguloFin);
                        anguloInicio += anguloFin;
                    }
                    break;
            }
            byte[] imagen=null;
            using (MemoryStream ms = new MemoryStream())
            {
                bmp.Save(ms, ImageFormat.Png);
                imagen = ms.ToArray();
            }
            ViewBag.Imagen = String.Format("data:image/png;base64,{0}",
            Convert.ToBase64String(imagen));
            return PartialView("Grafico", lbeProducto);
        }
    }
}

Nota: Para el gráfico de Pie se esta creando un color al azar para cada producto.

Crear una Hoja de Estilos para la Vista

Primero crear una carpeta llamada "Content", luego clic derecho "Agregar" y luego "Hoja de estilos" y como nombre llamarle "ACME.css" y escribir el siguiente código:

body {
    background-color:gray;
}
.Titulo {
    background-color:black;
    color:white;
    font-size:larger;
}
.Subtitulo {
    background-color:white;
    color:black;
    font-size:large;
}
.AnchoTotal {
    width:100%;
}
.Centrado {
    text-align:center;
}
.FilaCabecera {
    background-color:lightgray;
    color:black;
}
.FilaDatos {
    background-color:white;
    color:black;
}

Crear la Vista Productos para mostrar los datos

Ir al controlador y ubicarse sobre el método "Lista" (acción), clic derecho y seleccionar "Agregar vista", desmarcar todos los check ya que es una vista sin tipo y escribir el siguiente código:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Lista</title>
    <link href="~/Content/ACME.css" rel="stylesheet" />
</head>
<body>
    <div>
        @using (Ajax.BeginForm("ConsultaGrafico", "Producto", 
         new AjaxOptions { HttpMethod = "get", InsertionMode = InsertionMode.Replace, 
         UpdateTargetId = "divGrafico" }, new { id = "frmGrafico" }))
        {
        <table class="AnchoTotal">
            <tr class="Titulo">
                <td colspan="2">Gráficar Datos en el Servidor en ASP.NET MVC 
                 con llamada asíncrona usando Ajax Form y Vista Parcial</td>
            </tr>
            <tr class="Subtitulo">
                <td colspan="2">Consulta de Productos por Categoría</td>
            </tr>
            <tr>
                <td style="width:40%">Seleccione la Categoría</td>
                <td style="width:60%">Seleccione el Tipo de Gráfico</td>
            </tr>
            <tr>
                <td>
                    @Html.DropDownList("idCategoria",
                     new SelectList(ViewBag.Categorias,"IdCategoria","Nombre"))
                </td>
                <td>
                    @Html.DropDownList("tipoGrafico",
                     new SelectList(ViewBag.TiposGrafico))
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <div id="divGrafico"></div>
                </td>
            </tr>
        </table>
        }
    </div>
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script src="~/Scripts/Rutinas.js"></script>
    <script>iniciarLista();</script>
</body>
</html>

Nota: Es mejor colocar los archivos de JavaScript al final de la página para renderizar mas rápido.

Crear la Vista Parcial con la Consulta y el Gráfico a Mostrar

Ir nuevamente al controlador y ubicarse sobre el método "Lista" (acción), clic derecho y seleccionar "Agregar vista", cambiar de nombre a la vista por "Grafico", seleccionar el check "Crear como vista parcial" y escribir el siguiente código:

@using Northwind.Librerias.EntidadesNegocio
@model List<beProducto>
<table class="AnchoTotal">
    <tr>
        <td style="vertical-align:top">
            <table class="AnchoTotal">
                <tr class="FilaCabecera">
                    <td style="width:200px">Nombre del Producto</td>
                    <td style="width:10px">Stock</td>
                </tr>
                @foreach (beProducto obeProducto in Model)
                {
                    <tr class="FilaDatos">
                        <td>@obeProducto.Nombre</td>
                        <td>@obeProducto.Stock</td>
                    </tr>
                }
            </table>
        </td>
        <td>
            <img src="@ViewBag.Imagen" width="800" height="500" />
        </td>
    </tr>
</table>

Crear el archivo JavaScript con el código cliente

Antes que nada crear una carpeta llamada "Scripts" y arrastrar del explorador de Windows el archivo de jQuery: "jquery-1.8.2.min.js" y "jquery.unobtrusive-ajax.min.js" (necesario para el Ajax Form), luego agregar un archivo de JavaScript llamado "Rutinas.js" y escribir el siguiente código:

function iniciarLista() {
    $("#frmGrafico").submit();
    var cboIdCategoria = document.getElementById("idCategoria");
    cboIdCategoria.onchange = function () { llamadaAsincrona(); };
    var cboTipoGrafico = document.getElementById("tipoGrafico");
    cboTipoGrafico.onchange = function () { llamadaAsincrona(); };
    function llamadaAsincrona() {
        $("#frmGrafico").submit();
    }
}

Nota: Cuando se carga la página se esta haciendo un submit al formulario "frmGrafico" via jQuery el cual es asíncrono por que el formulario en un Ajax Form. También ocurre lo mismo al seleccionar una categoría del combo.

Modificar el archivo web.config para incluir la cadena de conexión

<configuration>
  <connectionStrings>
    <add name="conNW" providerName="SQLServer"
         connectionString="uid=UsuarioNW;pwd=123456;
         data source=DSOFT\Sqlexpress;database=Northwind"/>
  </connectionStrings>
  .....
</configuration>

Configurar el inicio y ejecutar la aplicación web

Para probar la aplicación web debemos configurar el inicio para lo cual nos vamos a la carpeta "App_Start" y abrimos el archivo "RouteConfig.cs" cambiando el nombre del controlador y la acción tal como sigue: controller = "Producto", action = "Lista".

Ejecución y Pruebas de la Aplicación Web ASP.NET MVC

Finalmente, grabar y pulsar F5 para ejecutar la aplicación, mostrándose el resultado similar a la siguiente figura:


Por defecto se muestra la categoría "Bebidas" y en el tipo de gráfico "Barras", cambiar el tipo de gráfico a "Columnas" y se verá la siguiente figura:


Probar ahora con el gráfico de "Lineas" y se mostrará algo similar a la siguiente figura:


Finalmente, cambiar el tipo de gráfico a "Pie" y se verá lo siguiente:


Nota: En el gráfico de Pie falta agregar una leyenda para distinguir cada producto de acuerdo al color generado. Esto queda como tarea para que aprendan mas sobre Drawing.

Comentario Final

En este post hemos visto como trabajar en forma conectada, y también hemos aprendido a crear gráficos dinámicamente usando la librería System.Drawing y las clases: Bitmap, Graphics, Rectangle, Font, Pen, StringFormat, Color, SolidBrush, las enumeraciones: Brushes y StringFormatFlags, también el Namespace: System.Drawing.Drawing2D para usar la clase: LinearGradientBrush (degradado).

En un anterior post vimos como crear gráficos en el Cliente usando HTML5 Canvas con JSON:

Aunque en apariencia los Demos son similares el anterior es desconectado de la base de datos y del servidor web, este demo es conectado o en línea para ver los últimos datos, por ejemplo muy útil para reportes gerenciales en línea.

Descarga del código

Video del Demo

Nota: El video es muy similar al código presentado en el Demo, pero la versión original era desconectada del servidor de datos y usaba una sesión, en cambio el demo es totalmente conectado, la diferencia solo es en el controller y es mínima.

jueves, 12 de febrero de 2015

El Libro del Día: HTML5 Up and Running

El Libro del Día: 2015-02-12

Titulo: HTML5 Up and Running
Autor: Mark Pilgrim
Editorial: O'Reilly
Nro Paginas: 222

Capítulos:
1. How Did We Get Here?
2. Detecting HTML5 Features
3. What Does It All Mean?
4. Let’s Call It a Draw(ing Surface)
5. Video on the Web
6. You Are Here (And So Is Everybody Else)
7. The Past, Present, and Future of Local Storage for Web Applications
8. Let’s Take This Offline
9. A Form of Madness
10. “Distributed,” “Extensibility,” and Other Fancy Words
Appendix: The All-in-One Almost-Alphabetical Guide to Detecting Everything

Descarga:
HTML5_Up_and_Running

martes, 27 de enero de 2015

El Libro del Día: Ext JS in Action

El Libro del Día: 2015-01-27

Titulo: Ext JS in Action (Second Edition)
Autor: Jesus Garcia, Grgur Grisogono, Jacob Andresen
Editorial: Manning
Nro Paginas: 408

Capítulos:
PART 1 INTRODUCTION TO EXT JS 4.0
1 A framework apart
2 DOM manipulation
3 Components and containers
PART 2 EXT JS COMPONENTS
4 Core UI components
5 Exploring layouts
6 Forms in Ext JS
7 The data store
8 The grid panel
9 Taking root with trees
10 Drawing and charting
11 Remote method invocation with Ext Direct
12 Drag-and-drop
PART 3 BUILDING AN APPLICATION
13 Class system foundations
14 Building an application

Descarga:
ExtJS_in_Action

domingo, 4 de enero de 2015

El Libro del Día: Learning Raphaël JS Vector Graphics

El Libro del Día: 2015-01-04

Titulo: Learning Raphaël JS Vector Graphics
Autor: Damian Dawber
Editorial: Packt
Nro Paginas: 130

Capítulos:
Chapter 1: The Graphical Web
Chapter 2: Basic Drawing with Raphaël
Chapter 3: Drawing Paths
Chapter 4: Transformations and Event Handling
Chapter 5: Vector Animation
Chapter 6: Working with Existing SVGs
Chapter 7: Creating a Suite of Social Media Visualizations

Descarga:
Learning_Raphael_JS_Vector_Graphics

jueves, 25 de diciembre de 2014

El Libro del Día: HTML5 Canvas Cookbook

El Libro del Día: 2014-12-25

Titulo: HTML5 Canvas Cookbook
Autor: Eric Rowell
Editorial: Packt
Nro Paginas: 348

Capítulos:
Chapter 1: Getting Started with Paths and Text
Chapter 2: Shape Drawing and Composites
Chapter 3: Working with Images and Videos
Chapter 4: Mastering Transformations
Chapter 5: Bringing the Canvas to Life with Animation
Chapter 6: Interacting with the Canvas: Attaching Event Listeners to Shapes and Regions
Chapter 7: Creating Graphs and Charts
Chapter 8: Saving the World with Game Development
Chapter 9: Introducing WebGL
Appendix A: Detecting Canvas Support
Appendix B: Canvas Security
Appendix C: Additional Topics

Descarga:
HTML5_Canvas_Cookbook

miércoles, 24 de diciembre de 2014

El Libro del Día: HTML5 Canvas (2nd Edition)

El Libro del Día: 2014-12-24

Titulo: HTML5 Canvas (2nd Edition)
Autor: Steve Fulton, Jeff Fulton
Editorial: O'Reilly
Nro Paginas: 749

Capítulos:
1. Introduction to HTML5 Canvas
2. Drawing on the Canvas
3. The HTML5 Canvas Text API
4. Images on the Canvas
5. Math, Physics, and Animation
6. Mixing HTML5 Video and Canvas
7. Working with Audio
8. Canvas Games: Part I
9. Canvas Games: Part II
A. Full Code Listings

Descarga:
HTML5_Canvas

jueves, 23 de octubre de 2014

El Libro del Día: Beginning JavaScript Charts

El Libro del Día: 2014-10-23

Titulo: Beginning JavaScript Charts
Autor: Fabio Nelli
Editorial: Apress
Nro Paginas: 602

Capítulos:
Chapter 1: Charting Technology Overview
Chapter 2: jQuery Basics
Chapter 3: Simple HTML Tables
Chapter 4: Drawing a Line Chart
Chapter 5: Drawing a Bar Chart
Chapter 6: Drawing a Pie Chart
Chapter 7: Creating a Library for Simple Charts
Chapter 8: Introducing jqPlot
Chapter 9: Line Charts with jqPlot
Chapter 10: Bar Charts with jqPlot
Chapter 11: Pie Charts and Donut Charts with jqPlot
Chapter 12: Candlestick Charts with jqPlot
Chapter 13: Scatter Charts and Bubble Charts with jqPlot
Chapter 14: Funnel Charts with jqPlot
Chapter 15: Adding Controls to Charts
Chapter 16: Embedding jqPlot Charts in jQuery Widgets
Chapter 17: Handling Input Data
Chapter 18: Moving from jqPlot to Highcharts
Chapter 19: Working with D3
Chapter 20: Line Charts with D3
Chapter 21: Bar Charts with D3
Chapter 22: Pie Charts with D3
Chapter 23: Candlestick Charts with D3
Chapter 24: Scatterplot and Bubble Charts with D3
Chapter 25: Radar Charts with D3
Chapter 26: Handling Live Data with D3
Appendix A: Guidelines for the Examples in the Book
Appendix B: jqPlot Plug-ins

Descarga:
Beginning_JavaScript_Charts

jueves, 2 de octubre de 2014

El Demo del Día: Gráficos de Lineas y Curvas en WinForms

Gráficos de Lineas y Curvas en WinForms

Hoy veremos como crear gráficos en .NET dinamicamente usando la clase Graphics del espacio de Nombres System.Drawing, la cual tiene métodos que permiten dibujar textos, lineas, curvas, etc.

Para el ejemplo lo haremos mediante un Timer que genera números al azar con los cuales se crearan los puntos a graficar, pero en un caso real, en vez del Timer podemos leer de una base de datos una serie de datos o también recibir por el puerto serial o via sockets leer el valor de un dispositivo conectado a la computadora, por ejemplo un termómetro, balanza electrónica, medición de latidos del corazón, pulsos, etc.

Crear la Aplicación Windows Forms

En el Visual Studio crear una aplicación en C# llamada: "GraficoLineasCurvas" y renombrar el formulario a "frmGrafico". Arrastrar solo un control Timer y llamarlo: "tmrGrafico" configurando sus propiedad Enabled en True, para que se habilite cada 100 milisegundos el gráfico.

El diseño del formulario debe quedar como se muestra en la figura:



Escribir el siguiente código en el formulario, sobre todo la función "graficarSeries" que esta asociado al evento "Tick" del timer "tmrGrafico":

using System;
using System.Drawing;
using System.Windows.Forms;

namespace GraficoLineasCurvas
{
    /*Creado por Luis Dueñas para el Blog*/
    public partial class frmGrafico : Form
    {
        private int x = 0;
        private int n = 40;
        private Point punto1Linea;
        private Point punto1Curva;

        public frmGrafico()
        {
            InitializeComponent();
        }

        private void graficarSeries(object sender, EventArgs e)
        {
            Random oAzar = new Random();
            int yLinea = oAzar.Next(this.Height-200) + 100;
            int yCurva = oAzar.Next(this.Height-200) + 100;
            if (x == 0)
            {
                punto1Linea = new Point(x,yLinea);
                punto1Curva = new Point(x, yCurva);
            }
            Point punto2Linea = new Point(x, yLinea);
            Point punto4Curva = new Point(x, yCurva);
            Graphics grafico = this.CreateGraphics();
            grafico.DrawString("Gráficos Dinámicos en .NET (Por Lduenas)",
                new Font("Arial",40),Brushes.Green,100,20);
            grafico.DrawLine(new Pen(Brushes.Red, 4), punto1Linea, punto2Linea);

            Point punto2Curva;
            Point punto3Curva;
            int c = (int)((x/n)-1)*n;
            if (punto1Curva.Y >= punto4Curva.Y)
            {
                punto2Curva = new Point(c + (n/4), punto4Curva.Y);
                punto3Curva = new Point(c+((3*n) / 4), punto1Curva.Y);              
            }
            else
            {
                punto2Curva = new Point(c+ (n / 4), punto1Curva.Y);
                punto3Curva = new Point(c+ ((3 *n) / 4), punto4Curva.Y);              
            }
            grafico.DrawBezier(new Pen(Brushes.Blue, 4), punto1Curva, punto2Curva,
            punto3Curva, punto4Curva);
         
            x += n;
            punto1Linea = punto2Linea;
            punto1Curva = punto4Curva;
            if (x >= this.Width)
            {
                x = 0;
                grafico.Clear(this.BackColor);
            }
        }
    }
}

Nota: Se crea la variable x para la posición de la columna y la variable y para la fila, ademas 2 variables punto1Linea y punto1Curva para guardar el punto anterior desde donde se iniciara el gráfico.

Para las lineas solo necesitamos 2 puntos: inicio (punto1Linea) y fin (punto2Linea), pero para la curva de Bézier necesitamos 4 puntos: punto de anclaje de inicio (punto1Curva), punto de control 1 (punto2Curva), punto de control 2 (punto3Curva), y punto de anclaje final (punto4Curva).

La variable n (por defecto 40) indica el intervalo en que aumenta las columnas o posición x.

Probar la Aplicación Creada

Grabar el proyecto y ejecutarlo con F5. Aparece una ventana maximizada como en la siguiente figura:




El texto con el título se mostrará de color verde, el gráfico de Lineas se mostrará en color rojo y el gráfico de Curvas en color azul.

Cuando llegue al final del ancho se borrará el dibujo y se creará nuevamente. Puedes experimentar modificando el tamaño del intervalo n de 40 a mas o menos.

Comentario Final

Es muy fácil crear gráficos dinámicos en .NET, ya sea de lineas o curvas, sin necesidad de recurrir a ningún Control, ya que estos solo se utilizan para graficar datos históricos (existentes den bases de datos, archivos de textos, xml, etc), pero, si deseamos graficar en tiempo real mejor es crear nuestro gráfico dinámicamente usando la clase Graphics de System.Drawing.

Descarga
Demo20_GraficoLineasCurvas


martes, 29 de julio de 2014

El Libro del Día: HTML5 Canvas For Dummies

El Libro del Día: 2014-07-29

Titulo: HTML5 Canvas For Dummies
Autor: Don Cowan
Editorial: Wiley
Nro Paginas: 387

Capítulos:
Part I: Looking at Canvas
Chapter 1: A Quick Glimpse Behind the Canvas
Chapter 2: Setting Up Your Canvas Platform
Part II: Drawing on Canvas
Chapter 3: Creating Objects
Chapter 4: Enhancing Objects
Chapter 5: Transforming Objects
Chapter 6: Moving Objects
Part III: Breathing Life into Your Canvas
Chapter 7: Mastering the Art of Canvas
Chapter 8: Introducing User Interaction
Chapter 9: Creating Engaging Imagery and Motion
Chapter 10: Sounding Off with Audio
Part IV: Developing More Complex Applications
Chapter 11: Grabbing Attention with Video
Chapter 12: Enhancing Canvas Applications
Part V: The Part of Tens
Chapter 13: Ten Great Canvas Applications
Chapter 14: Ten Great Tools

Descarga:
HTML5_Canvas_ForDummies