Integration of MSLine Fusion Chart with AngularJS and WebAPI

Rajnilari2015
Posted by in AngularJS 1x category on for Beginner level | Points: 250 | Views : 2562 red flag

Data Visualization is a very important aspect from the view point of an end user since it presents the visual representation of data. It brings clarity in communicating the information to the end users via the graphs, plots, tables, charts etc. It is through the application of proper and effective visualization that help users to analyze and reason about data and evidence which on the other hand brings more data accessibility, understand ability and thereby usability leading to make proper strategic decision.

FusionCharts, part of InfoSoft Global (P) Ltd, is privately held software provider of data visualization products (JavaScript Charts, Maps, Widgets and Dashboards).

In this article, we will look into the integration of MSLine Fusion Chart with AngularJS and WebAPI.


 Download source code for Integration of MSLine Fusion Chart with AngularJS and WebAPI

Introduction

Data Visualization is a very important aspect from the view point of an end user since it presents the visual representation of data. It brings clarity in communicating the information to the end users via the graphs, plots, tables, charts etc. It is through the application of proper and effective visualization that help users to analyze and reason about data and evidence which on the other hand brings more data accessibility, understand ability and thereby usability leading to make proper strategic decision.

FusionCharts, part of InfoSoft Global (P) Ltd, is privately held software provider of data visualization products (JavaScript Charts, Maps, Widgets and Dashboards).

In this article, we will look into the integration of MSLine Fusion Chart with AngularJS and WebAPI.

Objective

Consider a scenario where say 2 Cricket teams (say Team 1 and Team 2) are playing with each other for a T-20 match.The objective is to plot a Fusion Chart of type MSLine where the x-axis will display the Overs while the y-axis will display the Runs Made by the team(s) per over.

The final output should be as under

Using the code

Let us first create the data structure

public class RunsPerOver
{
    public string value { get; set; } //datum for total runs made by a team per over
}   

public class Category
{
    public string label { get; set; } //datum that contains the information about the sub-products on a day to day basis
}

/// <summary>
/// This class contains the information about the Match Overs. This will be plotted for x-axis
/// </summary>
public class MatchOvers
{
    public List<Category> category { get; set; }
}

/// <summary>
/// This class contains the information about the Team Info.This will be plotted for y-axis
/// </summary>
public class TeamInfo
{
    public string seriesname { get; set; } //team name
    public string color { get; set; } //team color
    public List<RunsPerOver> data { get; set; } //total runs made by a team per over
}

public class OverwiseTeamReport
{        
    public List<MatchOvers> matchOvers { get; set; }
    public List<TeamInfo> teamInfo { get; set; }
}

and then write the WebAPI as under

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebAPI2.Controllers
{    
    public class MSLineChartReportController : ApiController
    {       

        [Route("FusionChartReports/OverwiseTeamReport")]
        public OverwiseTeamReportGetOverwiseTeamReport()
        {
            return new OverwiseTeamReport{ matchOvers = GetMatchOvers(), teamInfo = GetTeamInfo() };
        }
        
        /// <summary>
        /// Generate match overs
        /// </summary>
        /// <returns></returns>
        private List<MatchOvers> GetMatchOvers()
        {
            var lstMatchOvers = new List<MatchOvers>();

            Enumerable
               .Range(0, 1)
               .ToList()
               .ForEach(i => lstMatchOvers.Add
                (
                    new MatchOvers
                    {
                        category = GenerateMatchOvers()
                    }
                ));
            return lstMatchOvers;
        }

        /// <summary>
        /// Get Team Information
        /// </summary>
        /// <returns></returns>
        private List<TeamInfo> GetTeamInfo()
        {
            var lstTeamInfo = new List<TeamInfo>();
            int noOfTeams = 2;

            Enumerable
               .Range(0, noOfTeams)
               .ToList()
               .ForEach(i => lstTeamInfo.Add
                (
                    new TeamInfo
                    {
                        seriesname = 
                                        i == 0 
                                        ?"Team 1" : i == 1 
                                        ? "Team 2" : string.Empty,

                        color =         i == 0 
                                        ? "#c9ff00" : i == 1 
                                        ? "#1984aa" : string.Empty,

                        data = GetRunsPerTeamPerOver(i)
                    }
                ));

            return lstTeamInfo;
        }

        /// <summary>
        /// Generate match overs
        /// </summary>
        /// <returns></returns>
        private List<Category> GenerateMatchOvers()
        {
            var lstMonthCategories = new List<Category>();
            int overs = 20;
           
            Enumerable
                .Range(1, overs)
                .ToList()
                .ForEach(i => lstMonthCategories.Add(new Category { label = i.ToString() }));
            return lstMonthCategories;
        }        
       
        /// <summary>
        /// Get Runs Per Team Per Over
        /// </summary>
        /// <returns></returns>

        private List<RunsPerOver> GetRunsPerTeamPerOver(int i)
        {
            var lstRunsPerOver = new List<RunsPerOver>();
            int overs = 20;
            var team1Runs = new[] { 2,3,5,6,7,8,9,11,14,15,16,18,20,22,24,26,27,29,30,34 };
            var team2Runs = new[] { 1, 4, 5, 7, 8, 10, 12, 14, 16,17, 18,19, 20, 23, 25, 26, 27, 29, 31, 35 };
            switch(i)
            {
                case 0:

                    for (int j = 0; j < overs; j++)
                        lstRunsPerOver.Add(new RunsPerOver { value = team1Runs[j].ToString() });
                    break;
                case 1:

                    for (int j = 0; j < overs; j++)
                        lstRunsPerOver.Add(new RunsPerOver { value = team2Runs[j].ToString() });
                    break;
            }            
            return lstRunsPerOver;
        }         
    }
}

When we ran this in PostMan, we receive the below JSON

{
    "matchOvers": [
        {
            "category": [
                {
                    "label": "1"
                },
                {
                    "label": "2"
                },
                {
                    "label": "3"
                },
                {
                    "label": "4"
                },
                {
                    "label": "5"
                },
                {
                    "label": "6"
                },
                {
                    "label": "7"
                },
                {
                    "label": "8"
                },
                {
                    "label": "9"
                },
                {
                    "label": "10"
                },
                {
                    "label": "11"
                },
                {
                    "label": "12"
                },
                {
                    "label": "13"
                },
                {
                    "label": "14"
                },
                {
                    "label": "15"
                },
                {
                    "label": "16"
                },
                {
                    "label": "17"
                },
                {
                    "label": "18"
                },
                {
                    "label": "19"
                },
                {
                    "label": "20"
                }
            ]
        }
    ],
    "teamInfo": [
        {
            "seriesname": "Team 1",
            "color": "#c9ff00",
            "data": [
                {
                    "value": "2"
                },
                {
                    "value": "3"
                },
                {
                    "value": "5"
                },
                {
                    "value": "6"
                },
                {
                    "value": "7"
                },
                {
                    "value": "8"
                },
                {
                    "value": "9"
                },
                {
                    "value": "11"
                },
                {
                    "value": "14"
                },
                {
                    "value": "15"
                },
                {
                    "value": "16"
                },
                {
                    "value": "18"
                },
                {
                    "value": "20"
                },
                {
                    "value": "22"
                },
                {
                    "value": "24"
                },
                {
                    "value": "26"
                },
                {
                    "value": "27"
                },
                {
                    "value": "29"
                },
                {
                    "value": "30"
                },
                {
                    "value": "34"
                }
            ]
        },
        {
            "seriesname": "Team 2",
            "color": "#1984aa",
            "data": [
                {
                    "value": "1"
                },
                {
                    "value": "4"
                },
                {
                    "value": "5"
                },
                {
                    "value": "7"
                },
                {
                    "value": "8"
                },
                {
                    "value": "10"
                },
                {
                    "value": "12"
                },
                {
                    "value": "14"
                },
                {
                    "value": "16"
                },
                {
                    "value": "17"
                },
                {
                    "value": "18"
                },
                {
                    "value": "19"
                },
                {
                    "value": "20"
                },
                {
                    "value": "23"
                },
                {
                    "value": "25"
                },
                {
                    "value": "26"
                },
                {
                    "value": "27"
                },
                {
                    "value": "29"
                },
                {
                    "value": "31"
                },
                {
                    "value": "35"
                }
            ]
        }
    ]
}

Now, it's time to consume the web services through AngularJS and use the Fusion msline Chart for the Data Visualization part.

For this to happen we will create a "OverwiseTeamReport.js" file where we will define the Module, Controller and the Service consumption.

var myApp = angular.module("myApp", []);
myApp.controller("OverwiseTeamReportController", function($scope, $http){

	$scope.displayChart = function(){

		FusionCharts.ready(function () {

		var overwiseTeamChart; //declare an object that will hold the instance of the FusionChart
		
		var chartLayout = {
			         	"caption": "Team Performance",
				        "xaxisname": "Overs",
				        "yaxisname": "Runs Made",       
				        "bgcolor": "FFFFFF",       
				        "canvasborderthickness": "1",
				        "showvalues": "0"
				  };
			
			//invoke the service			
			var promiseGet = $http.get("http://localhost:60422/FusionChartReports/OverwiseTeamReport");

			promiseGet.then(function (promiseObj) {				
							
					// binding the data
					$scope.dataSource = { 'chart' : chartLayout, 'categories': promiseObj.data.matchOvers, 'dataset': promiseObj.data.teamInfo };

					overwiseTeamChart = new FusionCharts({
										type: 'msline',
										renderAt: 'chartContainer',												
										width: "800",
										height: "500",
										dataFormat: 'json',
										dataSource : $scope.dataSource

									});

					//render the chart to the div which is chartContainer
					overwiseTeamChart.render("chartContainer");					
			},function (errorPl) { //if something went wrong
                  $log.error('failure loading the record', errorPl);
              }
          ); //end of promise object
		});//end Fusion Chart Ready Function
	}; //end function displayChart
}); //end controller

Here we are consuming the WebAPI by using the promise object and then merging the JSON in the way Fusion Chart needs that. The Fusion Data Source needs a)chart b)categories and c) dataset. The later two are coming from the API.

Finally we need to bind the data. For this, let us create "OverwiseTeamReport.html" and add the below script

<!DOCTYPE html>
<html>
	<head>
	  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
	  <title>Overwise TeamReport</title> 
	  <link href="css/custom.css" rel="stylesheet">
	  <link href="css/custom2.css" rel="stylesheet">  
	  <script data-require="angular.js@1.4.0-beta.6" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script> 
	  <script type='text/javascript' src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
	  <script type='text/javascript' src="http://static.fusioncharts.com/code/latest/fusioncharts.widgets.js"></script>     
	  <script type='text/javascript' src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"></script>
	  <script src="OverwiseTeamReport.js"></script>
	  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
	</head>
	<body ng-app="myApp"> 
		<div 
				id="chartContainer" 
				ng-controller="OverwiseTeamReportController" 
				align="center"  
				ng-init='displayChart()'>
		</div> 		 
	</body>
</html>

That's all we need to do for the complete integration.

N.B.~ This article assumes that users have previous experience in AngularJS and WebAPI. If not then here is a good point to start

  1. AngularJS How to tutorials
  2. CRUD Operation using Web API and MVC4

Conclusion

Hope this will be helpful. Thanks for reading the article. Zipped file attached.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)