Introduction

In this article, we will see in detail about how to create a Dynamic MVC dashboard with the chart and data display, using AngularJS and WEB API. Using this Web Application, you can write your own SQL query to bind the dynamic dashboard with the chart and data. This program makes your work easy in displaying any table/columns details with your entered where condition, order by, and group by options for the selected database on your home page with both the data and chart.



In our previous article,

We explained in detail about how to display any data on the home page dashboard on our MVC Web Application. In this article, we will see in detail about how to display the data and chart on the dashboard in MVC Web Application, using AngularJs and Web API.

In this demo Application, we have drawn a pie chart in our MVC dashboard page. You can draw any chart as per your requirement. In our previous article, we have explained about how to draw a chart such as Line, Pie, Bar, Donut, Bubble and Line and Bar Chart in MVC Application .
We have used the same logic to draw the chart on our MVC dashboard page.

Features in Shanu MVC Dashboard

  1. Dynamic SQL Query

  2. Column Names

  3. Table Names

  4. Where Condition

  5. Group By

  6. Order By

  7. Chart SQL Query

  8. Chart Setting and Draw Chart

    Here, we will see the details of each part.

    Kindly refer to our previous article MVC Dashboard Using AngularJS And Web API
    for the sections from 1 to 6. We have explained in detail about each section with the animated images.

    This article has all the same features with the additional chart feature, to be displayed on our MVC dashboard.

  9. Chart SQL Query: To display the chart first, we need to write our Select query to display both the chart item and the value.



    Here, the sample query is used to display the chart in our MVC dashboard page. Here, for chart binding; the user can enter the complete Select query to bind the result in the Combo box.

    Sample Select query to be used for our Application is given below:
    1. Select ItemName as Name,SUM(Price) as Value FROM ItemDetail GROUP BY ItemName ORDER BY Value,Name
    To draw a chart, we have fixed the standard -- as always display two columns, where one is the name and another one is the value. Here, the name is any name (Legend) to be displayed for a chart and a value is the actual value to draw the chart. In search button click, we first bind the chart item to the Combo box. We will be using this Combo box result to draw the chart.

  10. Chart Setting and Draw Chart

    A user can add Chart Title and Watermark text, as per his requirement at the run time and click “Click to Draw Chart) button to draw your chart on the dashboard.

Note

You can display any chart data from any table from the given database. All you need to do is, write the Select query for the chart with the name and value column.

Prerequisites

Visual Studio 2015: You can download it from here.

Code Part

Step 1:

Create a sample database and table to test this Application. Here is a SQL Script to create the database and the table with Insert query. Kindly run the code, given below, in your SQL Server to create DB and the tables.

  1. USE MASTER
  2. GO
  3. --1) Check for the Database Exists .If the database is exist then drop and create new DB
  4. IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'DashboardDB' )
  5. DROP DATABASE DashboardDB
  6. GO
  7. CREATE DATABASE DashboardDB
  8. GO
  9. USE DashboardDB
  10. GO
  11. -- 1) //////////// ItemDetails table
  12. -- Create Table ItemDetails,This table will be used to store the details like Item Information
  13. IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'ItemDetail' )
  14. DROP TABLE ItemDetail
  15. GO
  16. CREATE TABLE [dbo].[ItemDetail](
  17. [ID] [int] IDENTITY(1,1) NOT NULL,
  18. [ItemNo] [varchar](100) NOT NULL ,
  19. [ItemName] [varchar](100) NOT NULL,
  20. [Comments] [varchar](100) NOT NULL,
  21. [Price] INT NOT NULL,
  22. PRIMARY KEY CLUSTERED
  23. (
  24. [ID] ASC
  25. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  26. ) ON [PRIMARY]
  27. GO
  28. Insert into ItemDetail(ItemNo,ItemName,Comments,Price) values
  29. ('101','NoteBook', 'HP Notebook 15 Inch', 24500)
  30. Insert into ItemDetail(ItemNo,ItemName,Comments,Price) values
  31. ('102','MONITOR', 'SAMSNG', '8500')
  32. Insert into ItemDetail(ItemNo,ItemName,Comments,Price) values
  33. ('103','MOBILE', 'SAMSUNG NOTE 5', 42500)
  34. Insert into ItemDetail(ItemNo,ItemName,Comments,Price) values
  35. ('104','MOBILE', 'SAMSUNG S7 Edge', 56000)
  36. Insert into ItemDetail(ItemNo,ItemName,Comments,Price) values
  37. ('105','MOUSE', 'ABKO', 780)
  38. Insert into ItemDetail(ItemNo,ItemName,Comments,Price) values
  39. ('106','HDD' ,'LG', 3780)
  40. select * from ItemDetail
  41. select ItemName,SUM(convert(int,Price)) as totalCost
  42. from ItemDetail
  43. GROUP BY ItemName
  44. -- 2) User table
  45. IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'UserDetails' )
  46. DROP TABLE UserDetails
  47. GO
  48. CREATE TABLE [dbo].UserDetails(
  49. [UserID] [int] IDENTITY(1,1) NOT NULL,
  50. [UserName] [varchar](100) NOT NULL,
  51. [UserType] [varchar](100) NOT NULL,
  52. [Phone] [varchar](20) NOT NULL,
  53. PRIMARY KEY CLUSTERED
  54. (
  55. [UserID] ASC
  56. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  57. ) ON [PRIMARY]
  58. Insert into UserDetails(UserName,UserType,Phone) values
  59. ('SHANU','Admin','01039124503')
  60. Insert into UserDetails(UserName,UserType,Phone) values
  61. ('Afraz','user','01039120984')
  62. Insert into UserDetails(UserName,UserType,Phone) values
  63. ('Afreen','user','01039120005')
  64. Insert into UserDetails(UserName,UserType,Phone) values
  65. ('Raj','Admin','01039120006')
  66. Insert into UserDetails(UserName,UserType,Phone) values
  67. ('Mak','Manager','01039124567')
  68. Insert into UserDetails(UserName,UserType,Phone) values
  69. ('Jack','Manager','01039120238')
  70. Insert into UserDetails(UserName,UserType,Phone) values
  71. ('Pak','User','01039125409')
  72. Insert into UserDetails(UserName,UserType,Phone) values
  73. ('Ninu','Accountant','01039126810')
  74. Insert into UserDetails(UserName,UserType,Phone) values
  75. ('Nanu','Accountant','01039152011')
  76. -- select * from Userdetails
  77. -- 3 UserAddress
  78. IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'UserAddress' )
  79. DROP TABLE UserAddress
  80. GO
  81. CREATE TABLE [dbo].UserAddress(
  82. [UserAddID] [int] IDENTITY(1,1) NOT NULL,
  83. [UserID] [int] ,
  84. [Address] [varchar](200) NOT NULL,
  85. [Email] [varchar](100) NOT NULL,
  86. PRIMARY KEY CLUSTERED
  87. (
  88. [UserAddID] ASC
  89. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  90. ) ON [PRIMARY]
  91. Insert into UserAddress(UserID,Address,Email) values
  92. (1,'Madurai,Tamil Nadu, India','[email protected]')
  93. Insert into UserAddress(UserID,Address,Email) values
  94. (2,'Madurai,Tamil Nadu, India','[email protected]')
  95. Insert into UserAddress(UserID,Address,Email) values
  96. (3,'Seoul,South Korea','[email protected]')
  97. select * from UserAddress
  98. select A.UserName,A.UserType,A.Phone,B.Address,B.Email
  99. From
  100. Userdetails A Left Outer JOIN UserAddress B
  101. on
  102. A.UserID=B.UserID
Create Stored Procedure to run Dynamic Query

This is our main stored procedure used to run all our dynamic SQL Select queries and return the result to bind in our MVC page.
  1. USE [DashboardDB]
  2. GO
  3. /****** Object: StoredProcedure [dbo].[USP_Dashboard_Select] ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. -- 1) select top 10 random kidsLearnerMaster records
  9. -- Author : Shanu
  10. -- Create date : 2016-05-14
  11. -- Description :To run dymanic Query
  12. -- Tables used : Dynamic Table
  13. -- Modifier : Shanu
  14. -- Modify date : 2016-05-14
  15. -- =============================================
  16. -- To Select all user roles
  17. -- EXEC USP_Dashboard_Select @columnName = 'UserName,UserType,Phone' ,@TableNames = 'UserDetails' ,@isCondition=0,@ConditionList='UserType=''ADMIN'' ',@isGroupBY =1,@GroupBYList = 'UserName,UserType,Phone', @isOrderBY =1,@OrderBYList = ' UserType '
  18. -- EXEC USP_Dashboard_Select @columnName = 'ItemName,SUM(Price) as totalCost' ,@TableNames = 'ItemDetail' ,@isCondition=0,@ConditionList='Price>''400'' ',@isGroupBY =1,@GroupBYList = 'ItemName'
  19. -- EXEC USP_Dashboard_Select @sqlQuery = 'Select * from ItemDetail'
  20. -- EXEC USP_Dashboard_Select @sqlQuery = 'select ID,ItemNo ,ItemName ,Comments ,Price from ItemDetail'
  21. -- =============================================
  22. ALTER PROCEDURE [dbo].[USP_Dashboard_Select]
  23. (
  24. @sqlQuery varchar(MAX)='',
  25. @columnName varchar(MAX)='',
  26. @TableNames varchar(MAX)='',
  27. @isCondition INT=0,
  28. @ConditionList varchar(MAX)='',
  29. @isGroupBY INT=0,
  30. @GroupBYList varchar(MAX)='',
  31. @isOrderBY INT=0,
  32. @OrderBYList varchar(MAX)=''
  33. )
  34. AS
  35. BEGIN
  36. BEGIN TRY
  37. IF @sqlQuery =''
  38. BEGIN
  39. SET @sqlQuery = 'SELECT ' + @columnName + ' FROM ' + @TableNames
  40. IF @isCondition=1
  41. BEGIN
  42. SET @sqlQuery = @sqlQuery+ ' WHERE ' + @ConditionList
  43. END
  44. IF @isGroupBY=1
  45. BEGIN
  46. SET @sqlQuery = @sqlQuery+ ' GROUP BY ' + @GroupBYList
  47. END
  48. IF @isOrderBY=1
  49. BEGIN
  50. SET @sqlQuery = @sqlQuery+ ' Order BY ' + @OrderBYList
  51. END
  52. EXEC (@sqlQuery)
  53. END
  54. ELSE
  55. BEGIN
  56. EXEC (@sqlQuery)
  57. END
  58. END TRY
  59. BEGIN CATCH
  60. SELECT ERROR_NUMBER() AS ErrorNumber
  61. ,ERROR_MESSAGE() AS ErrorMessage;
  62. END CATCH
  63. END
Step 2: Create your MVC Web Application in Visual Studio 2015

After installing our Visual Studio 2015; click Start, followed by Programs, and select Visual Studio 2015. Click Visual Studio 2015. Click New, followed by Project, select Web and then select ASP.NET Web Application. Enter your project name and click OK.



Select MVC, WEB API and click OK.



Now, we have created our MVC Application. As a next step, we add our connection string in our Web.Config file. Here, we are not using entity framework. Here, we will directly get the data from our MVC Web API controller method, using the normal ADO.NET method.
  1. <add name="dashboard" connectionString="Data Source=SQLSERVERNAME;Initial Catalog=DashboardDB;Persist Security Info=True;User ID=UID;Password=PWD" providerName="System.Data.SqlClient" />
Kindly update with your SQL Server connection.

Step 3: Add web API Controller

Right click Controllers folder, click Add and click Controller.



Here, we will add a WEB API Controller to be used for our AngularJS.

Select Web API 2 Controller – Empty and click Add .next, enter the controller name as DashboardAPIController

Get Method

Here, use the Http GET method to get all our dynamic data from the database, using normal ADO.NET method.

  1. [HttpGet]
  2. public string getDashboardDetails(string sqlQuery, string columnName, string tableNames, Nullable<int> isCondition, string conditionList, Nullable<int> isGroupBY, string groupBYList, Nullable<int> isOrderBY, string orderBYList)
  3. {
  4. if (sqlQuery == null)
  5. sqlQuery = "";
  6. if (columnName == null)
  7. columnName = "";
  8. if (tableNames == null)
  9. tableNames = "";
  10. if (isCondition == null)
  11. isCondition = 0;
  12. if (conditionList == null)
  13. conditionList = "";
  14. if (isGroupBY == null)
  15. isGroupBY = 0;
  16. if (groupBYList == null)
  17. groupBYList = "";
  18. if (isOrderBY == null)
  19. isOrderBY = 0;
  20. if (orderBYList == null)
  21. orderBYList = "";
  22. string connectionString = ConfigurationManager.ConnectionStrings["dashboard"].ToString();
  23. DataSet ds = new DataSet();
  24. using (SqlConnection connection = new SqlConnection(connectionString))
  25. {
  26. // Create the SQL command and add Sp name
  27. SqlCommand command = new SqlCommand();
  28. command.Connection = connection;
  29. command.CommandText = "USP_Dashboard_Select";
  30. command.CommandType = CommandType.StoredProcedure;
  31. // Add parameter for Query.
  32. SqlParameter parameter = new SqlParameter();
  33. parameter.ParameterName = "@sqlQuery";
  34. parameter.SqlDbType = SqlDbType.NVarChar;
  35. parameter.Direction = ParameterDirection.Input;
  36. parameter.Value = sqlQuery;
  37. command.Parameters.Add(parameter);
  38. // Add parameter for Column Names
  39. SqlParameter parameter1 = new SqlParameter();
  40. parameter1.ParameterName = "@columnName";
  41. parameter1.SqlDbType = SqlDbType.NVarChar;
  42. parameter1.Direction = ParameterDirection.Input;
  43. parameter1.Value = columnName;
  44. command.Parameters.Add(parameter1);
  45. // Add parameter for Table names
  46. SqlParameter parameter2 = new SqlParameter();
  47. parameter2.ParameterName = "@tableNames";
  48. parameter2.SqlDbType = SqlDbType.NVarChar;
  49. parameter2.Direction = ParameterDirection.Input;
  50. parameter2.Value = tableNames;
  51. command.Parameters.Add(parameter2);
  52. // Add parameter to check for Where condition
  53. SqlParameter parameter3 = new SqlParameter();
  54. parameter3.ParameterName = "@isCondition";
  55. parameter3.SqlDbType = SqlDbType.NVarChar;
  56. parameter3.Direction = ParameterDirection.Input;
  57. parameter3.Value = isCondition;
  58. command.Parameters.Add(parameter3);
  59. // Add parameter for Where conditions
  60. SqlParameter parameter4 = new SqlParameter();
  61. parameter4.ParameterName = "@ConditionList";
  62. parameter4.SqlDbType = SqlDbType.NVarChar;
  63. parameter4.Direction = ParameterDirection.Input;
  64. parameter4.Value = conditionList;
  65. command.Parameters.Add(parameter4);
  66. // Add parameter to check for Group By
  67. SqlParameter parameter5 = new SqlParameter();
  68. parameter5.ParameterName = "@isGroupBY";
  69. parameter5.SqlDbType = SqlDbType.NVarChar;
  70. parameter5.Direction = ParameterDirection.Input;
  71. parameter5.Value = isGroupBY;
  72. command.Parameters.Add(parameter5);
  73. // Add parameter for Group By
  74. SqlParameter parameter6 = new SqlParameter();
  75. parameter6.ParameterName = "@groupBYList";
  76. parameter6.SqlDbType = SqlDbType.NVarChar;
  77. parameter6.Direction = ParameterDirection.Input;
  78. parameter6.Value = groupBYList;
  79. command.Parameters.Add(parameter6);
  80. // Add parameter to check for Order By
  81. SqlParameter parameter7 = new SqlParameter();
  82. parameter7.ParameterName = "@isOrderBY";
  83. parameter7.SqlDbType = SqlDbType.NVarChar;
  84. parameter7.Direction = ParameterDirection.Input;
  85. parameter7.Value = isOrderBY;
  86. command.Parameters.Add(parameter7);
  87. // Add parameter for OrderBY
  88. SqlParameter parameter8 = new SqlParameter();
  89. parameter8.ParameterName = "@orderBYList";
  90. parameter8.SqlDbType = SqlDbType.NVarChar;
  91. parameter8.Direction = ParameterDirection.Input;
  92. parameter8.Value = orderBYList;
  93. command.Parameters.Add(parameter8);
  94. connection.Open();
  95. using (SqlDataAdapter da = new SqlDataAdapter(command))
  96. {
  97. da.Fill(ds);
  98. connection.Close();
  99. }
  100. }
  101. return DataTableToJSONWithJavaScriptSerializer(ds.Tables[0]);
  102. }
Step 4: Creating AngularJs Controller

First, create a folder inside the Script Folder and we give the folder name as “MyAngular”.

Now, add your Angular Controller inside the folder.

Right Click the MyAngular Folder and click Add and New Item > Select Web > Select AngularJs Controller and give the name to Controller. We have given my AngularJs Controller as “Controller.js”.



If the Angular JS package is missing, then add the package to your project.

Right Click your MVC project and Click-> Manage NuGet Packages. Search for AngularJs and click Install.

Modules.js: Here, we will add the reference to the AngularJS JavaScript and create an Angular Module named “AngularJs_Module”.
  1. // <reference path="../angular.js" />
  2. /// <reference path="../angular.min.js" />
  3. /// <reference path="../angular-animate.js" />
  4. /// <reference path="../angular-animate.min.js" />
  5. var app;
  6. (function () {
  7. app = angular.module("dashbordModule", ['ngAnimate']);
  8. })();
Controllers: In AngularJS Controller, we have done all the business logic and returned the data from Web API to our MVC HTML page.

Variable declarations

First, we declare all the local variables required to be used.

  1. app.controller("AngularJs_Controller", function ($scope, $filter, $timeout, $rootScope, $window, $http) {
  2. $scope.date = new Date();
  3. $scope.MyName = "shanu";
  4. $scope.isQuerys = false;
  5. $scope.Querys = "";
  6. $scope.ColumnNames = "UserName,UserType,Phone";
  7. $scope.TableNames = "UserDetails";
  8. $scope.isCondition = false;
  9. $scope.whereCondition = 0;
  10. $scope.Conditions = "";
  11. $scope.isGroupBy = false;
  12. $scope.GroupBy = 0;
  13. $scope.GroupBys = "";
  14. $scope.isOrderBy = false;
  15. $scope.OrderBy = 0;
  16. $scope.OrderBys = "";
  17. // Array value to check for SQL Injection
  18. $scope.sqlInjectionArray = ['create', 'drop', 'delete', 'insert', 'update', 'truncate',
  19. 'grant', 'print', 'sp_executesql', 'objects', 'declare',
  20. 'table', 'into', 'sqlcancel', 'sqlsetprop', 'sqlexec',
  21. 'sqlcommit', 'revoke', 'rollback', 'sqlrollback', 'values',
  22. 'sqldisconnect', 'sqlconnect', 'system_user', 'schema_name',
  23. 'schemata', 'information_schema', 'dbo', 'guest', 'db_owner',
  24. 'db_', 'table', '@@', 'Users', 'execute', 'sysname', 'sp_who',
  25. 'sysobjects', 'sp_', 'sysprocesses', 'master', 'sys', 'db_',
  26. 'is_', 'exec', 'end', 'xp_', '; --', 'alter', 'begin', 'cursor',
  27. 'kill', '--', 'tabname', 'sys'];
  28. // Declaration for Chart
  29. $scope.chartQuerys = "Select ItemName as Name,SUM(Price) as Value FROM ItemDetail GROUP BY ItemName ORDER BY Value,Name";
  30. $scope.sItemName = "";
  31. $scope.itemCount = 5;
  32. $scope.selectedItem = "MOUSE";
  33. $scope.chartTitle = "SHANU Item Sales Chart";
  34. $scope.waterMark = "SHANU";
  35. $scope.ItemValues = 0;
  36. $scope.ItemNames = "";
  37. $scope.minsnew = 0;
  38. $scope.maxnew = 0;
Search Method

In this method, we call on search button click. Here, we check for all the validation of the user entered data, before passing all the parameters to our Web API method. In this method, we have commented to check each condition.

In this method, we call the searchbildChartData method to bind the select result to the Combo box.

  1. //search Details
  2. $scope.searchDetails = function () {
  3. // 1. Check for Select Query -> In this fucntion we check for SQL injection in user entered select query if any key word from the array list is found then we give msg to user to entert he valid select query
  4. if ($scope.isQuerys == true) {
  5. if ($scope.Querys != "") {
  6. $scope.whereCondition = 1;
  7. for (var i = 0; i < $scope.sqlInjectionArray.length-1; i++) {
  8. if ($filter('lowercase')($scope.Querys).match($scope.sqlInjectionArray[i])) {
  9. alert("Sorry " + $scope.sqlInjectionArray[i] + " keyword is not accepted in select query");
  10. return;
  11. }
  12. }
  13. searchTableDetails($scope.Querys, $scope.ColumnNames, $scope.TableNames, $scope.whereCondition, $scope.Conditions, $scope.GroupBy, $scope.GroupBys, $scope.OrderBy, $scope.OrderBys);
  14. return;
  15. }
  16. else {
  17. alert("Enter Your Select Query !");
  18. return;
  19. }
  20. }
  21. else
  22. {
  23. $scope.Querys = "";
  24. }
  25. // 2. Check for Column Names -> If user entered the valid column names the details will be checkd and binded in page
  26. if ($scope.ColumnNames == "") {
  27. alert("Enter the Column Details !");
  28. return;
  29. }
  30. else
  31. {
  32. for (var i = 0; i < $scope.sqlInjectionArray.length - 1; i++) {
  33. if ($filter('lowercase')($scope.ColumnNames).match($scope.sqlInjectionArray[i])) {
  34. alert("Sorry " + $scope.sqlInjectionArray[i] + " keyword is not accepted in Column Names");
  35. return;
  36. }
  37. }
  38. }
  39. // 3. Check for Table Names -> If user entered the valid Table names the details will be checkd and binded in page
  40. if ($scope.TableNames == "") {
  41. alert("Enter the Table Details !");
  42. return;
  43. }
  44. else {
  45. for (var i = 0; i < $scope.sqlInjectionArray.length - 1; i++) {
  46. if ($filter('lowercase')($scope.TableNames).match($scope.sqlInjectionArray[i])) {
  47. alert("Sorry " + $scope.sqlInjectionArray[i] + " keyword is not accepted in Table Names");
  48. return;
  49. }
  50. }
  51. }
  52. // 4. Check for Where condition -> If user check the Where condition check box, the user entered where condition will be added to the select query
  53. if ($scope.isCondition == true) {
  54. if ($scope.Conditions == "") {
  55. alert("Enter the Where Condition !");
  56. return;
  57. }
  58. else {
  59. for (var i = 0; i < $scope.sqlInjectionArray.length - 1; i++) {
  60. if ($filter('lowercase')($scope.Conditions).match($scope.sqlInjectionArray[i])) {
  61. alert("Sorry " + $scope.sqlInjectionArray[i] + " keyword is not accepted in Where Condition");
  62. return;
  63. }
  64. }
  65. $scope.whereCondition = 1;
  66. }
  67. }
  68. else {
  69. $scope.whereCondition = 0;
  70. }
  71. // 5. Check for GroupBy condition -> If user check the GroupBy condition check box, the user entered GroupBy condition will be added to the select query
  72. if ($scope.isGroupBy == true) {
  73. if ($scope.GroupBys == "") {
  74. alert("Enter the Group By Details !");
  75. return;
  76. }
  77. else {
  78. for (var i = 0; i < $scope.sqlInjectionArray.length - 1; i++) {
  79. if ($filter('lowercase')($scope.GroupBys).match($scope.sqlInjectionArray[i])) {
  80. alert("Sorry " + $scope.sqlInjectionArray[i] + " keyword is not accepted in GroupBy");
  81. return;
  82. }
  83. }
  84. $scope.GroupBy = 1;
  85. }
  86. }
  87. else {
  88. $scope.GroupBy = 0;
  89. }
  90. // 6. Check for OrderBy condition -> If user check the OrderBy condition check box, the user entered OrderBy condition will be added to the select query
  91. if ($scope.isOrderBy == true) {
  92. if ($scope.OrderBys == "") {
  93. alert("Enter the Group By details !");
  94. return;
  95. }
  96. else {
  97. for (var i = 0; i < $scope.sqlInjectionArray.length - 1; i++) {
  98. if ($filter('lowercase')($scope.OrderBys).match($scope.sqlInjectionArray[i])) {
  99. alert("Sorry " + $scope.sqlInjectionArray[i] + " keyword is not accepted in OrderBy");
  100. return;
  101. }
  102. }
  103. $scope.OrderBy = 1;
  104. }
  105. }
  106. else {
  107. $scope.OrderBy = 0;
  108. }
  109. searchTableDetails($scope.Querys, $scope.ColumnNames, $scope.TableNames, $scope.whereCondition, $scope.Conditions, $scope.GroupBy, $scope.GroupBys, $scope.OrderBy, $scope.OrderBys);
  110. // 7. Check for Chart Select Query -> In this fucntion we check for SQL injection in user entered select query if any key word from the array list is found then we give msg to user to entert he valid select query
  111. if ($scope.chartQuerys != "") {
  112. $scope.whereCondition = 0;
  113. for (var i = 0; i < $scope.sqlInjectionArray.length - 1; i++) {
  114. if ($filter('lowercase')($scope.chartQuerys).match($scope.sqlInjectionArray[i])) {
  115. alert("Sorry " + $scope.sqlInjectionArray[i] + " keyword is not accepted in select query");
  116. return;
  117. }
  118. }
  119. searchbildChartData($scope.chartQuerys, $scope.ColumnNames, $scope.TableNames, $scope.whereCondition, $scope.Conditions, $scope.GroupBy, $scope.GroupBys, $scope.OrderBy, $scope.OrderBys);
  120. return;
  121. }
  122. else {
  123. alert("Enter Your Chart Select Query !");
  124. return;
  125. }
  126. }
Main Search Method

Finally, after the validation, we call our main bind method to pass all the parameters to our WEB API to get the dynamic data from the database.

  1. // Main Select and Bind function
  2. //All query details entered by user after validation this method will be called to bind the result to the Dashboard page.
  3. function searchTableDetails(sqlQuery, columnName, tableNames, isCondition, conditionList, isGroupBY, groupBYList, isOrderBY, orderBYList) {
  4. $http.get('/api/DashboardAPI/getDashboardDetails/', { params: { sqlQuery: sqlQuery, columnName: columnName, tableNames: tableNames, isCondition: isCondition, conditionList: conditionList, isGroupBY: isGroupBY, groupBYList: groupBYList, isOrderBY: isOrderBY, orderBYList: orderBYList } }).success(function (data) {
  5. $scope.dashBoadData = angular.fromJson(data);;
  6. //alert($scope.dashBoadData.length);
  7. //if ($scope.dashBoadData.length > 0) {
  8. //}
  9. })
  10. .error(function () {
  11. $scope.error = "An Error has occured while loading posts!";
  12. });
  13. }
Chart Data Bind Method

This method will be called from our main method to bind the result to combobox to draw our Pie chart.

  1. // For binding the Chart result to Listbox before bind result to Chart
  2. function searchbildChartData(sqlQuery, columnName, tableNames, isCondition, conditionList, isGroupBY, groupBYList, isOrderBY, orderBYList) {
  3. $http.get('/api/DashboardAPI/getDashboardDetails/', { params: { sqlQuery: sqlQuery, columnName: columnName, tableNames: tableNames, isCondition: isCondition, conditionList: conditionList, isGroupBY: isGroupBY, groupBYList: groupBYList, isOrderBY: isOrderBY, orderBYList: orderBYList } }).success(function (data) {
  4. $scope.itemData = angular.fromJson(data);
  5. $scope.itemCount = $scope.itemData.length;
  6. $scope.selectedItem = $scope.itemData[0].Name;
  7. $scope.minsnew = $scope.itemData[0].Value;
  8. $scope.maxnew = $scope.itemData[$scope.itemData.length-1].Value;
  9. })
  10. .error(function () {
  11. $scope.error = "An Error has occured while loading posts!";
  12. });
  13. }
Step 5: Draw Pie Chart for our Dashboard.

We are using jQuery to draw our Pie Chart. In draw chart button, Click event, and we call the draw Pie Chart jQuery method to draw our chart. In this method, we get the chart value and name from the Combo box and draw the chart on the canvas tag, which we placed on our MVC Dashboard main page.

  1. function drawPieChart() {
  2. var lastend = 0;
  3. var XvalPosition = xSpace;
  4. chartWidth = (canvas.width / 2) - xSpace;
  5. chartHeight = (canvas.height / 2) - (xSpace / 2);
  6. widthcalculation = parseInt(((parseInt(chartWidth) - 100) / noOfPlots));
  7. //Draw Xaxis Line
  8. //-- draw bar X-Axis and Y-Axis Line
  9. var XLineStartPosition = xSpace;
  10. var yLineStartPosition = xSpace;
  11. var yLineHeight = chartHeight;
  12. var xLineWidth = chartWidth;
  13. colorval = 0;
  14. var chartTotalResult = getChartTotal();
  15. $('#DropDownList1 option').each(function () {
  16. if (isNaN(parseInt($(this).val()))) {
  17. }
  18. else
  19. {
  20. ctx.fillStyle = pirChartColor[colorval];
  21. ctx.beginPath();
  22. ctx.moveTo(chartWidth, chartHeight);
  23. //Here we draw the each Pic Chart arc with values and size.
  24. ctx.arc(chartWidth, chartHeight + 6, chartHeight, lastend, lastend +
  25. (Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult)), false);
  26. ctx.lineTo(chartWidth, chartHeight);
  27. ctx.fill();
  28. lastend += Math.PI * 2 * (parseInt($(this).val()) / chartTotalResult);
  29. //END Draw Bar Graph **************==================********************
  30. }
  31. colorval = colorval + 1;
  32. });
    }