Integration of StackedColumn2d Fusion Chart with AngularJS and WebAPI

Rajnilari2015
Posted by in AngularJS category on for Beginner level | Points: 250 | Views : 1049 red flag
Rating: 4 out of 5  
 2 vote(s)

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 StackedColumn2d Fusion Chart with AngularJS and WebAPI.


 Download source code for Integration of StackedColumn2d 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 StackedColumn2d Fusion Chart with AngularJS and WebAPI.

Objective

Consider a scenario where say 4 kind of sub-products of the type Loan product are available. Say these 4 sub-products are Car Loan, Educational Loan, House Loan and TV Loan.The objective is to plot a Fusion Chart of type StackedColumn2d where the x-axis will display the days (date-wise) on which how many sub-products were applied (consider it as the total number of days for the current month) and the y-axis will plot the No. of customers applied for the Loan.

The final output should be as under

Using the code

Let us first create the data structure

public class DaywiseSubProductCustomer
{
    public string value { get; set; } //datum for customers have applied for sub-product
}   

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 sub-products on a day to day basis. This will be plotted for x-axis
/// </summary>
public class DatewiseSubProductCategories
{
    public List<Category> category { get; set; }
}

/// <summary>
/// This class contains the information about the Subproduct and customer aplied for the Subproduct.This will be plotted for y-axis
/// </summary>
public class SubProductCustomer
{
    public string seriesname { get; set; } //sub-product name
    public string color { get; set; } //sub-product color
    public List<DaywiseSubProductCustomer> data { get; set; } //on a daily basis how many customers have applied for sub-product wise loan
}

public class CustomerSubProductReport
{        
    public List<DatewiseSubProductCategories> datewiseSubProductCategories { get; set; }
    public List<SubProductCustomer> subProductCustomer { get; set; }
}

and then write the WebAPI as under

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

namespace WebAPI2.Controllers
{    
    public class FusionChartReportController : ApiController
    {      

        [Route("FusionChartReports/CustomerSubProductWiseMonthlyReport")]
        public CustomerSubProductReport GetCustomerSubProductWiseMonthlyReport()
        {
            return new CustomerSubProductReport { datewiseSubProductCategories = GetDatewiseSubProductCategories(), subProductCustomer = GetMonthlyCustomerReportSubProductWise() };
        }
        
        /// <summary>
        /// Get Datewise SubProduct Categories 
        /// </summary>
        /// <returns></returns>
        private List<DatewiseSubProductCategories> GetDatewiseSubProductCategories()
        {
            var lstChartCategories = new List<DatewiseSubProductCategories>();

            Enumerable
               .Range(0, 1)
               .ToList()
               .ForEach(i => lstChartCategories.Add
                (
                    new DatewiseSubProductCategories
                    {
                         category = GetCategoriesOfTheMonth()
                    }
                ));
            return lstChartCategories;
        }

        /// <summary>
        /// Get Monthly Customer Report SubProductWise
        /// </summary>
        /// <returns></returns>
        private List<SubProductCustomer> GetMonthlyCustomerReportSubProductWise()
        {
            var lstProductLeadData = new List<SubProductCustomer>();

            Enumerable
               .Range(0, 4)
               .ToList()
               .ForEach(i => lstProductLeadData.Add
                (
                    new SubProductCustomer
                    {
                        seriesname = 
                                        i == 0 
                                        ?"Car Loan" : i == 1 
                                        ? "Educational Loan" : i == 2 
                                        ? "House Loan" : i == 3
                                        ? "TV Loan" : string.Empty,

                        color = i == 0 ? "#c9ff00" : i == 1 ? "#1984aa" : i == 2 ? "#09a5ff" : i == 3 ? "#a1ffc0" : string.Empty,

                        data = GetDaywiseCustomerCountForLoanApplied()
                    }
                ));

            return lstProductLeadData;
        }

        /// <summary>
        /// Get Categories Of The Month
        /// </summary>
        /// <returns></returns>
        private List<Category> GetCategoriesOfTheMonth()
        {
            var lstMonthCategories = new List<Category>();
           
            Enumerable
                .Range(1, GetTotalNoOfDaysInCurrentMonth())
                .ToList()
                .ForEach(i => lstMonthCategories.Add(new Category { label = i.ToString() }));
            return lstMonthCategories;
        }

        /// <summary>
        /// Get Total No Of Days In CurrentMonth
        /// </summary>
        /// <returns></returns>
        private int GetTotalNoOfDaysInCurrentMonth()
        {
            DateTime date = DateTime.Now;
            var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
            var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
            return Convert.ToInt32((lastDayOfMonth - firstDayOfMonth).TotalDays)+1;            
        }
       
        /// <summary>
        /// Get Daywise Customer Count For Loan Applied
        /// </summary>
        /// <returns></returns>

        private List<DaywiseSubProductCustomer> GetDaywiseCustomerCountForLoanApplied()
        {
            var lstDaywiseSubProductCustomer = new List<DaywiseSubProductCustomer>();
            Enumerable
                .Range(1, GetTotalNoOfDaysInCurrentMonth())
                .ToList()
                .ForEach(i => lstDaywiseSubProductCustomer.Add(new DaywiseSubProductCustomer { value = GetRandomNumbers(0, 100).ToString() }));
            return lstDaywiseSubProductCustomer;
        }

        /// <summary>
        /// generate random numbers
        /// </summary>
        private static readonly Random random = new Random();
        private static readonly object syncLock = new object();
        private static int GetRandomNumbers(int minVal, int maxVal)
        {
            lock (syncLock) return random.Next(minVal, maxVal);
        }       
    }    
}

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

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

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

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

	$scope.displayChart = function(){

		FusionCharts.ready(function () {

		var productwiseMonthlyChart; //declare an object that will hold the instance of the FusionChart
		
		var chartLayout = {
         	"caption": "Customer Application Daywise Report",
	        "showvalues": "0",
			"xaxisname": "Date",
			"yaxisname": "No Of Customer",
	        "plotfillalpha": "95",
	        "formatnumberscale": "0",
	        "showborder": "0"
	  };
			
			//invoke the service			
			var promiseGet = $http.get("http://localhost:60422/FusionChartReports/CustomerSubProductWiseMonthlyReport");

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

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

										});

					//render the chart to the div which is chartContainer
					productwiseMonthlyChart.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 "ProductwiseMonthlyReport.html" and add the below script

<!DOCTYPE html>
<html>
	<head>
	  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
	  <title>Product-wise monthly report in current year</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="ProductwiseMonthlyReport.js"></script>
	  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
	</head>
	<body ng-app="myApp"> 
		<div 
				id="chartContainer" 
				ng-controller="ProductwiseMonthlyReportController" 
				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)