Asp. NET real-time Chart Realization method Sharing _ Practical skills

Source: Internet
Author: User

In the analysis and comparison of large quantities of data, the most commonly used and most intuitive method of performance is to draw trend charts. In general, we use Excel to produce various types of trend charts, but they are all based on static data, that is, the data is sorted in advance rather than dynamically generated. If you publish on the Web, you can only publish your chart in a static GIF image, which does not fundamentally meet the needs of different users for different data.
ASP is good at server-side web programming, the operation of the background database is its strength. However, it is difficult to make real-time database diagram with ASP, because the ASP itself does not support the graph function, only uses the third party control to develop, like VB's MSChart control. The. NET framework introduced by Microsoft is a good solution to this problem. Microsoft in. NET platform integrates the real-time Database Diagram production component-OWC (Microsoft Office Web components). By calling OWC in the ASP.net page, we can easily draw various types of real-time charts. OWC supports nearly 50 types of charts, including graphs, line charts, column charts, area charts, chart, and so on. Compared with MSChart, OWC is powerful and easy to operate. In addition, because OWC is server-based and MSChart can only be applied to clients, MSChart is less than OWC in server-side web development.

The following author will be combined with examples to illustrate the application of OWC in asp.net page, this example is the project of the author developed a subsystem of the market analysis system of chemical fiber products and their raw materials, the author used the OWC in this project, fully enjoyed the powerful function of OWC to bring convenience to the development work.

Three-layer structure

The whole system architecture adopts B/s three-layer structure mode, the system is divided into user interface layer (also known as performance layer), Business logic layer (also called functional layer) and database service layer (also known as data layer), the development platform adopts the. NET Framework, which effectively reduces the requirements of the system to clients. Avoids the difficulty of distributing applications and versioning on the client.

User interface layer: The user interface is based on asp.net technology. Asp. NET technology to enhance the system's versatility, the client only need to install IE or Netscape, such as any browser, without loading any components.

Business Logic Layer: Using the technology of the. NET Framework call OWC, we can quickly obtain the data dynamic generating chart of the database according to the user's requirement. The system can support complex retrieval conditions, fast retrieval speed and short response time.

Database service layer: The database service layer can use any of the relational databases. In this project, the author uses SQL Server, which integrates seamlessly with the. NET Framework. Ado.net is used in database access technology.

We will highlight the implementation of the business logic layer below.

Introduction to chart elements

A complete chart consists of a number of elements, and we have to understand them so that we can have a full control of the chart at our whim and in order to better understand the program. The author has made a simple diagram, in which the main parts of the program and the name of the element are annotated, which helps the reader to master OWC and understand the code referenced in this article.

Using the OWC component

The source code involved in this section is from the market analysis system for chemical fiber products and their raw materials, which is passed in Windows 2000/xp Simplified Chinese Professional Edition,. NET Framewrok 1.0 environment. The steps for using the OWC component are as follows:

1. Create a new subdirectory chart in the current directory that holds the chart file, and assign the "modify" permission to the directory to the ASP.net account. The specific steps are as follows: Right-click the Chart directory name, select the Properties menu item, click the Security tab in the pop-up Chart Properties dialog box, click the Add button, locate the ASP.net account, give the Modify permission, and click OK to end. In this way, ASP. NET, you can write a chart file in the chart directory.

2. Defines a server-side image control whose properties ImageUrl will be directed to the dynamically generated chart file at the end of the program, so there is no need to assign a value to it here.

Copy Code code as follows:

< Asp:image id= "Imgchart" width= "" height= "" "Visible=" False "runat=" Server "></asp:image>

3. Add OWC references.

Before you use OWC, you must first add a OWC reference to Solution Explorer. The steps are as follows: Open the Solution Explorer panel, right-click References, select the Add Reference menu, click the COM card in the Pop-up Add Reference dialog box, locate Microsoft Office Web Components 9.0, click Select and OK buttons, OWC is added to the reference.

4. Define the OWC space and add a OWC chart Owcchart to the space.

Copy Code code as follows:

Dim Owcchartspace as OWC. ChartSpace = New OWC. ChartSpace ()

Dim Owcchart as OWC. WCChart = OwcChartSpace.Charts.Add

5. Use SQL retrieval criteria for database retrieval, and assign the results to Owcchart in the form of a recordset dataset.

OWC supports only recordset datasets and does not support dataset datasets, so objects such as SqlCommand, SqlDataAdapter, and so on, can only be retrieved using a Recordset object.

Copy Code code as follows:

' Open Connection Connection

Connado.open (connectionString)

Recordsetado.activeconnection = Connado

' Set cursor to static cursor

Recordsetado.cursortype = ADODB. CursorTypeEnum.adOpenStatic

Recordsetado.cursorlocation = ADODB. Cursorlocationenum.aduseclient

' Variable strSQL a standard SQL retrieval condition is stored in the

Recordsetado.open (strSQL)

The recordset data set is then assigned to the OWC object:

Copy Code code as follows:

Owcchartspace.datasource = Recordsetado

In this case, we assume that the data retrieved with the SQL statement has three fields: product, date, and price. The values of these three fields correspond to the curves in the chart, the category (X) axis, and the value (Y) axis data one by one respectively.

6. Determine the type of curve and determine the name of the field that distinguishes the different curves.

First you determine that the curve type is a smooth curve.

Copy Code code as follows:

Owcchart.type = OWC. Chartcharttypeenum.chcharttypesmoothline

OWC supports showing more than two curves in the same chart. So we have to give the basis for distinguishing the different curves, which is the value of the Product field. Specifically, there are several different values in the Product field that generate several different curves.

Copy Code code as follows:

Owcchart.setdata (OWC. Chartdimensionsenum.chdimseriesnames, 0, "product")

7. Determine the field that corresponds to the category (X) axis label and the value (Y) axis label.

You first need to define a set of curves that are owcseries as OWC, and then walk through each curve in the chart, assigning the value of the Date field to the category (x) axis as the x-axis tick mark, and assigning the value of the Price field to the values (y) axis as the y-axis tick label. If we can determine that there is only one curve in the chart, we can omit the traversal process, but this will certainly reduce the generality of the program.

Copy Code code as follows:

Dim owcseries as OWC. WCSeries

For each owcseries in Owcchart.seriescollection

Owcseries.setdata (OWC. Chartdimensionsenum.chdimcategories, 0, "date")

Owcseries.setdata (OWC. Chartdimensionsenum.chdimvalues, 0, "price")

Next

8. Set the properties of the axis.

This section of code landscaping the chart by setting the text content, color, size, major and minor tick marks, and their labels, primary and secondary network lines for the axis titles. If the reader is somewhat vague about the concept in this code, you can refer to the chart provided in the previous section. For specific settings, see the following code.

Copy Code code as follows:

' first define axis as an axis collection

Dim axis as OWC. WCAxis

' Traverse the Axis collection

For each axis in owcchart.axes

' Show axis title

Axis. HasTitle = True

' Set the category (X) axis first

If axis. TYPE=OWC. ChartAxisTypeEnum.

Chcategoryaxis Then

Axis. Hasticklabels = True

' Show x-axis tick labels

Axis. Position = OWC. Chartaxispositionenum.chaxispositionbottom

' Where the label is displayed

Axis. Title.Font.Color = "Blue"

' x axis Title text color

Axis. Title.Font.Size = "9"

' x axis caption text size

Axis. Title.caption = "date range"

' X-Axis caption text content

Else

' Set the value (Y) axis

Axis. MajorGridlines.Line.Color = "Silver"

The color of the main network line of the Y axis

Axis. MajorTickMarks = OWC. Charttickmarkenum.chtickmarknone

' Do not show y-axis major tick marks

Axis. Hasticklabels = True

' Show y-axis tick labels

Axis. Title.Font.Color = "Blue"

' Y-axis title text color

Axis. Title.Font.Size = "9"

' Y axis caption text size

Axis. title.caption= "Price (thousand Yuan/ton)"

' Y-Axis caption text content

End If

Next

9. Prints the chart in GIF format and assigns the image file name to the images control.

Copy Code code as follows:

' Generate random file names with random numbers

Randomize ()

Dim Nfilenamesuffix as Integer

Dim Sfilenamesuffix as String

Nfilenamesuffix = 100000 * RND ()

Sfilenamesuffix = System.Convert.ToString (Nfilenamesuffix)

' Output chart in GIF format, size 500*300, chart file name: Polyesterprice_ random number. gif, stored in chart subdirectory

Owcchartspace.exportpicture (MapPath ("Chart/polyesterprice_") + Sfilenamesuffix + ". gif", "GIF", 500, 300)

' Point the URL of the image control to the chart file

Imgchart.imageurl= "Chart/polyesterprice_" + Sfilenamesuffix + ". gif"

Through the above nine steps, we have completed a real-time database diagram generation and display. The point to be noted here is that the nine steps above are just a basic process for generating a chart, and you can better and more accurately control how the chart is generated and displayed by setting OWC other properties, such as the legend, the thickness and color of the line, the display frequency of the axis tick marks and labels, the network line, and so on. This part of the author is no longer introduced, see the source code in part IV of this article.

The chart effect generated by this code is shown in the following figure.

Optimization

All of the chart files that are generated in real time above are stored in the chart folder and are not overwritten by random file names. However, more and more files not only occupy the hard disk space, but also hinder the management and reduce the performance. Can we automatically delete the previous chart files in the program? The answer is yes. As long as we put the following code in the Page_Load () function of the code file, when the program runs, it automatically deletes the files from the previous day. In this way, the chart folder is always stored in the same day as the chart file, thereby effectively avoiding the file garbage.

Copy Code code as follows:

' First get the list of files in the chart folder

Dim fileentries () as String = System.IO.Directory.GetFiles (MapPath ("chart"))

Dim Sfile as String

' Traverse file list

For each sfile in Fileentries

' Compare the build date of the file with the system date, if it is a file that was generated before that day, delete it

If Datetime.compare (System.IO.File.GetCreationTime (sfile). AddDays (1), DateTime.Now) < 0 Then

System.IO.File.Delete (sfile)

End If

Next

Although the graphs produced with OWC are fully functional and aesthetically pleasing, there are many drawbacks. First, the dataset DataSet is not supported by OWC, so that we cannot use the DataGrid to display the datasheet while generating the chart, unless we manually generate the table by looping through all the data in the recordset Recordset, or retrieve the database two times with the same search criteria. But this will undoubtedly increase the burden on the server. Second, the curves drawn in the same chart can only be the same type, or the same smoothing graph, or the same histogram, it cannot display different types of curves in the same chart. Finally, in some detail, such as the classification (X) axis settings, OWC can not provide a more detailed, user-friendly way to set up. If the reader is to pursue a more powerful function and better display effect, I recommend two professional based on. NET, the two controls are produced by Dundas and Softwarefx, which support both Web form and win form development, but both are paid for. Readers who are interested can go to their website to download the demo version to experience the powerful features of the professional chart controls.

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.