Thursday, June 26, 2014

Creating custom controls for Windows Store App (Javascript- WinJS)

Introduction

The Windows Library for JavaScript (WinJS) is a library of CSS and JavaScript files. It contains JavaScript objects, organized into namespaces, designed to make developing Windows Store app using JavaScript easier. WinJS includes objects that help you handle activation, access storage, and define your own classes and namespaces. It also includes a set of controls like AppBar, ListView, Rating, TimePicker etc.

Though there are many useful controls, they don’t cover all needs (for Ex: A generic control for plotting simple graph, tree view, animation etc.) and it is time for us to develop such custom controls, let’s understand how to do it.

Problem Definition

Let’s consider a simple problem where it’s required to plot a donut like graph to show up the percentage (%) values in our Windows Store App and it should be able to bind to the ViewModel property.

This is how our final graph will look like, 
Solution

First things first,

Include WinJS references in HTML page, because our control will use APIs from these files. 
<script src="//Microsoft.WinJS.1.0/js/base.js"></script>
<
script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
Few simple steps to create a custom WinJS control:
  • Define a Namespace and a Class for control
  • Initialize the control and define control options(in class constructor)
  • Implement the code to plot donut graph (we will be using HTML5 Canvas)
  • Use the control in HTML/JavaScript.

Define a Namespace and a Class for control:

WinJS provide APIs to create Namespaces and Classes in JavaScript, we will be using the same to create ours.
WinJS.Namespace.define() and WinJS.Class.define() are used to create Namespace and Class respectively.

WinJS.Namespace.define("Demo.UI", {
    DonutChart: WinJS.Class.define(function (element, options) {
       // Constructor: here we will validate the DOM element, define options and more.
       this.element = element || document.createElement("div");
    },{
       // Properties: here we will declare and define the properties, private methods and core logic lies here i.e. code to create graph in our case.
       donutValue: {
                    get: function () {
                        return this._donutValue;
                    },
                    set: function (value) {                       
                        this._donutValue = value;
                    }
    }// End of Properties
) // End of Control class definition
}); // End of Namespace definition

The constructor will take two parameters element and options where element is Element object and options we can configure according to our control let's say radius in our case.
Now we have our Namespace and Class ready to use.

Initialize the control and define control options:

In the constructor, we have to validate the element is existing or not if element doesn’t exist create an element (“div” in this example) and add a set of declaratively specified options (properties and events) to the control this is achieved using WinJS.UI.setOptions() method.

function MyControl(element, options) {
                this.element = element || document.createElement("div");
                this.element.winControl = this;
                this.options = options;
                // Set option defaults
                this._donutValue = 0;
                // Set user-defined options
                WinJS.UI.setOptions(this, options);

                element.textContent = options.donutValue;// If it fails to plot graph then display only text
            }

Implement the code to plot donut graph:

We will be using one of HTML5’s great features Canvas to plot the graph, will create the donut chart in _createDonut() method [Note: _createDonut is made as private method so that this method should not be used outside the control]. We can create any number of HMTL element and logic inside this method.

Here is the code snippet where we used Canvas’s arc method to draw circles i.e donut chart

_createDonut: function () {
                    var settings = $.extend({
                        // These are the defaults.
                        color1: '#808080',
                        color2: '#107c10',
                        textColor: '#808080',
                        backgroundColor: "transparent",
                        radius: 20,
                        lineWidth1: 1,
                        lineWidth2: 5,
                        donutValue: 0
                    }, this.options);
                    if (this.donutValue > 0) {
                        try{
                            settings.donutValue = this.donutValue;
                            var percentage = settings.donutValue / 100;
                            var id = this.element.getAttribute("id") + "_canvas";
                            var width = this.element.offsetWidth;
                            var height = this.element.offsetHeight;
                            this.element.innerHTML = "";
                            this.element.innerHTML = "<canvas id='" + id + "' width='" + width + "' height='" + height + "'></canvas>";
                            var c = document.getElementById(id);
                            var ctx = c.getContext("2d");

                            var centerX = c.width / 2;
                            var centerY = c.height / 2;
                            radius = width > height ? height * 0.455 : width * 0.455;
                            //Inner circle
                            ctx.beginPath();
                            ctx.strokeStyle = settings.color1;
                            ctx.lineWidth = settings.lineWidth1;
                            ctx.arc(centerX, centerY, radius, 0 * Math.PI, 2 * Math.PI);
                            ctx.stroke();
                            //Outer Circle
                            ctx.beginPath();
                            ctx.lineWidth = settings.lineWidth2;
                            ctx.strokeStyle = settings.color2;
                            ctx.arc(centerX, centerY, radius, 1.5 * Math.PI, (1.5 + (2 * percentage)) * Math.PI) //calculating the end angle for arc 
                            ctx.stroke();
                            //Display text
                            ctx.font = "15px Segoe UI";
                            ctx.fillStyle = settings.textColor;
                            ctx.fillText(settings.donutValue + "%", centerX - 14, centerY + 5); 
                            clearInterval(this.terminateInterval);
                        }
                        catch (ex) {
                            clearInterval(this.terminateInterval);
                        }
                    }
                    else {
                        this.element.innerHTML = "<span style='color:black; text-align:center;'>---</span>";
                    }

                }

Assume that the control is given with an empty div element, in our code we will create a Canvas element dynamically and append it to the given div element. We are using JQuery $.extend() method to map the default options with the options configured from UI.

Putting the bits altogether:

WinJS.Namespace.define("Demo.UI", {
    DonutChart: WinJS.Class.define(function (element, options) {
       // Constructor: here we will validate the DOM element, define options and more.
       this.element = element || document.createElement("div");
       this.element.winControl = this;
       this.options = options;
       // Set option defaults
       this._donutValue = 0;
       // Set user-defined options
this.terminateInterval = 0;
       WinJS.UI.setOptions(this, options);
element.textContent = options.donutValue;   
    },{
       // Properties: here we will declare and define the properties, private methods and core logic lies here i.e. code to create graph in our case.
_notZero: 0,
       donutValue: {
                    get: function () {
                        return this._donutValue;
                    },
                    set: function (value) {                       
                           if (this._donutValue > 0) {
                                  clearInterval(this._notZero);
                        }
                           this._donutValue = value;
                           this._notZero = setInterval(this._createDonut.bind(this), 1000);
                           this.terminateInterval = this._notZero;
                        }
},
_createDonut: function () {
              //Copy from above
}
    }// End of Properties
) // End of Control class definition
}); // End of Namespace definition


Using the control in HTML/JavaScript:

Now we have created all necessary code and have it in say demo.ui.donutchart.js, let’s see how to use it in our HTML.

Include a reference to demo.ui.donutchart.js script file

<script src="../../js/customcontrols/demo.ui.donutchart.js"></script>

In HTML use the data-win-control attribute to set the control name Demo.UI.DonutChart, use the data-win-options attribute to set the options (Ex. { radius: 20,  color2: '#107c10' }) provided to the constructor and use data-win-bind to bind the data from ViewModel property.

So our html will be,
<div id="donut" data-win-bind="winControl.donutValue:AvgPercent " data-win-control="Demo.UI.DonutChart" data-win-options="{ radius: 20,  color2: '#107c10' }"></div>

Now question is how this will call the control constructor and draw the graph.

Answer is, when WinJS.UI.processAll() method is called from our code [usually this method will be called in default.js of the Windows Store App Solution ] the WinJS will parse the DOM, if the control is found mapping between control and the html done automatically by WinJS i.e. WinJS will instantiate the control and calls the constructor with element where the chart will be created  and options provided in data-win-options as parameters.

Final thing, we will use WinJS.Binding.processAll(document.getElementById("container"), ViewModel); to bind the data to the page or element.

Now debug/deploy the app and we can see the required graph on the screen.

References:



Friday, January 24, 2014

Enable Windows 8 App(HTML) to make XHR request to service hosted in different domain

Introduction

In this small article we are going to learn how to enable our windows 8 app to make a XHR request to service hosted in different domain(e.g Web API hosted in some virtual machine and app in running in my local machine). It seems simple and yes the solution is also simple and straight forward, since I'm new to Win8 app development it took time to understand the things. Lets define the problem.

Problem

First thing is I have two solutions one is Win8 javascript app solution and another one is service solution I have used Web API for it. Now, when i host my service in local IIS and access the service from my Win8 app it was working i.e i was able to get the data and response status was 200. But when i hosted the same service in some virtual machine(VM) and tried to access it was giving 404(Not found) error. SO whats the solution???

Solution

The following is my XHR request,

WinJS.xhr({
            type: "POST",
            url: "url"
            data: JSON.stringify(some_data),
            headers: {"Content-type": "application/json; charset=utf-8" },
        }).then(
            function (success) {
               // play with the data
            },
                function (error) {
                   //handle the errors
                }
        );

There is nothing wrong with the request nor with the service but thing is we have to enable capabilities of Win8 app in package.appxmanifest. In this file under Capabilities tab you can find Capabilities section in that check the Private Networks (Client & Server) check box and save it, this solves the problem.

Tuesday, December 24, 2013

MaxJsonLength exception

MaxJsonLength exception in ASP.NET MVC4 during JavascriptSerializer:

Code:
public ActionResult Index(){
    var data = null  //give some large data e.g big list of values
    var resultData = Json(data, JsonRequestBehavior.AllowGet);
    resultData.MaxJsonLength = Int32.MaxValue;
    return resultData;
}

Note: Then web.config setting is ignored by the default JsonResult implementation. So we might need to implement a custom Json Result or we can use the above code.

Friday, September 6, 2013

Enable Compatibility mode in IE

Introduction
As there are new releases of IE(Internet Explorer) coming out regularly with new features and functionalities, it is not required for legacy page/site to support latest version of the browser. So, for this reason compatibility mode is been introduced in IE8 onwards.
Problem
I have an ASP.NET MVC web application, I want it to run in IE8 or IE9 compatiblity mode in IE10 as our client uses only IE8 or IE9 and we have IE10 in our work stations. Lets see how can we acheive this.
Solution
We can achieve this by setting the value of the compatiblity mode.
Web page can specify compatibility mode either by using META tag or by setting the http header, note that META tag will take precedence over http header when both are present.

Sol 1: META Tag- place the following code in head element of web page(html page)
<meta http-equiv="X-UA-Compatible" content="IE=8, IE=9"/>
it is not only applicable for IE but also for other browsers like chrome
<meta http-equiv="X-UA-Compatible" content="IE=8, IE=9, chrome=1"/>
Important to Note: META tag should be placed in head section before any script or css tag.

Sol 2: HTTP Header- We can configure our server to send a HTTP Header along with each page i.e send "X-UA-Compatibility: IE=8" HTTP header
Now, how do we achieve the same in ASP.NET MVC application?
Add the following code snippet in web.config file
<system.webServer>
    <httpProtocol>
        <customHeaders>
            <clear/>
            <add name="X-UA-Compatible" value="IE=8"/>
        </customHeaders>
    </httpProtocol>
<system.webServer>
Important to Note:
  • system.webServer tag will only be effective if your MVC3 is to run on IIS7 or later
  • If you find your <meta> tag is overridden by IE's intranet settings, this webServer setting will override the compatibility.
For more details browser compatibility mode click here.

Monday, August 12, 2013

Get unique/distinct values from an array using JQuery $.grep and $.inArray

Consider an example of getting unique elments from an array a = [1,1,2,3,8,2]

Array.prototype.unique = function(){
    var array = this;
    return array.filter(function(ele, index, arr){
        return index == arr.indexOf(ele);
    });
}
and in our Javascript,

var array = [1,1,2,3,8,2];
var uniqueElments = arrray.unique();

//Output will be 1,2,3,8
But the issue is few of the older version browsers including IE7 that doesn't support some array features - such as indexOf or filter, so we can use jquery functionalities like:

  •     use $.grep instead of Array.filter
    • The $.grep() method removes items from an array as necessary so that all remaining        items pass a provided test. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.
  • use $.inArray instead of Array.indexOf
    • The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.
Now here's how the changed code would look like:

Array.prototype.unique = function(){
    var array = this;
    return $.grep(array, function(ele, index){
            return $.inArray(ele, array) === index;
    });
}
References:
$.grep
$.inArray

Friday, July 26, 2013

ASP.NET MVC Custom HTML Helpers (C#)

In this article we will understand the different ways of creating custom helper method in ASP.NET MVC4 application. Though we have built-in html helpers like Html.ActionLink(), Html.TextBox() and many more, some times we may need to have custom helper methods for example Image or a block of html controls which is commonly used across the application like Address fields.


Custom HTML Helpers make it easier to generate view content. We can create custom helpers in three ways:

1. with Static Methods
2. with Extension Methods
3. with @helper in the razor view.

Let's understand how to implement the same.

1. Static Methods:


In this approach we will create a static method and use that method in the view, here its is ImageStatic method which will return HtmlString.


CustomHelper.cs:
namespace HelperApplication.Helpers
{
    public static class CustomHelpers
    {
        //Static method
        public static IHtmlString ImageStatic(string src, string alt = "Image", int width = 50, int height = 50)
        {
            var value = String.Format("<img src='{0}' alt='{1}' width='{2}' height='{3}'/>", src, alt, width, height);
            return new HtmlString(value);
        }
        //Extension method
        public static IHtmlString ImageExtension(this HtmlHelper helper, string src, string alt = "image", int width = 50, int height = 50)
        {
            var value = String.Format("<img src='{0}' alt='{1}' width='{2}' height='{3}'/>", src, alt, width, height);
            return new HtmlString(value);
        }
    }
}

src- image source (path)
alt- alternative text if image could not be loaded, and it is assigned a default value "Image". When no values is passed to this parameter it will take the default value "Image".
width & height- width and height of the image these parameters are also assigned a default value 50

Using the ImageStatic html helper method in view..
Index.cshtml:

@using HelperApplication.Helpers
<div>
     <span>ImageTag with default values for alt, width, height</span>     
     @CustomHelpers.ImageTag("../../images/image.png")
</div>
<div>
     <span>ImageTag with width=100 and height=100</span>     
     @CustomHelpers.ImageStatic("../../images/image.png","Image With alt",100,100)
</div>

The above code will render the images one with default dimensions(i.e width and height) and another one with given dimension (i.e width=100 and height=100)

2. Extension Methods:


This is another approach to create custom html helpers, here we will extend the functionality of the HtmlHelper class.

In the CustomHelper.cs class we have created another method called ImageExtension. We can see this HtmlHelper helper parameter, this implies that ImageExtension method extends functionality of HtmlHelper class. Thus, we can use this method just like other helper methods (Html.ActionLink() similarly Html.ImageExtension).

Note: To make our method accessible like other built-in helper methods we have to add namespace to webconfig file <add namespace="HelperApplication.Helpers"/> in ~/Views/web.config not in ~/web.config

Index.cshtml:
<div>
    <span>ImageTag with default values for alt, width, height</span>
     @Html.ImageExtension("../../images/image.png")
</div>
<div>
     <span>ImageTag with width=100 and height=100</span>
     @Html.ImageExtension("../../images/image.png","Image With alt",100,100)
</div>

3. @helper :