Serving image from ASP.NET MSChart to external applications via WebService

I have an existing ASP.NET application that uses Microsoft Charting control for .NET. I created a CCharting class that hold several methods related to getting data for the chart, applying chart appearance etc. Main method of that class is

Public Sub DrawChart(ByVal i_omsChart As Chart, ByVal i_iChartWidth As Integer, ByVal i_iChartHeight As Integer)

As a 1st parameter it accepts actual chart control from the page, 2nd and 3rd are chart width and height. The method then gets the data for the chart, binds chart to that data, applies chart appearance (colors, series, axises) etc. So drawing a chart is a simple as instantiating the class and calling the method:

Dim oCharting As New CCharting
CCharting.DrawChart(xmsChart,500,300)

where xmsChart is a chart control from HTML markup of the page. The result is displayed on the page:

But now I needed to give access to that chart to external applications, that do not have access neither to chart data nor to Microsoft charting control, may run under different OS’s, be Web apps or not. The solution I came up with is to serve chart image via Web Service.

Since CCharting class already had all the chart drawing functionality, I decided to reuse it. A WebService was created with GetChartImage method:

<WebMethod()> _
Public Function GetChartImage(ByVal i_iChartWidth As Integer, ByVal i_iChartHeight As Integer) As Byte()
   Dim oCharting As New CCharting
   Dim omsChart As New Chart
   Dim oStream As New IO.MemoryStream()  

   oCharting.DrawChart(omsChart, i_iChartWidth, i_iChartHeight)
   omsChart.SaveImage(oStream, ChartImageFormat.Png)

   Return oStream.ToArray

End Function

It’s very simple. The method accepts chart width and height as parameters and returns chart image in form of a byte array. Notice Line 4 – instead of hard-coded chart control from HTML markup a chart object is created programmaticaly. DrawChart method accept it and draws chart on it (Line 7). Then image is saved in PNG format into memory stream (Line 8). And finally the stream is converted to byte array to be returned as a result (Line 10).

An example of using this Web Service in an external application is a WinForm app. A very basic VB.NET winform app was created with a single PictureBox control (named xpicChart) on the form. A reference to WebService above was added (namespace named WebApi). After that loading image into PictureBox takes just 3 lines of code:

Dim oWebApi As New WebApi.CWebServiceSoapClient
Dim aImage As Byte() = oWebApi.GetChartImage(xpicChart.Width, xpicChart.Height)
xpicChart.Image = Image.FromStream(New IO.MemoryStream(aImage))

1st line creates a WebService client object, 2nd calls the method and retrieves image as a byte array and 3rd loads image into the picture box by converting the byte array into memory stream. The result:

Leave a Reply

Your email address will not be published. Required fields are marked *