In most cases, our web programs not only need to provide specific data to the user, in some cases, we also need to give advanced users or managers to provide data aggregation and analysis of functions such as charts.
If we don't want to show a bunch of annoying data, and we want to visualize the data visually with pie or bar charts, we can consider using a chart control to display it.
In the following article, we will introduce you to the implementation of the data dashboard program.
There was an article about the programming trend on StackOverflow, which showed us the hot problem tags on the StackOverflow through bars and area diagrams.
Figure 1 Popular tags in StackOverflow
With the above diagram, we can intuitively understand the trends of the popular tags on the StackOverflow, and now we are implementing the same functionality through the instrumentation program.
In the dashboard interface, we display the data through pie, area, and bar charts, where we use the Google Charts control to display pie, area, and bar graphs.
Google charts through JavaScript to achieve dynamic picture rendering, it is very simple to use, we just give the corresponding drawing function to pass the corresponding data, we can generate the corresponding data graph.
UI Design
Figure 2 Dashboard Interface
Now that we're going to display the pie, area, and bar of the data in the main interface (Dashboard), we use the Google charts control to dynamically load three graphics into the index.cshtml page, and here's the index.cshtml page code:
<!--Dashboard UI START-->
<body>
<div>
@{html.renderaction ("Dashboard_pie", " DashBoard "); }
</div>
<div>
@{html.renderaction ("Dashboard_areachart", "Dashboard");}
</div>
<div>
@{html.renderaction ("Dashboard_columnchart", "Dashboard");}
</div>
</body>
<!--Dashboard UI end-->
Above, we define three div elements, index.cshtml pages dynamically load Dashboard_pie, Dashboard_areachart, and dashboard_columnchart content.
Next, we want to define Dashboard_pie (pie chart), Dashboard_areachart (area map) and Dashboard_columnchart (bar chart) page, before defining the data graph interface, let's first introduce Google The use of charts.
Javascript
Before we mentioned the use of Google charts is very convenient, first we need to refer to the Jsapi library, in the page code to add the following code:
<!--Adds Google JS API reference.-->
<script type= "Text/javascript" src= "Https://www.google.com/jsapi" ></script>
Google's Jsapi, not only can load Google's own Ajax APIs (such as Google Map API, Google Search API and Google Earth API), it can also load a variety of commonly used JS library (such as: JQuery, JQuery UI, Prototype, MooTools, and dojo, etc.).
Now, we add the following JavaScript code to the page, referencing Google's visualization library:
<script type= "Text/javascript" >
google.load ("Visualization", "1", {packages: ["Corechart"]});
Google.setonloadcallback (Drawpiechart);
</script>
Above, we loaded the visualization library with the Google Load () method and defined the callback function as Drawpiechart () after the successful loading.
One might ask: "Why not just provide JavaScript libraries in Google CDN?" "There are two reasons why, first of all, we did not find a reference to the visualization library in the Google CDN (please tell), and secondly, the Google Load () method loads a series of related resources (such as JavaScript and CSS). So we don't have to quote them.
Earlier, we defined the callback function Drawpiechart (), but we have not implemented the method, and then we need to implement the callback function Drawpiechart (), which is responsible for drawing the data graph, which is implemented as follows:
/**
* Draws the pie chart.
**/
function Drawpiechart () {
//Gets data from Getlanguagerank ().
$.ajax ({
type: ' Get ',
dataType: ' json ',
URL: ' <%= url.content ("")%> ',
data: {},
success: function (data) {
var dt = new google.visualization.DataTable ();
Dt.addcolumn (' string ', ' Language ');
Dt.addcolumn (' number ', ' question ');
Adds data.
for (var i = 0; i < data.length i++) {
dt.addrow ([Data[i]. Name, Data[i]. Question]);
}
var options = {
title: "Top Programming language"
};
Draws pie implemention.
var chart = new Google.visualization.PieChart (document.getElementById (' Piechart '));
Chart.draw (dt, options);
},
error:function (XHR, Textstatus, e) {
console.log (' Status: ' + textstatus + ') Error: ' + e.tostring ());
},
complete:function () {
}}
);
Above, we implement the callback function Drawpiechart (), which obtains data from the backend by calling the $.ajax () method, and passes the data to the draw () method to draw the data graph if the data is successful.
Next, we implement the Dashboard_pie data graph interface, the specific code is as follows:
<!--Pie Chart page-->
<! DOCTYPE html>
Above, we added a DIV element to the form element, and since we specified the loading position of the pie chart in the callback function Drawpiechart (), we need to add the div element of the pie chart to the page.
Earlier, we mentioned the callback function Drawpiechart (), the $.ajax () method to get the data from the backend, now we need to provide an API method for the client to get the corresponding data through the calling API.
Here, we use StackOverflow jan/01/2010 to july/01/2013 's hot tag data.
Because the data is in CSV format, we can use Excel to view the data.
Figure 3 Popular Tag data
By using the data in the diagram above, we define the language class, which contains four fields, ID, Name, question, and Createon, which are defined as follows:
Figure 4 Language class
<summary>
///The language model.
</summary> public
class Questiontag
{public
int Id {get; set;}
public string Name {get; set;}
public int question {get; set;}
Public DateTime Createon {get; set;}
}
Above, we define the Questiontag class, and then we need to define the controller class, which is responsible for returning the backend data, so we create the Dashboardcontroller class in the controllers file, and we add the Getlanguagerank ( ) method, specifically implemented as follows:
Figure 5 Dashboardcontroller Class
<summary>
///Gets language rank data.
</summary>
///<returns>json arrary.</returns> public
jsonresult Getlanguagerank ()
{
//Gets data from database.
}
Import data
Above, we define the Dashboardcontroller class, which contains the Getlanguagerank () method, and then we save the CSV data to the database. First, we create the data table in the database, the specific SQL code is as follows:
--=============================================
--description:table for storing question tag data-
-======= ======================================
SET ANSI_NULLS on
go
set QUOTED_IDENTIFIER in
go
set Ansi_padding on
go
CREATE TABLE [dbo].[ Questiontags] (
[Name] [varchar] COLLATE chinese_prc_ci_as NOT NULL,
[question] [int] is not NULL,
[ Createon] [datetime] not NULL in
[PRIMARY] Go
SET ansi_padding off
We then import the CSV data into SQL Server, which is implemented as follows:
--=============================================-
description:imports CSV data into database.
--=============================================
BULK INSERT questiontags from
' C:\Users\Administrator\ Desktop\stackoverflow Tags data.csv '
with (
firstrow = 2, --Start row excludes header.
FieldTerminator = ', ',--csv field delimiter
rowterminator = ' \ n ',--use to shift's control to next row
Errorf ILE = ' C:\Users\Administrator\Desktop\ErrorLog.csv ',?
TABLOCK
)
Above, we directly use the SQL statement to import the CSV data into the database, where we defined the import data source file and data format, and defined the Errorlog file record import failed data, and finally, we add a questiontags ID primary key in the table.
Figure 6 Importing CSV data
Asp. NET Controller
Now that we've stored the data in the database, we'll use EF to get the data from the database, and there are 3 different programming models that are exposed to EF that should know the EF:
- Database first: Databases in advance
- Model first: Models in advance
- Code First: Coding first
Since we have already defined the data table, we will use the database first model to access the database.
Next, let's Implement the Getlanguagerank () method, with the following specific code:
<summary>
///Gets language rank data.
</summary>
///<param name= "index" >specifies the range of data,
///for instance, where is 0, Then get the data range from jan/1/2010 till feb/2/2010.
</param>
///<returns>json array</returns> public
jsonresult getlanguagerank (int index = 0)
{
using (var db = new Dashboarddbcontext ())
{
var result = (from tags in db.) Questiontags by
tags. Createon Ascending
Select new {tags. Id, tags. Name, tags. Question, tags. Createon}). Skip ((index% 42) * 25). Take (25). ToList ();
return Json (result, jsonrequestbehavior.allowget);
}
}
We implemented the Getlanguagerank () method, which obtains data at a specified time based on the index value and then returns it to the client via the JSON data format.
Now that we've implemented the pie chart (dashboard_pie), let's run the index.cshtml page to see how it works!
Fig. 7 Pie chart
We notice that figure 1 is a dynamic diagram that visually shows the trend of stackoverflow popular tags, and if we're going to implement a dynamic data graph, how do we do that?
In fact, the problem is converted to real-time access to data, and then generate a data map is OK, if you want to achieve real-time acquisition time, we think of the methods are:
- 1.Timer ()
- 2. Method two database real-time method data (SqlDependency)
- 3.Other (Please share the good method)
Next, we'll use the timer () function in JavaScript to periodically access the Getlanguagerank () method, so we need to modify the JavaScript code and call the Drawcolumnchart () method periodically through the timer () function. Specifically implemented as follows:
<script type= "Text/javascript" > Google.load ("Visualization", "1", {packages: ["Corechart"]});
Google.setonloadcallback (Timerstart);
var cnt = 0, t;
function Timerstart () {t = Window.setinterval (Drawcolumnchart, 1000);
function Timerstop () {cleartimeout (t); function Drawcolumnchart () {$.ajax ({type: ' Get ', DataType: ' json ', url: ' <%= url.content ("~/dashboard /getlanguagerank ")%> ', data: {index:cnt}, success:function (data) {var dt = new Google.visualization.Dat
ATable ();
Dt.addcolumn (' string ', ' Language ');
Dt.addcolumn (' number ', ' question '); for (var i = 0; i < data.length i++) {Dt.addrow ([data[i]. Name, Data[i].
Question]); var dateTime = new Date (parseint (data[0).
CREATEON.SUBSTR (6))); var options = {title: "Top programming language on" + (Datetime.getmonth () + 1) + '/' + datetime.getdate ()
+ '/' + datetime.getfullyear (),//width:600, height:500}; Var Chart = new Google.visualization.ColumnChart (document.getElementById (' Columnchart '));
Chart.draw (dt, options);
}, Error:function (XHR, Textstatus, E) {timerstop ();
Console.log (' Status: ' + textstatus + ' Error: ' + e.tostring ());
}, Complete:function () {cnt = cnt + 1;
}
});
} </script>
When Google's visualization library is loaded, access the callback function Timerstart (), and then use the SetInterval () method to call drawcolumnchart every 1s () to draw a new histogram.
Fig. 8 Column Chart
We now use the timer () function to access the API interface in real time, and the data is displayed dynamically through a histogram.
Page style
Now that we've finished with the pie chart and the histogram, we need to add some simple CSS effects to the meter program, which is as follows:
/*dashboard APP css*/
. PageHeader
{
height:20px;
Background-color: #2C2C2C;
padding:10px 10px;
margin-bottom:10px;
Color:white;
Position:relative
}
. PageHeader H1
{
font:normal 1.2em Arial;
Color:white;
margin:0;
padding:0
}
. PageHeader. platformular
{
position:absolute;
top:10px;
right:10px
}
. Pagebody
{
margin:0 10px;
}
. PageFooter
{
clear:both;
padding-top:10px;
width:100%;
Text-align:center;
Font-size:0.8em;
Color: #686868;
margin:25px 0 0 0;
Border-top:solid 1px #e7e7e7;
}
Now we rerun the program to see the page effect.
Fig. 10 Instrument Program
In this article, we implemented a simple instrumentation program using the asp.net MVC and EF database one, using the Google Charts control to display the data graph, which is just a simple program, and we have a lot of room for improvement, Providing a rich and powerful program is the goal of every programmer.
The above is the entire content of this article, I hope to help you learn.