ASP. net mvc implements the instrumentation Program

Source: Internet
Author: User

1.1.1 Summary

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.

When you visit my blog, you can see a tool on the left to count the number of visitors each day. This is a simple data meter program, we can intuitively know the number and time of the day.

In the following blog, we will introduce the implementation of the data dashboard program.

Directory
  • Uidesign
  • Javascript
  • Import Data
  • ASP. NET Controller
  • Page Style
1.1.2 text

A while ago, I had a blog post about the programming trend on StackOverflow. It showed us the hot question labels on Stackoverflow through bars and area diagrams.

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

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:

@{ Html.RenderAction("Dashboard_Pie", "DashBoard"); }    @{ Html.RenderAction("Dashboard_AreaChart", "DashBoard"); }    @{ Html.RenderAction("Dashboard_ColumnChart", "DashBoard"); }    

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:

 

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:

google.load(, , { packages: [] });    google.setOnLoadCallback(drawPieChart);

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:

drawPieChart() {    $.ajax({        type: ,        dataType: ,        url: ,        data: {},        success: (data) {            dt = google.visualization.DataTable();            dt.addColumn(, );            dt.addColumn(, );            (i = 0; i < data.length; i++) {                dt.addRow([data[i].Name, data[i].Question]);            }            options = {                title: };            chart = google.visualization.PieChart(document.getElementById());            chart.draw(dt, options);        },        error: (xhr, textStatus, e) {            console.log(+ textStatus + + e.toString());        },        complete: () {        }    });}

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:

 

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 (download from here ).

Because the data is in CSV format, we can use Excel to view the data.

Through the data, we define the Language class, which contains four fields: Id, Name, Question, and CreateOn. The specific definitions are as follows:

{    Id { ; ; }    Name { ; ; }    Question { ; ; }    CreateOn { ; ; }}

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:

 

JsonResult GetLanguageRank(){    }
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:

GOGOGO[dbo][QuestionTags][Name] [varchar]50Chinese_PRC_CI_AS [Question] [int] [CreateOn] [datetime] [PRIMARY]GO

Next, we import CSV data to SQL Server. The specific implementation is as follows:

QuestionTagsFIRSTROW 2FIELDTERMINATOR ROWTERMINATOR ERRORFILE ,?    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.

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:

JsonResult GetLanguageRank(index = 0){    (var db = DashboardDbContext())    {            var result = (from tags db.QuestionTags                         orderby tags.CreateOn ascending              select { tags.Id, tags.Name, tags.Question, tags.CreateOn }).Skip((index % 42) * 25).Take(25).ToList();            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!

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:

google.load(, , { packages: [] });    google.setOnLoadCallback(timerStart);    cnt = 0, t;    timerStart() {        t = window.setInterval(drawColumnChart, 1000);    }    timerStop() {        clearTimeout(t);    }    drawColumnChart() {        $.ajax({            type: ,            dataType: ,            url: ,            data: { index: cnt },            success: (data) {                dt = google.visualization.DataTable();                dt.addColumn(, );                dt.addColumn(, );                (i = 0; i < data.length; i++) {                    dt.addRow([data[i].Name, data[i].Question]);                }                dateTime = Date(parseInt(data[0].CreateOn.substr(6)));                options = {                title: +                     (dateTime.getMonth() + 1) + + dateTime.getDate() + + dateTime.getFullYear(),                    height: 500                };                chart = google.visualization.ColumnChart(document.getElementById());                chart.draw(dt, options);            },            error: (xhr, textStatus, e) {                timerStop();                console.log(+ textStatus + + e.toString());            },            complete: () {                cnt = cnt + 1;            }        });    }

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.

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:

{    : ;    : ;    : ;    : ;    : ;    : ;}    {        : ;        : ;        : ;        : ;    }    {        : ;        : ;        : ;    }{    : ;}{    : ;    : ;    : ;    : ;    : ;    : ;    : ;    : ;}

Now, run the program again to view the page effect.

1.1.3 Summary

In this blog, 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.

Reference
  • Http://blog.platformular.com/2012/04/12/create-a-dashboard-experience-in-asp-net-mvc/

 

Demo

Updated: 08/02/2013

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.