Monday, February 1, 2016

Extending Chartjs


ChartJs is a free Javascript Chart library.Here is one example to extend the line chart with null data value.
    var ctx = document.getElementById("chart").getContext("2d");
    var data = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [{
                label: "My First dataset",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [65, null, null, 81, 56, 55, 40]
            },
        ]
    };

    Chart.types.Line.extend({
        // Passing in a name registers this chart in the Chart namespace in the same way
        name: "MissingLine",
        initialize: function(data) {
            var helpers = Chart.helpers;
            //Declare the extension of the default point, to cater for the options passed in to the constructor
            this.PointClass = Chart.Point.extend({
                strokeWidth: this.options.pointDotStrokeWidth,
                radius: this.options.pointDotRadius,
                display: this.options.pointDot,
                hitDetectionRadius: this.options.pointHitDetectionRadius,
                ctx: this.chart.ctx,
                inRange: function(mouseX) {
                    return (Math.pow(mouseX - this.x, 2) < Math.pow(this.radius + this.hitDetectionRadius, 2));
                }
            });

            this.datasets = [];

            //Set up tooltip events on the chart
            if (this.options.showTooltips) {
                helpers.bindEvents(this, this.options.tooltipEvents, function(evt) {
                    var activePoints = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
                    this.eachPoints(function(point) {
                        point.restore(['fillColor', 'strokeColor']);
                    });
                    helpers.each(activePoints, function(activePoint) {
                        activePoint.fillColor = activePoint.highlightFill;
                        activePoint.strokeColor = activePoint.highlightStroke;
                    });
                    this.showTooltip(activePoints);
                });
            }

            //Iterate through each of the datasets, and build this into a property of the chart
            helpers.each(data.datasets, function(dataset) {

                var datasetObject = {
                    label: dataset.label || null,
                    fillColor: dataset.fillColor,
                    strokeColor: dataset.strokeColor,
                    pointColor: dataset.pointColor,
                    pointStrokeColor: dataset.pointStrokeColor,
                    points: []
                };

                this.datasets.push(datasetObject);

                helpers.each(dataset.data, function(dataPoint, index) {
                    /***
                     * Check for datapoints that are null
                     ***/
                    if (helpers.isNumber(dataPoint) || dataPoint === null) {
                        //Add a new point for each piece of data, passing any required data to draw.
                        datasetObject.points.push(new this.PointClass({
                            /*** 
                             * add ignore field so we can skip them later
                             ***/
                            ignore: dataPoint === null,
                            value: dataPoint,
                            label: data.labels[index],
                            datasetLabel: dataset.label,
                            strokeColor: dataset.pointStrokeColor,
                            fillColor: dataset.pointColor,
                            highlightFill: dataset.pointHighlightFill || dataset.pointColor,
                            highlightStroke: dataset.pointHighlightStroke || dataset.pointStrokeColor
                        }));
                    }
                }, this);

                this.buildScale(data.labels);

                this.eachPoints(function(point, index) {
                    helpers.extend(point, {
                        x: this.scale.calculateX(index),
                        y: this.scale.endPoint
                    });
                    point.save();
                }, this);

            }, this);

            this.render();
        },

        draw: function(ease) {
            var helpers = Chart.helpers;
            var easingDecimal = ease || 1;
            this.clear();

            var ctx = this.chart.ctx;

            this.scale.draw(easingDecimal);

            helpers.each(this.datasets, function(dataset) {
                //Transition each point first so that the line and point drawing isn't out of sync
                //We can use this extra loop to calculate the control points of this dataset also in this loop

                helpers.each(dataset.points, function(point, index) {
                    point.transition({
                        y: this.scale.calculateY(point.value),
                        x: this.scale.calculateX(index)
                    }, easingDecimal);

                }, this);

                // Control points need to be calculated in a seperate loop, because we need to know the current x/y of the point
                // This would cause issues when there is no animation, because the y of the next point would be 0, so beziers would be skewed
                if (this.options.bezierCurve) {
                    helpers.each(dataset.points, function(point, index) {
                        //If we're at the start or end, we don't have a previous/next point
                        //By setting the tension to 0 here, the curve will transition to straight at the end
                        if (index === 0) {
                            point.controlPoints = helpers.splineCurve(point, point, dataset.points[index + 1], 0);
                        } else if (index >= dataset.points.length - 1) {
                            point.controlPoints = helpers.splineCurve(dataset.points[index - 1], point, point, 0);
                        } else {
                            point.controlPoints = helpers.splineCurve(dataset.points[index - 1], point, dataset.points[index + 1], this.options.bezierCurveTension);
                        }
                    }, this);
                }

                //Draw the line between all the points
                ctx.lineWidth = this.options.datasetStrokeWidth;
                ctx.strokeStyle = dataset.strokeColor;

                var penDown = false;
                var start = null

                helpers.each(dataset.points, function(point, index) {
                    /***
                     * no longer draw if the last point was ignore (as we don;t have anything to draw from)
                     * or if this point is ignore
                     * or if it's the first
                     ***/
                    if (!point.ignore && !penDown) {
                        ctx.beginPath();
                        penDown = true;
                        start = point;
                    }
                    if (index > 0 && !dataset.points[index - 1].ignore && !point.ignore) {
                        if (this.options.bezierCurve) {
                            ctx.bezierCurveTo(
                                dataset.points[index - 1].controlPoints.outer.x,
                                dataset.points[index - 1].controlPoints.outer.y,
                                point.controlPoints.inner.x,
                                point.controlPoints.inner.y,
                                point.x,
                                point.y
                            );
                        } else {
                            ctx.lineTo(point.x, point.y);
                        }
                    } else if (index === 0 || dataset.points[index - 1].ignore) {
                        ctx.moveTo(point.x, point.y);
                    }

                    if (((dataset.points.length > index + 1 && dataset.points[index + 1].ignore) ||
                        dataset.points.length == index + 1) && !point.ignore) {
                        ctx.stroke();

                        if (this.options.datasetFill) {
                            ctx.lineTo(point.x, this.scale.endPoint);
                            ctx.lineTo(start.x, this.scale.endPoint);
                            ctx.fillStyle = dataset.fillColor;
                            ctx.closePath();
                            if (point.x != start.x) {
                                ctx.fill();
                            }
                        }
                        penDown = false;
                    }

                }, this);


                //Now draw the points over the line
                //A little inefficient double looping, but better than the line
                //lagging behind the point positions
                helpers.each(dataset.points, function(point) {
                    /**
                     * don't draw the dot if we are ignoring
                     */
                    if (!point.ignore)
                        point.draw();
                });

            }, this);
        }
    });

    var myLineChart = new Chart(ctx).MissingLine(data);
Resources:
http://jsfiddle.net/leighking2/sLgefm04/6/

Sunday, January 31, 2016

How to handle ASP.NET MVC JSON Result Date Format Issue

ASP.Net MVC controller will return JsonResult for action so that ajax can handle those Json data. But Json data has issues for type DateTime, especially Microsoft SQL Server DB. Here is some result if you just display those data in string format: "/Date(-501361200000)/". This is one very popular topic for ASP.Net MVC Json data processing. You can process those Json DateTime at client side using some Javascript tricks. But the best solution is on the Server side, you can use Json.Net from newtonsoft to do the magic.

This is one typical action method in controller:
        public JsonResult GetStudent(string name)
        {
            try
            {
                if (name == null)
                {
                    return Json(null, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    using (StudentService _service = new StudentService())
                    {
                        Student = _service.GetStudent(name);
                        return Json(model, JsonRequestBehavior.AllowGet);
                    }
                }
            }
            catch (Exception ex)
            {
                return Json(ex.Message, JsonRequestBehavior.AllowGet);
            }
        }
You don't need to change above code. What you should do is:
First,  add a new class CustomJsonResult which inherits from JsonResult.
using System;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class CustomJsonResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            // Using Json.NET serializer
            var isoConvert = new IsoDateTimeConverter();
            isoConvert.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            response.Write(JsonConvert.SerializeObject(Data, isoConvert));
        }
    }
}
Second, in your Base Controller, override Json method to return CustomJsonResult.
        protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            return new CustomJsonResult
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding,
                JsonRequestBehavior = behavior
            };
        }
Then all JsonResult call in your controller will return CustomJsonResult I created above, which use Newtonsoft.Json.Converters.IsoDateTimeConverter as serializer instead, and you will see the readable DateTime instead of annoying and wild date format in JsonResult.

Source:
http://stackoverflow.com/questions/726334/asp-net-mvc-jsonresult-date-format

Friday, January 15, 2016

Applying c# Extensions for Claims-based Authentication

In My AccountController, I have NewLogin Action:
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult NewLogin(LocalAccountLoginViewModel model, string returnUrl)
        {
            using (UserService _service = new UserService())
            {
                CFG_Users user = _service.GetUserById(model.UserId);
                if (user == null)
                {
                    DisplayErrorPage("Error", Resources.Account.LoginResources.UserNotExist);
                    return View(model);
                }
                if (!user.Enabled)
                {
                    DisplayErrorPage("Error", Resources.Account.LoginResources.UserNotActive);
                    return View(model);
                }

                if (!_service.ValidateUser(model.UserId, model.Password))
                {
                    DisplayErrorPage("Error", Resources.Account.LoginResources.InvalidUserNamePassword);
                    return View(model);
                }

                var claims = new List<Claim>();

                // create *required* claims
                claims.Add(new Claim(ClaimTypes.NameIdentifier, user.IDUser));
                claims.Add(new Claim(ClaimTypes.Name, _service.GetUserName(user)));
                claims.Add(new Claim("IsAdmin", _service.IsUserAdmin(user).ToString()));
                claims.Add(new Claim("Culture", user.IDLanguage.Trim()));

                IdentitySignin(claims, model.UserId, model.RememberMe);

                if (!string.IsNullOrEmpty(returnUrl))
                    return Redirect(returnUrl);

                return RedirectToAction("Index", "Dashboard", null);
            }
        }
The NewLogin action  applied following helper method to finish the sign in process.
        /// <summary>
        /// Helper method that adds the Identity cookie to the request output
        /// headers. 
        /// </summary>
        /// <param name="claims"></param>
        /// <param name="providerKey"></param>
        /// <param name="isPersistent"></param>
        public void IdentitySignin(List<Claim> claims, string providerKey = null, bool isPersistent = false)
        {
            var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

            // add to user here!
            AuthenticationManager.SignIn(new AuthenticationProperties()
            {
                AllowRefresh = true,
                IsPersistent = isPersistent,
                ExpiresUtc = DateTime.UtcNow.AddDays(1)
            }, identity);

            var userCulture = identity.GetCulture();
            // set lang to the user's language 
            if (RouteData.Values["lang"] != userCulture)
            {
                RouteData.Values["lang"] = userCulture;
                SetThreadCulture(userCulture);
            }
        }

        public void IdentitySignout()
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie,
                DefaultAuthenticationTypes.ExternalCookie);
        }

        private IAuthenticationManager AuthenticationManager
        {
            get { return HttpContext.GetOwinContext().Authentication; }
        }
Note I applied C# Extensions so I can easily use GetCulture for my identity. Here is the Claim Identity Extension code:
using System.Collections.Generic;
using System.Security.Claims;
using System.Linq;
namespace MyApp.Extensions
{
    public static class ClaimsIdentityExtensions
    {
        public static bool IsAdmin(this ClaimsIdentity identity)
        {
            var claims = identity.Claims;
            return bool.Parse(GetClaim(claims, "IsAdmin")); 
        }

        public static string GetCulture(this ClaimsIdentity identity)
        {
            var claims = identity.Claims;
            return GetClaim(claims, "Culture"); //todo: replace Culture with a Const
        }

        public static string GetName(this ClaimsIdentity identity)
        {
            var claims = identity.Claims;
            return GetClaim(claims, ClaimTypes.Name); ;
        }

        public static string GetUserId(this ClaimsIdentity identity)
        {
            var claims = identity.Claims;
            return GetClaim(claims, ClaimTypes.NameIdentifier);
        }

        private static string GetClaim(IEnumerable<Claim> claims, string key)
        {
            var claim = claims.ToList().FirstOrDefault(c => c.Type == key);
            if (claim == null)
                return null;
            return claim.Value;
        }
    }
}

Reference:
http://leastprivilege.com/2012/10/08/custom-claims-principals-in-net-4-5/

Friday, January 8, 2016

How to share Localization Resource in ASP.Net 5 MVC with Javascript

ASP.Net MVC projects can use Resource files to do localization. Its very easy to use those resource files in razor view files. For each resource, there are multiple resource files referring to different languages. ASP.Net treats those resource files as one resource class. The application will use specific language resource during the run time while one language is selected.

Regarding the Javascript, if we want to apply those resource files, we need to send them to Javascript one by one in razor file. To avoid those tedious process and to improve the independence of Javascript, we can create resource section in razor file using HTML 5 section tag. And let Javascript to read those resource by themselves. Here is the code in view:
<section class="myResouceLabels"
    data-Message1 = "@MyResources.MyMessage1"
    data-Message2 = "@MyResources.MyMessage2">
</section>
In your Javascript:
    // Return a message contained in the container
    function GetResourceMessage(msgId) {
        var container = $(".myResouceLabels");
        if (container.length == 0) return;
        return container.attr(msgId);
    }
    ....
    alert(GetResourceMessage(data-Message1);
    alert(GetResourceMessage(data-Message1);
Note section tag contained all attributes with data as leading string, which is different than other tags. Be careful not to make mistake!!!

Definitely, you need css decorating to let the section don't be displayed.
myResouceLabels { display: none }

Tuesday, December 29, 2015

How to apply Claim Based Authorization Framework for ASP.NET 5


Note, if you added WebMatrix.WebData.dll into your project reference, then every time your code called ClaimsPrincipal.Claims, system displayed HttpException with the message Unable to connect to SQL Server database.  WebMatrix.WebData.dll contains classes used with the SimpleMembership API introduced by WebMatrix. SimpleMembership, which uses a database, is automatically enabled because the dll uses PreApplicationStart method to initialize itself. The result is that Thread.CurrentPrincipal yields a System.Web.Security.RolePrincipal instead of the ClaimsPrincipal associated with the user. 
The resolution is simple, remove the dll and everything should work fine.

Reference:
http://michiel.vanotegem.nl/2013/05/fix-claimsauthorizationmanager-checkaccess-throws-httpexception/
https://social.msdn.microsoft.com/Forums/vstudio/en-US/57944284-9ec8-4780-995c-b872f2aa9688/authorizationcontext-parameter-of-claimsauthorizationmanager-does-not-contain-claims-of?forum=Geneva
http://weblog.west-wind.com/posts/2015/Apr/29/Adding-minimal-OWIN-Identity-Authentication-to-an-Existing-ASPNET-MVC-Application#Resources
http://dotnetcodr.com/2013/02/11/introduction-to-claims-based-security-in-net4-5-with-c-part-1/
http://dotnetcodr.com/2013/02/14/introduction-to-claims-based-security-in-net4-5-with-c-part-2-the-new-inheritance-model/
http://dotnetcodr.com/2013/02/25/claims-based-authentication-in-mvc4-with-net4-5-c-part-1-claims-transformation/
http://dotnetcodr.com/2013/02/28/claims-based-authentication-in-mvc4-with-net4-5-c-part-2-storing-authentication-data-in-an-authentication-session/