ASP. net mvc implements the instrumentation program, asp. netmvc implements the instrumentation
In most cases, our Web programs not only need to provide users with specific data, but in some cases, we also need to provide advanced users or managers with functions such as data aggregation and analysis charts.
If we don't want to display a lot of annoying data and want to display the data intuitively through a pie chart or bar chart, we can consider using chart controls.
In the following article, we will introduce the implementation of the data dashboard program.
There was an article about StackOverflow's programming trends. It showed us hot question tags on Stackoverflow through bars and area diagrams.
Figure 1 Stackoverflow hot labels
Through this, We can intuitively understand the trend of hot labels on Stackoverflow, And now we implement the same function through the instrumentation program.
On the meter program interface, we will display data through the pie chart, area chart, and bar chart. Here we use the Google Charts Control to display the pie chart, area chart, and bar chart data graph.
Google Charts uses Javascript to draw dynamic images. It is easy to use. We only need to pass the corresponding data to the corresponding drawing function to generate corresponding data Charts.
Uidesign
Figure 2 Dashboard
Now, we want to display the data pie chart, region chart, and bar chart on the main Dashboard. Then we use the Google Charts Control to dynamically load the three images to the Index. in the cshtml page, the following is 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 -->
The preceding three div elements are defined. The Index. cshtml page dynamically loads the content of Dashboard_Pie, Dashboard_AreaChart, and Dashboard_ColumnChart.
Next, we will define the Dashboard_Pie (pie chart), Dashboard_AreaChart (region chart), and Dashboard_ColumnChart (Bar Chart) pages. Before defining the Data graph interface, let's first introduce the use of Google Charts.
Javascript
As mentioned above, Google Charts is very easy to use. First, we need to reference the jsapi library and add the following code to the page code:
<!-- Adds Google js api reference.--><script type="text/javascript" src="https://www.google.com/jsapi"></script>
Google's JSAPI can load not only AJAX APIs provided by Google (such as Google Map API, Google Search API, and Google Earth API ), it can also load a variety of common JS libraries (such as jQuery, jQuery UI, Prototype, MooTools, and Dojo ).
Now, we add the following Javascript code to reference Google's visualization Library:
<script type="text/javascript"> google.load("visualization", "1", { packages: ["corechart"] }); google.setOnLoadCallback(drawPieChart);</script>
Above, we used google's load () method to load the visualization library, and defined the callback function after successful loading as drawPieChart ().
Someone may ask, "Why not use the Javascript library provided by Google CDN directly ?" There are two reasons: First, we did not find the reference address related to the visualization library in Google CDN (if any, please let us know). Second, google's load () the method loads a series of related resources (such as Javascript and CSS), so that we do not need to reference them one by one.
Previously, we defined the callback function drawPieChart (), but we have not implemented this method. Next, we need to implement the callback function drawPieChart (), which is responsible for drawing data graphs. The specific implementation is 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 25 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 implemented the callback function drawPieChart (), which calls $. the ajax () method obtains data from the backend. If the data is obtained successfully, it is passed to the draw () method to draw a data chart.
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, because we specified the position for loading the pie chart in the callback function drawPieChart, therefore, we need to add the div element of the pie chart to the page.
As mentioned above, the callback function drawPieChart () is passed through $. the ajax () method obtains data from the backend. Now, we need to provide an API method for the client to obtain the corresponding data by calling the API.
Here, we use Stackoverflow Jan/01/2010 to July/01/2013 hot tag data.
Because the data is in CSV format, we can use Excel to view the data.
Figure 3 popular tag data
Through the data, we define the Language class, which contains four fields: Id, Name, Question, and CreateOn. The specific definitions are as follows:
Figure 4 Language
/// <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; }}
The above defines the QuestionTag class. Next, we need to define the Controller class, which is responsible for returning back-end data. Therefore, we create the DashboardController class in the Controllers file and add the getjavasagerank () method, the specific implementation is 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
The above defines the DashboardController class, which contains the get‑agerank () method. Next we save the CSV data to the database. First, create a data table in the database. The specific SQL code is as follows:
-- =============================================-- Description: Table for storing question tag data-- =============================================SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[QuestionTags]( [Name] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL, [Question] [int] NOT NULL, [CreateOn] [datetime] NOT NULL) ON [PRIMARY]GOSET ANSI_PADDING OFF
Next, we import CSV data to SQL Server. The specific implementation is as follows:
-- =============================================-- Description: Imports csv data into database.-- =============================================BULK INSERT QuestionTagsFROM 'C:\Users\Administrator\Desktop\Stackoverflow Tags Data.csv'WITH( FIRSTROW = 2, -- Start row excludes header. FIELDTERMINATOR = ',', --CSV field delimiter ROWTERMINATOR = '\n', --Use to shift the control to next row ERRORFILE = 'C:\Users\Administrator\Desktop\ErrorLog.csv',? TABLOCK)
Above, we directly use SQL statements to import CSV data into the database, where we define the source file and data format of the imported data, and define the data that fails to import the ErrorLog file records, finally, we add the auto-incrementing Id Primary Key to the table QuestionTags.
Figure 6 Import CSV data
ASP. NET Controller
Now we have stored the data in the database. Next we will use EF to obtain the data in the database. If we have been in contact with EF, we should know that there are three programming models for EF:
- Database First: Database First
- Model First: Model First
- Code First: Code First
As we have defined the data table above, we will use the Database First model to access the Database.
Next, let's implement the getreceivagerank () method. The specific code is as follows:
/// <summary>/// Gets language rank data./// </summary>/// <param name="index">Specifies the range of data,/// for instance, when index 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 orderby 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); } }
The getreceivagerank () method is implemented. It obtains data of the specified time based on the index value and returns the data to the client in JSON format.
Now we have implemented the pie chart (Dashboard_Pie). Next, let's run the Index. cshtml page to view the running effect!
Figure 7 pie chart
We noticed that figure 1 is a dynamic chart that intuitively shows the trend of Stackoverflow hot labels. How can we achieve dynamic data Graph Generation?
In fact, the problem is converted to real-time data acquisition, and it is OK to generate a Data graph. To achieve real-time data acquisition, we can think of the following methods:
- 1. Timer ()
- 2. method 2 real-time database method data (SqlDependency)
- 3. Other (Please share your ideas)
Next, we will use the Timer () function in Javascript to regularly access the getjavasagerank () method. Therefore, we need to modify the Javascript code and call the drawColumnChart () method regularly through the Timer () function, the specific implementation is 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.DataTable(); 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 25 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>
After Google's visualization library is loaded, access the timerStart () callback function and call drawColumnChart () every 1 s to create a new column chart using the setInterval () method.
Figure 8 bar chart
Now, we use the real-time access API interface of the Timer () function, and the data is dynamically displayed through the bar chart.
Page Style
Now we have completed the pie chart and bar chart. Next, we need to add some simple CSS effects to the Instrument Program. The specific code 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, run the program again to view the page effect.
Figure 10 Instrumentation
In this article, we use ASP. net mvc and EF Database First implement a simple instrumentation program and use the Google Charts Control to display data graphs. This is just a simple program, and we still have a lot of room for improvement, it is the goal of every programmer to provide a program with rich content and powerful functions.
The above is all the content of this article, hoping to help you learn.
Articles you may be interested in:
- Asp.net "server application unavailable" SOLUTION
- Cause and solution of Runtime Error in Asp. Net Program
- Implementation Code of JSON returned by ASP. NET or WebService
- Export data from. Net to Excel (in asp.net and winform programs)
- Introduction to using session in general processing programs in ASP. NET
- Simple Chat Room program written by ASP. NET using application and session Object
- Security of ASP. net mvc applications