Buscar contenidos

lunes, 28 de mayo de 2018

Grid.MVC

http://mvcgrid.net/


MVCGrid.Net

A grid for ASP.NET MVC and Bootstrap with ajax paging and sorting. Also has filtering support, export to csv, back button support, and graceful degradation.
The primary goal of this project is to provide the core grid functionality, along with a very simple and easy-to-use client-side API to allow you to easily add the additional front-end interaction you need. You can add it to your project very easily and get it running with minimal effort, but it also has the extensibility to customize when needed.
You configure your grids on app start, and provide a function callback to actually query your data. The library will handle the ajax requests. It will parse and validate the requested options and then pass the QueryOptions to your function to retrieve the data.

public static class MVCGridConfig
    {
        public static void RegisterGrids()
        {

            MVCGridDefinitionTable.Add("Filtering", new MVCGridBuilder<Solicitud>()
             .WithAuthorizationType(AuthorizationType.AllowAnonymous)
             .AddColumns(cols => {

                cols.Add("ViewLink").WithSorting(false)
                .WithHeaderText("Ver")
                .WithHtmlEncoding(false)
                .WithValueExpression((p, c) => c.UrlHelper.Action("Solicitud", "Home", new { id = p.Id }))               
                .WithValueTemplate("<a href='{Value}' ><span class='glyphicon glyphicon-folder-open'></span></a>");

                 cols.Add("Id").WithHeaderText("Id").WithSorting(true).WithFiltering(true)
                .WithValueExpression(p => p.Id.ToString());

                cols.Add("Titulo").WithHeaderText("Título").WithValueExpression(p => p.Titulo)
                .WithFiltering(true).WithSorting(true);

                cols.Add("FCreacion").WithHeaderText("Fecha de creación").WithValueExpression(p => p.FechaCreacion.ToShortDateString())
                .WithFiltering(true);

                 cols.Add("Hit").WithHeaderText("Vistas").WithValueExpression(p => p.Hit.ToString())
              .WithFiltering(false).WithSorting(false);

                 cols.Add("Ir").WithSorting(false)
               .WithHeaderText("Link")
               .WithHtmlEncoding(false)
               .WithValueExpression((p, c) => p.UrlContenido)
               .WithValueTemplate("<a href='{Value}'  target='_blank' ><span class='glyphicon glyphicon-send'></span></a>");
                
             })
             .WithSorting(true, "Id")
             .WithPaging(true, 10, true, 10)
             .WithFiltering(true)
             .WithRetrieveDataMethod((context) => {

                 var options = context.QueryOptions;

                 Solicitud solicitudObj = new Solicitud();

                 List<Solicitud> ListSolicitud = new List<Solicitud>();

                ListSolicitud = solicitudObj.Get(Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["RowsPerPage"]),
                Convert.ToInt32(((options.PageIndex == null) | (options.PageIndex == 0)) ? 1 : (options.PageIndex + 1)),
                (options.SortDirection == SortDirection.Unspecified ? "DESC" : options.SortDirection.ToString().Contains("A") ? "ASC" : "DESC"),
                options.SortColumnName,
                (options.Filters.Count == 0 ? "" : options.Filters.First().Value),
                (options.Filters.Count == 0 ? "" : options.Filters.First().Key));

                return new QueryResult<Solicitud>()
                {
                    Items = ListSolicitud,
                    TotalRecords = ListSolicitud.Count == 0 ? 0 : ListSolicitud.First().TotalVirtual
                    };
                    })
                );
        }
    }


----------------------------------------------------------------------

<script src="~/Scripts/bootstrap.min.js"></script>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <script src="~/MVCGridHandler.axd/script.js"></script>
    <script src="~/Scripts/jquery.cookie.js"></script>
    <script src="~/Scripts/jquery.masked-input.min.js"></script>

    <style type="text/css">
        * {
            font-family: Arial;
        }

        .well {
            background: #E6E6E6;
        }

        table {
            background: white;
        }
    </style>

    <script type="text/javascript">

        function Main() {

            $("#MVCGrid_Loading_Filtering").html('<img src="Images/loading.gif" />');

            $(".col-xs-6").each(function () {
                if ($(this).text().match('Showing')) {
                    $(this).text($(this).text().replace("to", "a"));
                    $(this).text($(this).text().replace("of", "de"));
                    $(this).text($(this).text().replace("Showing", "Mostrando"));
                    $(this).text($(this).text().replace("entries", " registros"));
                }
            });

            $("span").each(function () {
                if ($(this).text().match('Previous')) {
                    $(this).text($(this).text().replace("« Previous", "<<"));
                } else
                    if ($(this).text().match('Next »')) {
                        $(this).text($(this).text().replace("Next »", ">>"));
                    }
            });

            $("th").each(function () {
                if ($(this).text().match('Ver')) {
                    $(this).css("width", "10px");
                } else if ($(this).text().match('Id')) {
                    //$(this).css("width", "50px");
                }

            });
        }

        $().ready(function () {

            Main();

            $(document).ajaxComplete(function () {
                Main();
            });

        });


    </script>


jueves, 10 de mayo de 2018

Azure Search API

Learn how to take advantage of Azure Search to extend your data from common stores such as Azure SQL and DocumentDB to build great search experiences into web and mobile applications that use advanced linguistics and geo-spatial navigation.


martes, 17 de abril de 2018

Niveles de servicio y DTU en SQL Azure

Si ya estamos familiarizados con el servicio de bases de datos relacionales con SQL Azure también deberíamos estarlo con el concepto DTU (Database Throughput Unit), y si no lo estamos, es un buen momento para saberlo.
En SQL Azure, esencialmente existen tres niveles de servicios:
  • Básico: Ideal para bases de datos pequeñas, que suelen admitir una sola operación activa en un momento dado. Entre los ejemplos se incluyen las bases de datos usadas para desarrollo, pruebas o aplicaciones a pequeña escala que se usan con poca frecuencia.
  • Standard: La opción predilecta para la mayoría de aplicaciones en la nube, admite varias consultas simultáneas. Entre los ejemplos se incluyen aplicaciones web o para grupos de trabajo.
  • Premium: Diseñado para altos volúmenes de transacciones, admite un gran número de usuarios simultáneos y requiere el máximo nivel de capacidades de continuidad empresarial. Entre los ejemplos se incluyen bases de datos que admiten aplicaciones críticas.
Cada nivel de servicio tiene un conjunto de características con parámetros bien definidos:
sql-database-service-tiers-table
DTU (Database Throughput Unit)
La unidad de rendimiento de base de datos (DTU) es la unidad de medida que representa la potencia  de la misma. Una base de datos de tipo “Básica” tiene 5 DTU, lo que significa que puede completar 5 transacciones por segundo, mientras que una base de datos de tipo “Premium P11” tiene 1750 DTU, por lo que la cantidad de transacciones es mucho mayor.
single_db_dtus
Este tipo de ajustes lo podemos hacer desde la sección de “Escalar” de nuestra base de datos de una manera muy sencilla.
En conclusión podríamos decir que el rendimiento de nuestra base de datos dependerá de la clasificación de DTU que le tengamos asignada, obviamente como en cualquier otro de los servicios de Azure, podremos hacer esto de manera gradual, escalando cuando así lo necesitemos.

viernes, 6 de abril de 2018

Image Processing with .NET Core

If you're new to .NET Core, and familiar with the full .NET Framework, you may or may not have noticed that the System.Drawing namespace—which is very useful for image processing and manipulation—is not available to .NET Core. Because the full framework runs on Windows machines, .NET Core is cross platform; and to quote MSDN 'The System.Drawing namespace provides access to GDI+ basic graphics functionality.' We begin to see the problem here.

There is a good chance .NET Core will not be running on Windows, so we need to consider alternatives when looking to process images with .NET Core.

Image Processing with .NET Core
GitHub ImageSharp

lunes, 26 de marzo de 2018

Cálculo porcentaje de similitud entre Strings


C#: Calculating Percentage Similarity of 2 strings

double CalculateSimilarity(string source, string target)
{
    if ((source == null) || (target == null)) return 0.0;
    if ((source.Length == 0) || (target.Length == 0)) return 0.0;
    if (source == target) return 1.0;
   
    int stepsToSame = ComputeLevenshteinDistance(source, target);
    return (1.0 - ((double)stepsToSame / (double)Math.Max(source.Length, target.Length)));
}
int ComputeLevenshteinDistance(string source, string target)
{
    if ((source == null) || (target == null)) return 0;
    if ((source.Length == 0) || (target.Length == 0)) return 0;
    if (source == target) return source.Length;
   
    int sourceWordCount = source.Length;
    int targetWordCount = target.Length;
   
    // Step 1
    if (sourceWordCount == 0)
        return targetWordCount;
   
    if (targetWordCount == 0)
        return sourceWordCount;
   
    int[,] distance = new int[sourceWordCount + 1, targetWordCount + 1];
   
    // Step 2
    for (int i = 0; i <= sourceWordCount; distance[i, 0] = i++);
    for (int j = 0; j <= targetWordCount; distance[0, j] = j++);
   
    for (int i = 1; i <= sourceWordCount; i++)
    {
        for (int j = 1; j <= targetWordCount; j++)
        {
            // Step 3
            int cost = (target[j - 1] == source[i - 1]) ? 0 : 1;
   
            // Step 4
            distance[i, j] = Math.Min(Math.Min(distance[i - 1, j] + 1, distance[i, j - 1] + 1), distance[i - 1, j - 1] + cost);
        }
    }
   
    return distance[sourceWordCount, targetWordCount];
}