sábado, 30 de agosto de 2014

Ejemplo de Pie con mvc 4.5

No hay comentarios.:
En este ejemplo vamos a realizar una gráfica de pie.



1.) Descargar el chart.js de http://www.chartjs.org y agregarlo en la carpeta Script de tu proyecto



2.) Luego procedemos abrir cualquier  view, en mi caso utilizare /view/categories/index

Antes que inicie la tabla debes de agregar el cambas de html 5.

<p> 
    @Html.ActionLink("Create New", "Create") 
</p> 

@*Inicio del canvas de la grafica*@ 
<div id="canvas-holder"> 
    <canvas id="chart-area" width="300" height="300" /> 
</div> 

<table class="table">

3.) Ahora vamos agregar los script necesarios, en la parte de abajo de la pagina agregamos:

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
    <script src="~/Scripts/Chart.js"></script> 

    <script> 

        var pieData = [ 
                { 
                    value: 300, 
                    color: "#F7464A", 
                    highlight: "#FF5A5E", 
                    label: "Red" 
                }, 
                { 
                    value: 50, 
                    color: "#46BFBD", 
                    highlight: "#5AD3D1", 
                    label: "Green" 
                }, 
                { 
                    value: 100, 
                    color: "#FDB45C", 
                    highlight: "#FFC870", 
                    label: "Yellow" 
                }, 
                { 
                    value: 40, 
                    color: "#949FB1", 
                    highlight: "#A8B3C5", 
                    label: "Grey" 
                }, 
                { 
                    value: 120, 
                    color: "#4D5360", 
                    highlight: "#616774", 
                    label: "Dark Grey" 
                } 

        ]; 

         $(document).ready(function () { 
            var ctx = document.getElementById("chart-area").getContext("2d"); 
            window.myPie = new Chart(ctx).Pie(pieData); 
        });
         
    </script> 
}



Ha este punto ya debes de tener una gráfica, como puedes ver el Json esta escrito manualmente, ahora debemos generarlo.

5.) Para generar el json abrimos el controller en mi caso sera CategoriesController.cs y agregarmos:

        public JsonResult grafica() 
        { 
             var query = from c in db.Categories 
                        select new 
                        { 
                            value = c.Products.Count(), 
                            label = c.CategoryName 
                        };        

            return Json(query, JsonRequestBehavior.AllowGet); 

        }

Podrias ver el json generado con la ruta:
/categories/grafica

6.) Ahora agregamos el llamado del lado del cliente, para esto volvemos a nuestra view de índex y cambiamos la sección de script por:

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
    <script src="~/Scripts/Chart.js"></script> 

    <script> 

        $(document).ready(function () { 

            $.post( 
                 '@Url.Action("grafica", "Categories")' 
              ) 
             .done(function (data) { 
                 var ctx = document.getElementById("chart-area").getContext("2d"); 
                 window.myPie = new Chart(ctx).Pie(data); 
             }) 
             .fail(function (data) { 
                 console.log('error !!!'); 
             } 
         ); 


        }); 

    </script> 
}

Note que ya no es necesario que este escrito el json ya que lo vamos a generar.

Ahora nos mostrara nuestro pie sin colores, ya que el json generado aun no los tiene.



7.) Por ultimo vamos agregar colores al json generado, eso puede que lleve mas código ya que tenemos que tener una tabla de colores y llamarlos al momento del llenado.

Dentro del controlador vamos agregar 2 lista genéricas uno para los colores y otra para datos que enviaremos.

7.2) Lista genéricas:

 public class colores 
        { 
            private int _id; 
            private string _color;
            private string _highlight;

            public int id { get { return _id; } set { _id = value; } }
            public string color { get { return _color; } set { _color = value; } }
            public string highlight { get { return _highlight; } set { _highlight = value; } }

            public colores(int id,string color, string highlight)
            { 
                _id = id; 
                _color = color; 
                _highlight = highlight; 
            } 
        } 

        public class categorias
        { 
            private int _value;
            private string _color;
            private string _highlight;
            private string _label;


            public int value { get { return _value; } set { _value = value; } }
            public string color { get { return _color; } set { _color = value; } }
            public string highlight { get { return _highlight; } set { _highlight = value; } }
            public string label { get { return _label; } set { _label = value; } }

            public categorias(int value, string color, string highlight, string label)
            { 
                _value = value; 
                _color = color; 
                _highlight = highlight; 
                _label = label; 
            } 
        }

7.3) Ahora vamos a cambiar nuestro metodo gráfica para utilizar los colores, debemos de popular la lista de colores disponibles y luego popular las categorías, por ultimo agregarlos unir colores con categorías, ahora mismo solo vamos a trabajar con 5 colores, si las categorías son mas de 5 se van a repetir colores, si no quieres que se repitan agrega tantos colores como categorías.

public JsonResult grafica() 
        { 

            List<colores> col = new List<colores>();
            col.Add(new colores(0,"#F7464A", "#FF5A5E")); 
            col.Add(new colores(1,"#46BFBD", "#5AD3D1")); 
            col.Add(new colores(2,"#FDB45C", "#FFC870")); 
            col.Add(new colores(3,"#949FB1", "#A8B3C5")); 
            col.Add(new colores(4,"#4D5360", "#616774")); 

            var query = from c in db.Categories 
                        select new 
                        { 
                            value = c.Products.Count(), 
                            label = c.CategoryName 
                        }; 

            List<categorias> Cat = new List<categorias>(); 
            int id = 0;  
            foreach (var row in query)
            { 
                 
                colores filacolor; 
                filacolor = col[id]; 
                Cat.Add(new categorias(row.value, filacolor.color, filacolor.highlight, row.label));
                if(id==4) 
                { 
                    id = 0; 
                } 
                else 
                { 
                    id++; 
                } 
            } 

            return Json(Cat, JsonRequestBehavior.AllowGet); 

        }


Así quedara al final:



Agrego el código fuente completo.

Codigo fuente html

@model IEnumerable<WebApplication2.Models.Categories> 

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

<p> 
    @Html.ActionLink("Create New", "Create") 
</p> 

@*Inicio del canvas de la grafica*@ 
<div id="canvas-holder"> 
    <canvas id="chart-area" width="300" height="300" /> 
</div> 

<table class="table"> 
    <tr> 
        <th> 
            @Html.DisplayNameFor(model => model.CategoryName)
        </th> 
        <th> 
            @Html.DisplayNameFor(model => model.Description) 
        </th> 
        <th></th> 
    </tr> 

    @foreach (var item in Model) 
    { 
        <tr> 
            <td> 
                @Html.DisplayFor(modelItem => item.CategoryName) 
            </td> 
            <td> 
                @Html.DisplayFor(modelItem => item.Description) 
            </td> 
            <td> 
                @Html.ActionLink("Edit", "Edit", new { id = item.CategoryID }) | 
                @Html.ActionLink("Details", "Details", new { id = item.CategoryID }) | 
                @Html.ActionLink("Delete", "Delete", new { id = item.CategoryID }) 
            </td> 
        </tr> 
    } 

</table> 
@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
    <script src="~/Scripts/Chart.js"></script> 

    <script> 

        $(document).ready(function () { 

            $.post( 
                 '@Url.Action("grafica", "Categories")' 
              ) 
             .done(function (data) { 
                 var ctx = document.getElementById("chart-area").getContext("2d"); 
                 window.myPie = new Chart(ctx).Pie(data); 
             }) 
             .fail(function (data) { 
                 console.log('error !!!'); 
             } 
         ); 


        }); 

    </script> 
}

Codigo fuente controlador

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Data.Entity; 
using System.Linq; 
using System.Net; 
using System.Web; 
using System.Web.Mvc; 
using WebApplication2.Models; 

namespace WebApplication2.Controllers 
{ 



    public class CategoriesController : Controller
    { 
        private ApplicationDbContext db = new ApplicationDbContext();

        public class colores 
        { 
            private int _id; 
            private string _color;
            private string _highlight;

            public int id { get { return _id; } set { _id = value; } }
            public string color { get { return _color; } set { _color = value; } }
            public string highlight { get { return _highlight; } set { _highlight = value; } }

            public colores(int id,string color, string highlight)
            { 
                _id = id; 
                _color = color; 
                _highlight = highlight; 
            } 
        } 

        public class categorias
        { 
            private int _value;
            private string _color;
            private string _highlight;
            private string _label;


            public int value { get { return _value; } set { _value = value; } }
            public string color { get { return _color; } set { _color = value; } }
            public string highlight { get { return _highlight; } set { _highlight = value; } }
            public string label { get { return _label; } set { _label = value; } }

            public categorias(int value, string color, string highlight, string label)
            { 
                _value = value; 
                _color = color; 
                _highlight = highlight; 
                _label = label; 
            } 
        } 

        public JsonResult grafica() 
        { 

            List<colores> col = new List<colores>();
            col.Add(new colores(0,"#F7464A", "#FF5A5E")); 
            col.Add(new colores(1,"#46BFBD", "#5AD3D1")); 
            col.Add(new colores(2,"#FDB45C", "#FFC870")); 
            col.Add(new colores(3,"#949FB1", "#A8B3C5")); 
            col.Add(new colores(4,"#4D5360", "#616774")); 

            var query = from c in db.Categories 
                        select new 
                        { 
                            value = c.Products.Count(), 
                            label = c.CategoryName 
                        }; 

            List<categorias> Cat = new List<categorias>(); 
            int id = 0;  
            foreach (var row in query)
            { 
                 
                colores filacolor; 
                filacolor = col[id]; 
                Cat.Add(new categorias(row.value, filacolor.color, filacolor.highlight, row.label));
                if(id==4) 
                { 
                    id = 0; 
                } 
                else 
                { 
                    id++; 
                } 
            } 

            return Json(Cat, JsonRequestBehavior.AllowGet); 

        } 


        // GET: Categories 
        public ActionResult Index() 
        { 
            return View(db.Categories.ToList()); 
        } 


Ver

miércoles, 27 de agosto de 2014

Http a https IIS8

No hay comentarios.:
Para hacer un redirect de http a https lo mejor es usar la extensión  Rewrite Module, la extensión la tenemos que instalar, puedes bajarlo de:

http://www.iis.net/downloads/microsoft/url-rewrite

Luego cambian en el webconfig  en la sección de < system .webserver>


 <system.webServer>  
<rewrite> 
      <rules> 
         <rule name="http to https" stopProcessing="true"> 
                    <match url=".*" /> 
                    <conditions> 
                        <add input="{HTTPS}" pattern="off" /> 
                    </conditions> 
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:0}" /> 
        </rule> 
      </rules> 
 </rewrite> 

</system.webServer>
Ver