Implementation of Real-time charts in ASP. NET

Source: Internet
Author: User
When analyzing and comparing large volumes of data, the most common and intuitive way to show is to draw a trend chart. In general, we use EXCEL to create various types of trend charts, but they are all based on static data, that is, the data is prepared in advance rather than dynamically generated. If you publish a chart online, you can only publish it using a static GIF image. This does not fundamentally meet the needs of different users for different data.

ASP is good at Web programming on the server side, and operations on backend databases are even more powerful. However, it is difficult to use ASP to create real-time database charts, because ASP itself does not support chart functions and can only be developed with third-party controls, such as the Visual Studio Control of VB. The. NET Framework launched by Microsoft better solves this problem. On the. NET platform, Microsoft integrated the real-time database chart production component-OWC (Microsoft Office Web Components ). By calling OWC on the ASP. NET page, we can easily draw various types of real-time charts. OWC supports nearly 50 chart types, including graphs, line charts, bar charts, area charts, and K-line charts. Compared with MSChart, OWC is powerful and easy to operate. In addition, because OWC is based on the server, and MSChart can only be applied to the client, MSChart is inferior to OWC in Web development on the server.

Below I will introduce the OWC in ASP with examples. NET page. This example is a sub-system in the project "chemical fiber products and raw material market analysis system" developed by the author. In this project, the author uses OWC, the powerful functions of OWC bring convenience to the development work.

Layer-3 Structure

The overall system architecture adopts the B/S three-tier structure, which divides the system into the user interface layer (also called the presentation layer) and the business logic layer (also called the function layer) and the database service layer (also known as the data layer), the Development Platform uses.. NET Framework effectively reduces the requirements of the system on the client and avoids the difficulty of distributing applications and version control on the client.

● User interface layer: the user interface adopts ASP. NET technology. The Application of ASP. NET technology enhances the versatility of the system. The client only needs to install any browser such as IE or Netscape without loading any components.

● Business logic layer: uses the. NET Framework to call OWC, which can quickly obtain data in the database to dynamically generate charts based on user requirements. The system supports complex search conditions, fast retrieval, and short response time.

● Database service layer: the database service layer can use any relational database. In this project, I use SQL Server, which can be seamlessly integrated with. NET Framework. The database access technology uses ADO. NET.

The following describes how to implement the business logic layer.

Introduction to chart Elements

A complete chart is composed of several elements. We must have some understanding of it before we can fully and freely control the chart and better understand the program. The author makes a simple chart and marks the main parts involved in the program and the names of elements in the chart, to help readers understand OWC and the code referenced in this article.

 

Use OWC Components

The source code involved in this section is taken from the analysis system of chemical fiber products and raw material market. The system is available in Windows 2000/XP Simplified Chinese Professional Edition ,. NET Framewrok 1. 0. To use the OWC component, follow these steps:

1. Create a new sub-directory chart for storing chart files in the current directory, and grant the "modify" permission to the directory to the ASP. NET account. The procedure is as follows: Right-click the chart directory name, select the "attribute" menu item, and click the "Security" tab in the "Chart" attribute dialog box that appears, click Add to find ASP.. NET account, Grant "modify" permission, and click "OK. In this way, ASP. NET can write chart files in the chart directory.

2. Define a server-side Image control. The Image property imageURL will be directed to the dynamically generated chart file at the end of the program. Therefore, you do not need to assign a value here.

<Asp: image id = "imgChart" Width = "500" Height = "300" Visible = "False" Runat = "server"> </asp: image>

3. Add OWC reference.

Before using OWC, you must add the reference of OWC to Solution Explorer. The procedure is as follows: Open the Solution Explorer panel, right-click "Reference", and select the "add reference" menu, in the displayed "add reference" dialog box, click the "COM" card, find "Microsoft Office Web Components 9.0", and click "select" and "OK, the OWC is added to the reference.

4. Define the OWC space and add an OWC chart owcChart to the space.

Dim owcChartSpace As OWC. ChartSpace = New OWC. ChartSpace ()

Dim owcChart As OWC. WCChart = owcChartSpace. Charts. Add

5. Use SQL search conditions for database search, and assign the search results to owcChart in the form of a RecordSet dataset.

OWC only supports RecordSet datasets and does not support DataSet datasets. Therefore, objects such as sqlCommand and sqlDataAdapter cannot be used for retrieval, but only RecordSet objects can be used for retrieval.

'Open the connection.

ConnADO. Open (connectionString)

RecordsetADO. ActiveConnection = ConnADO

'Set the cursor to a static cursor

RecordsetADO. CursorType = ADODB. CursorTypeEnum. adOpenStatic

RecordsetADO. CursorLocation = ADODB. CursorLocationEnum. adUseClient

'Variable strSQL stores the standard SQL search conditions

RecordsetADO. Open (strSQL)

Then, assign the RecordSet dataset to the OWC object:

OwcChartSpace. DataSource = RecordsetADO

In this example, we assume that the data retrieved using SQL statements has three fields: product, date, and price. The values of these three fields correspond to the data in the curve, category (X) axis, and value (Y) axis in the chart.

6. Determine the curve type and field names for different curves.

First, determine the curve type as smooth curve.

OwcChart. Type = OWC. ChartChartTypeEnum. chChartTypeSmoothLine

OWC supports displaying more than two curves in the same chart. Therefore, we must provide the basis for distinguishing different curves, which is the value of the "product" field. Specifically, there are several different values in the "product" field, and several different curves are generated.

OwcChart. SetData (OWC. ChartDimensionsEnum. chDimSeriesNames, 0, "product ")

7. Confirm the fields corresponding to the category (X) axis label and the value (Y) axis label.

First, define the owcSeries as the OWC curve set, traverse each curve in the chart, and assign the value of the "date" field to the category (X) axis as the X axis scale label, assign the value of the "price" field to the value (Y) axis as the Y axis scale label. If we can determine that there is only one curve in the chart, we can also omit the traversal process, but this will undoubtedly reduce the versatility of the program.

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 attributes of the coordinate axis.

This part of code beautifies the chart by setting text content, color, size, primary and secondary dial lines and their labels, primary and secondary network lines, and other aspects of the Axis title. If the concepts in this section of code are vague, you can refer to the chart provided in the previous section. For more information, see the following code.

'Define axis as the Coordinate axis set first.

Dim axis As OWC. WCAxis

'Traverse the Coordinate Axis set

For Each axis In owcChart. Axes

'Show the axis title

Axis. HasTitle = True

'Set the category (X) axis first.

If axis. Type = OWC. ChartAxisTypeEnum.

ChCategoryAxis Then

Axis. HasTickLabels = True

'Display the X axis scale label

Axis. Position = OWC. ChartAxisPositionEnum. chAxisPositionBottom

'Display position of the tag

Axis. Title. Font. Color = "blue"

'X-axis title text color

Axis. Title. Font. Size = "9"

'X-axis title text size

Axis. Title. Caption = "Date range"

'X-axis title text content

Else

'Set the value (Y) axis

Axis. MajorGridlines. Line. Color = "silver"

'Y Axis Main Network line color

Axis. MajorTickMarks = OWC. ChartTickMarkEnum. chTickMarkNone

'The Y axis primary scale flag is not displayed

Axis. HasTickLabels = True

'Show Y axis scale labels

Axis. Title. Font. Color = "blue"

'Y-axis title text color

Axis. Title. Font. Size = "9"

'Y-axis title text size

Axis. Title. Caption = "price (thousand RMB/ton )"

'Y-axis title text content

End If

Next

9. output the chart in GIF format and assign the Image file name to the Image control.

'Use random numbers to generate random file names

Randomize ()

Dim nFileNameSuffix As Integer

Dim sFileNameSuffix As String

NFileNameSuffix = 100000 * Rnd ()

SFileNameSuffix = System. Convert. ToString (nFileNameSuffix)

'Output the chart in GIF format. The chart size is 500*300. The name of the chart is polyesterprice_random number .gif, which is stored in the chart subdirectory.

OwcChartSpace. ExportPicture (MapPath ("chart/PolyesterPrice _") + sFileNameSuffix + pai.gif "," gif ", 500,300)

'Point the Image control URL to the chart file.

ImgChart. ImageUrl = "chart/PolyesterPrice _" + sFileNameSuffix + pai.gif"

Through the preceding nine steps, a real-time database chart is generated and displayed. It should be noted that the preceding nine steps are only an essential basic process for generating a chart, by setting other OWC attributes, you can better and more accurately control the chart generation and display methods, such as the width and color of the line, the axis curve, the label display frequency, and the network line. I will not introduce this part. Please refer to the source code in the fourth part of this article.

For the chart results generated by the code in this article, see.

Optimization

All the preceding chart files generated in real time are stored in the chart folder. Because Random file names are used, these files are not overwritten. However, over time, more and more files not only occupy empty hard disk space, but also impede management and reduce performance. Can we automatically delete previous Chart files in the program? The answer is yes. We only need to place the following code in the Page_Load () function of the code file. When the program runs, the files earlier than the current day will be automatically deleted. In this way, the chart files generated on the current day are stored in the chart folder, effectively avoiding file spam.

'Retrieve the file list in the chart folder first.

Dim fileEntries () As String = System. IO. Directory. GetFiles (MapPath ("chart "))

Dim sFile As String

'Traverse the file list

For Each sFile In fileEntries

'Compare the file generation date with the system date. If the file is generated before the current 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 charts generated using OWC have complete functions and beautiful interfaces, they also have many defects. First, OWC does not support DataSet datasets, so that we cannot use the DataGrid to display data tables while generating charts, unless we use the loop to retrieve all the data in the Recordset record set to manually generate tables, or use the same search conditions to perform secondary searches on the database, but this will undoubtedly increase the burden on the server. Second, the curves drawn in the same chart can only be of the same type, the same as a smooth graph, or the same column graph. Different types of curves cannot be displayed in the same chart. Finally, in some details, such as the setting of the category (X) axis, OWC cannot provide more detailed and user-friendly settings. If you want to pursue more powerful functions and better display effects, I recommend two professional services based on. NET chart controls, both of which are produced by Dundas and Softwarefx companies, both support Web Form and Win Form development at the same time, but both are paid. If you are interested, you can download the DEMO version on their website to experience the powerful functions of 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.