Applies to: Nevron Chart for .NET
How to implement Chart AJAX Drill Down with Preview?
The following topic explains all of the needed steps to implement an AJAX interactive drill down with preview when the mouse is moved over a data point in Nevron Chart. This example demonstrates how a custom client side tool can be created that runs as a part the Nevron JavaScript Framework. The task is achieved by implementing the server side C# class NAjaxCustomTool and setting the AjaxToolsFactoryType property of the web control to the name of the custom JavaScript tool factory: "NCustomToolFactory", and by implementing the client side JavaScript classes:
- NCustomToolConfig
- NCustomTool
- NDisplayBookInfoCommand
- NHideBookInfoCommand
- NCustomToolFactory
The Pie Chart image that appears inside the floating DIV element is generated dynamically through the PieChart class, under the project PieChart.cs (PieChart.vb) code file. In this example, we are binding the Chart to Excel through OLEDB. Following is the sample data from the Excel spreadsheet:
Implementation:
1. In Visual Studio, create a new ASP.NET Web Application. Under the Web Application folder \App_Data, we have placed the Excel file that will be used.
2. We need to add a new code file to our project (PieChart.cs / PieChart.vb). This file will be responsible for the popup preview image. In this example, we have created PieChart.cs (PieChart.vb) in the project:
The Default.aspx page will contain the main Chart control, which will display a bar chart. When the user moves the mouse over one of the bars, the drill-down preview image for the Pie chart will appear.
3. Open the solution explorer and make sure to add references to the following Nevron assemblies: Nevron.Chart.dll; Nevron.Chart.WebForm.dll; Nevron.GraphicsGL.dll; Nevron.Presentation.dll; Nevron.System.dll; and Nevron.UI.WebForm.Controls.dll;
Select all Nevron references and set Copy Local property to True.
4. From the Solution explorer open the Web.config and make sure the following configuration exists in your web.config file:
<?
xml
version
=
"1.0"
?>
<
configuration
>
<
system.web
>
<
httpHandlers
>
<
add
verb
=
"*"
path
=
"NevronChart.axd"
type
=
"Nevron.Chart.WebForm.NChartImageResourceHandler"
validate
=
"false"
/>
<
add
verb
=
"*"
path
=
"NevronScriptManager.axd"
type
=
"Nevron.UI.WebForm.Controls.NevronScriptManager"
validate
=
"false"
/>
<
add
verb
=
"*"
path
=
"NevronCustomTools.axd"
type
=
"WebApplication.PieChart"
validate
=
"false"
/>
</
httpHandlers
>
</
system.web
>
<
system.webServer
>
<
handlers
>
<
add
name
=
"NevronChart"
preCondition
=
"integratedMode"
verb
=
"*"
path
=
"NevronChart.axd"
type
=
"Nevron.Chart.WebForm.NChartImageResourceHandler"
/>
<
add
name
=
"NevronScriptManager"
preCondition
=
"integratedMode"
verb
=
"*"
path
=
"NevronScriptManager.axd"
type
=
"Nevron.UI.WebForm.Controls.NevronScriptManager"
/>
<
add
name
=
"NevronCustomTools"
preCondition
=
"integratedMode"
verb
=
"*"
path
=
"NevronCustomTools.axd"
type
=
"WebApplication.PieChart"
/>
</
handlers
>
</
system.webServer
>
</
configuration
>
Please look at the web.config file, where the NevronCustomTools.axd HTTP handler must defined for this example to run properly.
<add name="NevronCustomTools" preCondition="integratedMode" verb="*" path="NevronCustomTools.axd" type="WebApplication.PieChart"/>
5. From the Solution explorer open the Default.aspx Source. Here you will add the JavaScript required for making the image appear and disappear based on the mouse movements. Make sure the following configuration exists:
<%@ Register assembly="Nevron.Chart.WebForm, Version=11.1.17.12, Culture=neutral, PublicKeyToken=346753153ef91008" namespace="Nevron.Chart.WebForm" tagprefix="ncwc" %>
<
head
id
=
"Head1"
runat
=
"server"
>
<
title
></
title
>
</
head
>
<
body
>
<
form
id
=
"form1"
runat
=
"server"
>
<!-- Custom JavaScript placeholder BEGIN -->
<
script
type
=
"text/javascript"
language
=
"javascript"
>
<!--
// This code definese the following JavaScript types:
// NCustomToolConfig
// NCustomTool
// NDisplayDetailedChartCommand
// NHideDetailedChartCommand
// NCustomToolFactory
////////////////////////////////
// class NCustomToolConfig
// A configuration object for the NCustomTool tool.
function NCustomToolConfig() {
// Runtime type info initialization
this.InitializeRuntimeTypeInfo(NCustomToolConfig.prototype);
this.NAjaxToolConfig(false);
};
// Inheritance
NCustomToolConfig.DeriveFrom(NAjaxToolConfig);
////////////////////////////////
// class NCustomTool
function NCustomTool(callbackService, toolConfig) {
// Runtime type info initialization
this.InitializeRuntimeTypeInfo(NCustomTool.prototype);
this.NAjaxTool(callbackService, toolConfig);
// Indicates, whether the tooltip is currently visible.
this.tooltipVisible = false;
// Contains a reference to the HTML div element that is used to display tooltips.
this.tooltipDiv = null;
// The image map object item, which tooltip is being currently displayed.
this.currentImageMapObjectItem = null;
// constructor body
if (NReflection.IsInstance(toolConfig.configurationObject))
this.config = toolConfig.configurationObject;
else
this.config = new NCustomToolConfig();
};
// Inheritance
NCustomTool.DeriveFrom(NAjaxTool);
// Displays the tooltip.
NCustomTool.prototype.ProcessMouseEnter = function (self, commandQueue, eventData) {
if (!NReflection.IsInstance(eventData.imageMapObjectItem))
return;
var imageMapItem = eventData.imageMapObjectItem;
if (imageMapItem.userData == null)
return;
if (self.tooltipVisible)
return;
self.tooltipVisible = true;
self.currentImageMapObjectItem = self.callbackService.currentOverElement;
commandQueue.Enqueue(new NDisplayDetailedChartCommand(self.callbackService, self, commandQueue, eventData, imageMapItem.userData));
};
// Moves the tooltip along with the mouse cursor.
NCustomTool.prototype.ProcessMouseMove = function (self, commandQueue, eventData) {
if (!self.tooltipVisible)
return;
var imageMapItem = eventData.imageMapObjectItem;
if (imageMapItem == null)
return;
commandQueue.Enqueue(new NDisplayDetailedChartCommand(self.callbackService, self, commandQueue, eventData, imageMapItem.userData));
};
// Hides the tooltip.
NCustomTool.prototype.ProcessMouseLeave = function (self, commandQueue, eventData) {
if (!self.tooltipVisible)
return;
self.tooltipVisible = false;
self.currentImageMapObjectItem = null;
commandQueue.Enqueue(new NHideDetailedChartCommand(self, commandQueue, eventData));
};
////////////////////////////////
// class NDisplayDetailedChartCommand
function NDisplayDetailedChartCommand(callbackService, tool, commandQueue, eventData, continent) {
// Runtime type info initialization
this.InitializeRuntimeTypeInfo(NDisplayDetailedChartCommand.prototype);
this.NCallbackCommand(callbackService, tool, commandQueue);
// The event data, associated with the event that caused the command generation.
this.eventData = null;
// The text of the tooltip.
this.continent = "Asia";
if (NReflection.IsInstance(eventData))
this.eventData = eventData;
if (NReflection.IsInstance(continent))
this.continent = continent;
};
// Inheritance
NDisplayDetailedChartCommand.DeriveFrom(NCallbackCommand);
// Creates/shows the tooltip div and displays the tooltip text within.
NDisplayDetailedChartCommand.prototype.Execute = function (self) {
var base = NDisplayDetailedChartCommand.GetBase();
var boxDiv;
var boxDivHeight = 200;
var boxDivDefaultWidth = 500;
var t = self.tool;
if (t.tooltipDiv == null) {
boxDiv = document.createElement("div");
boxDiv.style.height = NBrowserCaps.ToPixelLength(boxDivHeight);
boxDiv.style.width = NBrowserCaps.ToPixelLength(boxDivDefaultWidth);
if (self.cssClass != null)
boxDiv.className = self.cssClass;
boxDiv.style.position = "absolute";
var boxDivChildren = boxDiv.childNodes;
for (var i = 0; i <
boxDivChildren.length
; i++) {
var
childElement
=
boxDivChildren
[i];
childElement["CallbackService"] = self.callbackService;
}
document.body.appendChild(boxDiv);
t.tooltipDiv
=
boxDiv
;
boxDiv["CallbackService"] = self.callbackService;
boxDiv.onmousemove
=
NEventSinkService
.MouseMoveHandler;
}
else {
boxDiv
=
t
.tooltipDiv;
}
if (boxDiv.style.display != "block") {
boxDiv.style.display
=
"block"
;
boxDiv.innerHTML
=
"<img src='~/NevronCustomTools.axd?continent="
+ self.continent + "'><
br
/>";
}
var left = self.eventData.pageOffset.offsetLeft + 10;
var top = self.eventData.pageOffset.offsetTop - boxDivHeight - 10;
var documentWidth = 0;
if (document.documentElement != null && document.documentElement["clientWidth"] != null) {
documentWidth = document.documentElement.clientWidth;
}
else if (document.body != null && document.body["clientWidth"] != null) {
documentWidth = document.body.clientWidth;
}
if (documentWidth != 0) {
var width = boxDiv.offsetWidth;
var windowScrollPos = NBrowserCaps.GetScrollLeft();
if (left + width > documentWidth + windowScrollPos)
left = documentWidth - width + windowScrollPos;
}
if (top <
0
)
top
=
0
;
boxDiv.style.left
=
NBrowserCaps
.ToPixelLength(left);
boxDiv.style.top
=
NBrowserCaps
.ToPixelLength(top);
base.Execute(self);
};
////////////////////////////////
// class NHideDetailedChartCommand
function NHideDetailedChartCommand(tool, commandQueue, eventData) {
// Runtime type info initialization
this.InitializeRuntimeTypeInfo(NHideDetailedChartCommand.prototype);
this.NCommand(tool, commandQueue);
// The event data, associated with the event that caused the command generation.
this.eventData
=
null
;
if (NReflection.IsInstance(eventData))
this.eventData
= eventData;
};
// Inheritance
NHideDetailedChartCommand.DeriveFrom(NCommand);
//Hides the tooltip div.
NHideDetailedChartCommand.prototype.Execute
=
function
(self) {
var
base
=
NHideDetailedChartCommand
.GetBase();
var
t
=
self
.tool;
t.tooltipDiv.className
=
""
;
t.tooltipDiv.style.display
=
"none"
;
base.Execute(self);
};
////////////////////////////////
// class NCustomToolFactory
//
// This class will be used as a tool factory, because in our control initialization
// the AjaxToolsFactoryType property of the web control is set to "NCustomToolFactory".
function NCustomToolFactory() {
// Runtime type info initialization
this.InitializeRuntimeTypeInfo(NCustomToolFactory.prototype);
this.NToolFactory(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], arguments[8], arguments[9]);
};
// Inheritance
NCustomToolFactory.DeriveFrom(NToolFactory);
// Resets the callback service controller tools and initializes the controller
// with new tools, created on the base of the tool configuration objects that are
// cached in the configurationItems hashtable.
NCustomToolFactory.prototype.InitializeTools
=
function
(self, callbackService) {
var
base
=
NCustomToolFactory
.GetBase();
// initialize the built-in tools
base.InitializeTools(self, callbackService);
var
dictionaryEntries
=
self
.configurationItems.GetDictionaryEntries();
var
tools
=
callbackService
.controller.GetTools();
// initialize the custom tools
for (var
i
=
0
; i < dictionaryEntries.length; i++) {
var
toolConfig
=
dictionaryEntries
[i].val;
var
tool
=
null
;
if (toolConfig.toolId == NCustomTool.GetClassName()) {
tool
=
new
NCustomTool(callbackService, toolConfig);
}
if (tool != null) {
tools[tools.length] = tool;
tool.controller
=
callbackService
.controller;
}
}
}
//-->
</
script
>
<
div
>
<
ncwc:NChartControl
ID
=
"nChartControl1"
runat
=
"server"
Height
=
"400px"
Width
=
"465px"
AjaxEnabled
=
"True"
AsyncCallbackTimeout
=
"10000"
AsyncRequestWaitCursorEnabled
=
"False"
OnQueryAjaxTools
=
"nChartControl1_QueryAjaxTools"
>
</
ncwc:NChartControl
>
</
div
>
</
form
>
</
body
>
</
html
>
6. From the Solution explorer open the Default.aspx.cs (Default.aspx.vb) file and use the following code to programmatically create the main bar chart:
[C#]
using
System;
using
System.Data;
using
System.Data.OleDb;
using
System.Drawing;
using
System.Web;
using
Nevron.Chart;
using
Nevron.GraphicsCore;
using
Nevron.UI.WebForm.Controls;
namespace
WebApplication
{
public
partial
class
_Default : System.Web.UI.Page
{
protected
void
Page_Load(
object
sender, EventArgs e)
{
nChartControl1.AjaxToolsFactoryType =
"NCustomToolFactory"
;
if
(nChartControl1.RequiresInitialization)
{
//setting the bar chart
nChartControl1.BackgroundStyle.FrameStyle.Visible =
false
;
nChartControl1.Legends.Clear();
nChartControl1.Settings.JitterMode = JitterMode.Enabled;
nChartControl1.Settings.JitteringSteps = 16;
NChart chart = nChartControl1.Charts[0];
chart.Axis(StandardAxis.Depth).Visible =
false
;
chart.DockMargins =
new
NMarginsL(20, 10, 10, 30);
chart.BoundsMode = BoundsMode.Stretch;
chart.Enable3D =
true
;
chart.Depth = 10;
chart.Projection.SetPredefinedProjection(PredefinedProjection.Perspective);
chart.LightModel.SetPredefinedLightModel(PredefinedLightModel.MetallicLustre);
NBarSeries bar = (NBarSeries)chart.Series.Add(SeriesType.Bar);
bar.BarShape = BarShape.SmoothEdgeBar;
bar.BarEdgePercent = 20;
bar.HasBottomEdge =
false
;
DataTable table = ReadData(
"Continent"
);
nChartControl1.DataBindingManager.EnableDataBinding =
true
;
nChartControl1.DataBindingManager.AddBinding(0, 0,
"Values"
, table,
"Column2"
);
bar.InteractivityStyles.Add(0,
new
NInteractivityStyle(
true
,
"North America"
,
null
, CursorType.Hand));
bar.InteractivityStyles.Add(1,
new
NInteractivityStyle(
true
,
"South America"
,
null
, CursorType.Hand));
bar.InteractivityStyles.Add(2,
new
NInteractivityStyle(
true
,
"Europe"
,
null
, CursorType.Hand));
bar.InteractivityStyles.Add(3,
new
NInteractivityStyle(
true
,
"Asia"
,
null
, CursorType.Hand));
//bar.InteractivityStyles.Add(4, new NInteractivityStyle(true, "Australia", null, CursorType.Hand));
//Adding X axis labels
NOrdinalScaleConfigurator scaleX = chart.Axis(StandardAxis.PrimaryX).ScaleConfigurator
as
NOrdinalScaleConfigurator;
scaleX.AutoLabels =
false
;
int
nCount = table.Rows.Count;
for
(
int
i = 0; i < nCount; i++)
{
NCustomValueLabel label =
new
NCustomValueLabel(i, table.Rows[i][0].ToString());
label.Style.TextStyle =
new
NTextStyle(
new
Font(
"Verdana"
, 8), Color.Black);
label.Style.Angle =
new
NScaleLabelAngle(ScaleLabelAngleMode.View, -45);
label.Style.ContentAlignment = ContentAlignment.TopRight;
scaleX.CustomLabels.Add(label);
}
// setup Y axis
NAxis Yaxis = chart.Axis(StandardAxis.PrimaryY);
NLinearScaleConfigurator linearScale = (NLinearScaleConfigurator)Yaxis.ScaleConfigurator;
linearScale.MajorGridStyle.LineStyle.Pattern = LinePattern.Dot;
linearScale.MajorGridStyle.SetShowAtWall(ChartWallType.Left,
false
);
linearScale.InnerMajorTickStyle.Length =
new
NLength(0);
linearScale.LabelStyle.TextStyle =
new
NTextStyle(
new
Font(
"Verdana"
, 8), Color.Black);
// add interlaced stripe to the Y axis
NScaleStripStyle stripStyle =
new
NScaleStripStyle(
new
NColorFillStyle(Color.Beige),
null
,
true
, 0, 0, 1, 1);
stripStyle.Interlaced =
true
;
stripStyle.SetShowAtWall(ChartWallType.Back,
true
);
stripStyle.SetShowAtWall(ChartWallType.Left,
true
);
linearScale.StripStyles.Add(stripStyle);
NStyleSheet styleSheet = NStyleSheet.CreatePredefinedStyleSheet(PredefinedStyleSheet.Pastel);
styleSheet.Apply(nChartControl1.Document);
}
}
private
DataTable ReadData(
string
sheetName)
{
DataTable resultTable =
new
DataTable();
string
connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+
HttpContext.Current.Server.MapPath(@
"~\App_Data\chartData.xls"
) +
";Extended Properties=Excel 8.0;"
;
OleDbConnection oleDbConnection1 =
new
OleDbConnection(connectionString);
OleDbCommand oleDbCommand1 =
new
OleDbCommand(
"SELECT * From ["
+ sheetName +
"$]"
, oleDbConnection1);
OleDbDataReader oleDbDataReader1 =
null
;
try
{
oleDbConnection1.Open();
oleDbDataReader1 = oleDbCommand1.ExecuteReader();
int
columns = oleDbDataReader1.FieldCount;
//Creates columns in result table
for
(
int
i = 0; i < columns; i++)
{
DataColumn dc =
new
DataColumn();
resultTable.Columns.Add(dc);
}
//adds the data from excel file in the result table.
while
(oleDbDataReader1.Read())
{
DataRow dr = resultTable.NewRow();
for
(
int
i = 0; i < columns; i++)
{
dr[i] = oleDbDataReader1[i].ToString();
}
resultTable.Rows.Add(dr);
}
}
catch
{ }
finally
{
oleDbConnection1.Close();
}
return
resultTable;
}
protected
void
nChartControl1_QueryAjaxTools(
object
sender, EventArgs e)
{
// configure the client side tools
nChartControl1.AjaxTools.Add(
new
NAjaxDynamicCursorTool(
true
));
nChartControl1.AjaxTools.Add(
new
NAjaxCustomTool(
true
));
}
}
/// <summary>
/// Provides configuration for the client side NAjaxCustomTool tool.
/// </summary>
[Serializable]
public
class
NAjaxCustomTool : NAjaxToolDefinition
{
#region Constructors
/// <summary>
/// Initializes a new instance of NAjaxCustomTool with a given default enabled value.
/// </summary>
/// <param name="defaultEnabled">
/// Selects the initial enabled state of the tool.
/// </param>
public
NAjaxCustomTool(
bool
defaultEnabled)
:
base
(@
"NCustomTool"
, defaultEnabled)
{
}
#endregion
#region Overrides
/// <summary>
/// Generates JavaScript that will create a new tool configuration object at the client.
/// </summary>
/// <returns>Returns a JavaScript that will create a new tool configuration object at the client.</returns>
protected
override
string
GetConfigurationObjectJavaScript()
{
return
"new NCustomToolConfig()"
;
}
#endregion
}
}
[VB.NET]
Imports
Microsoft.VisualBasic
Imports
System
Imports
System.Data
Imports
System.Data.OleDb
Imports
System.Drawing
Imports
System.Web
Imports
Nevron.GraphicsCore
Imports
Nevron.UI.WebForm.Controls
Imports
Nevron.Chart
Partial Public
Class
[_Default]
Inherits
System.Web.UI.Page
Protected
Sub
Page_Load(
ByVal
sender
As
Object
,
ByVal
e
As
EventArgs)
nChartControl1.AjaxToolsFactoryType =
"NCustomToolFactory"
If
nChartControl1.RequiresInitialization
Then
'setting the bar chart
nChartControl1.BackgroundStyle.FrameStyle.Visible =
False
nChartControl1.Legends.Clear()
nChartControl1.Settings.JitterMode = JitterMode.Enabled
nChartControl1.Settings.JitteringSteps = 16
Dim
chart
As
NChart = nChartControl1.Charts(0)
chart.Axis(StandardAxis.Depth).Visible =
False
chart.DockMargins =
New
NMarginsL(20, 10, 10, 30)
chart.BoundsMode = BoundsMode.Stretch
chart.Enable3D =
True
chart.Depth = 10
chart.Projection.SetPredefinedProjection(PredefinedProjection.Perspective)
chart.LightModel.SetPredefinedLightModel(PredefinedLightModel.MetallicLustre)
Dim
bar
As
NBarSeries =
CType
(chart.Series.Add(SeriesType.Bar), NBarSeries)
bar.BarShape = BarShape.SmoothEdgeBar
bar.BarEdgePercent = 20
bar.HasBottomEdge =
False
Dim
table
As
DataTable = ReadData(
"Continent"
)
nChartControl1.DataBindingManager.EnableDataBinding =
True
nChartControl1.DataBindingManager.AddBinding(0, 0,
"Values"
, table,
"Column2"
)
bar.InteractivityStyles.Add(0,
New
NInteractivityStyle(
True
,
"North America"
,
Nothing
, CursorType.Hand))
bar.InteractivityStyles.Add(1,
New
NInteractivityStyle(
True
,
"South America"
,
Nothing
, CursorType.Hand))
bar.InteractivityStyles.Add(2,
New
NInteractivityStyle(
True
,
"Europe"
,
Nothing
, CursorType.Hand))
bar.InteractivityStyles.Add(3,
New
NInteractivityStyle(
True
,
"Asia"
,
Nothing
, CursorType.Hand))
'bar.InteractivityStyles.Add(4, new NInteractivityStyle(true, "Australia", null, CursorType.Hand));
'Adding X axis labels
Dim
scaleX
As
NOrdinalScaleConfigurator = TryCast(chart.Axis(StandardAxis.PrimaryX).ScaleConfigurator, NOrdinalScaleConfigurator)
scaleX.AutoLabels =
False
Dim
nCount
As
Integer
= table.Rows.Count
Dim
i
As
Integer
= 0
Do
While
i < nCount
Dim
label
As
NCustomValueLabel =
New
NCustomValueLabel(i, table.Rows(i)(0).ToString())
label.Style.TextStyle =
New
NTextStyle(
New
Font(
"Verdana"
, 8), Color.Black)
label.Style.Angle =
New
NScaleLabelAngle(ScaleLabelAngleMode.View, -45)
label.Style.ContentAlignment = ContentAlignment.TopRight
scaleX.CustomLabels.Add(label)
i += 1
Loop
' setup Y axis
Dim
Yaxis
As
NAxis = chart.Axis(StandardAxis.PrimaryY)
Dim
linearScale
As
NLinearScaleConfigurator =
CType
(Yaxis.ScaleConfigurator, NLinearScaleConfigurator)
linearScale.MajorGridStyle.LineStyle.Pattern = LinePattern.Dot
linearScale.MajorGridStyle.SetShowAtWall(ChartWallType.Left,
False
)
linearScale.InnerMajorTickStyle.Length =
New
NLength(0)
linearScale.LabelStyle.TextStyle =
New
NTextStyle(
New
Font(
"Verdana"
, 8), Color.Black)
' add interlaced stripe to the Y axis
Dim
stripStyle
As
NScaleStripStyle =
New
NScaleStripStyle(
New
NColorFillStyle(Color.Beige),
Nothing
,
True
, 0, 0, 1, 1)
stripStyle.Interlaced =
True
stripStyle.SetShowAtWall(ChartWallType.Back,
True
)
stripStyle.SetShowAtWall(ChartWallType.Left,
True
)
linearScale.StripStyles.Add(stripStyle)
Dim
styleSheet
As
NStyleSheet = NStyleSheet.CreatePredefinedStyleSheet(PredefinedStyleSheet.Pastel)
styleSheet.Apply(nChartControl1.Document)
End
If
End
Sub
Private
Function
ReadData(
ByVal
sheetName
As
String
)
As
DataTable
Dim
resultTable
As
DataTable =
New
DataTable()
Dim
connectionString
As
String
=
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
& HttpContext.Current.Server.MapPath(
"~\App_Data\chartData.xls"
) &
";Extended Properties=Excel 8.0;"
Dim
oleDbConnection1
As
OleDbConnection =
New
OleDbConnection(connectionString)
Dim
oleDbCommand1
As
OleDbCommand =
New
OleDbCommand(
"SELECT * From ["
& sheetName &
"$]"
, oleDbConnection1)
Dim
oleDbDataReader1
As
OleDbDataReader =
Nothing
Try
oleDbConnection1.Open()
oleDbDataReader1 = oleDbCommand1.ExecuteReader()
Dim
columns
As
Integer
= oleDbDataReader1.FieldCount
'Creates columns in result table
Dim
i
As
Integer
= 0
Do
While
i < columns
Dim
dc
As
DataColumn =
New
DataColumn()
resultTable.Columns.Add(dc)
i += 1
Loop
'adds the data from excel file in the result table.
Do
While
oleDbDataReader1.Read()
Dim
dr
As
DataRow = resultTable.NewRow()
i = 0
Do
While
i < columns
dr(i) = oleDbDataReader1(i).ToString()
i += 1
Loop
resultTable.Rows.Add(dr)
Loop
Catch
Finally
oleDbConnection1.Close()
End
Try
Return
resultTable
End
Function
Protected
Sub
nChartControl1_QueryAjaxTools(
ByVal
sender
As
Object
,
ByVal
e
As
EventArgs)
' configure the client side tools
nChartControl1.AjaxTools.Add(
New
NAjaxDynamicCursorTool(
True
))
nChartControl1.AjaxTools.Add(
New
NAjaxCustomTool(
True
))
End
Sub
End
Class
''' <summary>
''' Provides configuration for the client side NAjaxCustomTool tool.
''' </summary>
<Serializable> _
Public
Class
NAjaxCustomTool
Inherits
NAjaxToolDefinition
#Region "Constructors"
''' <summary>
''' Initializes a new instance of NAjaxCustomTool with a given default enabled value.
''' </summary>
''' <param name="defaultEnabled">
''' Selects the initial enabled state of the tool.
''' </param>
Public
Sub
New
(
ByVal
defaultEnabled
As
Boolean
)
MyBase
.
New
(
"NCustomTool"
, defaultEnabled)
End
Sub
#End Region
#Region "Overrides"
''' <summary>
''' Generates JavaScript that will create a new tool configuration object at the client.
''' </summary>
''' <returns>Returns a JavaScript that will create a new tool configuration object at the client.</returns>
Protected
Overrides
Function
GetConfigurationObjectJavaScript()
As
String
Return
"new NCustomToolConfig()"
End
Function
#End Region
End
Class
7. From the Solution explorer open the PieChart.cs (PieChart.vb) file and use the following code to programmatically create the Pie chart that will be displayed in the preview:
[C#]
using
System.Data;
using
System.Data.OleDb;
using
System.Drawing;
using
System.IO;
using
System.Web;
using
Nevron.Chart;
using
Nevron.Chart.WebForm;
using
Nevron.GraphicsCore;
namespace
WebApplication
{
public
class
PieChart : IHttpHandler
{
public
PieChart()
{
}
#region IHttpHandler Implementation
void
IHttpHandler.ProcessRequest(HttpContext context)
{
string
continent = context.Request[
"continent"
];
MemoryStream ms =
new
MemoryStream();
NSize chartSize =
new
NSize(250, 200);
NDocument document = CreateDocument(continent);
document.BackgroundStyle.FrameStyle.Visible =
true
;
document.BackgroundStyle.FillStyle =
new
NGradientFillStyle(GradientStyle.Horizontal, GradientVariant.Variant2, Color.AliceBlue, Color.LightGray);
document.Settings.JitterMode = JitterMode.Enabled;
document.Settings.JitteringSteps = 16;
NPngImageFormat imageFormat =
new
NPngImageFormat();
using
(INImage image = CreateImage(document, chartSize, imageFormat))
{
image.SaveToStream(ms, imageFormat);
}
byte
[] bytes = ms.GetBuffer();
context.Response.ContentType =
"image/png"
;
context.Response.OutputStream.Write(bytes, 0, bytes.Length);
context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
}
bool
IHttpHandler.IsReusable
{
get
{
return
true
;
}
}
#endregion
NDocument CreateDocument(
string
continent)
{
DataTable table = ReadData(continent);
NChartControl NChartControl1 =
new
NChartControl();
NChartControl1.BackgroundStyle.FrameStyle.Visible =
false
;
NChartControl1.Panels.Clear();
NPieChart chart =
new
NPieChart();
NChartControl1.Charts.Add(chart);
chart.Enable3D =
true
;
chart.Width = 70;
chart.Depth = 10;
chart.Size =
new
NSizeL(
new
NLength(98, NRelativeUnit.ParentPercentage),
new
NLength(99, NRelativeUnit.ParentPercentage));
chart.Location =
new
NPointL(
new
NLength(2, NRelativeUnit.ParentPercentage),
new
NLength(0, NRelativeUnit.ParentPercentage));
chart.Projection.SetPredefinedProjection(PredefinedProjection.Perspective);
chart.LightModel.SetPredefinedLightModel(PredefinedLightModel.MetallicLustre);
NPieSeries pie = (NPieSeries)chart.Series.Add(SeriesType.Pie);
pie.PieStyle = PieStyle.CutEdgeRing;
pie.InnerRadius =
new
NLength(15);
pie.PieEdgePercent = 30;
pie.LabelMode = PieLabelMode.SpiderNoOverlap;
pie.DataLabelStyle.Format =
"<label>\n<percent>"
;
pie.DataLabelStyle.TextStyle =
new
NTextStyle(
new
Font(
"Verdana"
, 7), Color.Black);
NChartControl1.DataBindingManager.EnableDataBinding =
true
;
NChartControl1.DataBindingManager.AddBinding(0, 0,
"Values"
, table,
"Column3"
);
NChartControl1.DataBindingManager.AddBinding(0, 0,
"Labels"
, table,
"Column2"
);
NDocument document =
new
NDocument();
document.RootPanel.Charts.Clear();
NStyleSheet styleSheet = NStyleSheet.CreatePredefinedStyleSheet(PredefinedStyleSheet.BrightMultiColor);
styleSheet.Apply(NChartControl1.Document);
document.Charts.Add(chart);
return
document;
}
private
DataTable ReadData(
string
continent)
{
DataTable resultTable =
new
DataTable();
string
connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+
HttpContext.Current.Server.MapPath(@
"~\App_Data\chartData.xls"
) +
";Extended Properties=Excel 8.0;"
;
OleDbConnection oleDbConnection1 =
new
OleDbConnection(connectionString);
OleDbCommand oleDbCommand1 =
new
OleDbCommand(
"SELECT * From [Country$] where [Continent] = '"
+ continent +
"'"
, oleDbConnection1);
OleDbDataReader oleDbDataReader1 =
null
;
try
{
oleDbConnection1.Open();
oleDbDataReader1 = oleDbCommand1.ExecuteReader();
int
columns = oleDbDataReader1.FieldCount;
//Creates columns in result table
for
(
int
i = 0; i < columns; i++)
{
DataColumn dc =
new
DataColumn();
resultTable.Columns.Add(dc);
}
//adds the data from excel file in the result table.
while
(oleDbDataReader1.Read())
{
DataRow dr = resultTable.NewRow();
for
(
int
i = 0; i < columns; i++)
{
dr[i] = oleDbDataReader1[i].ToString();
}
resultTable.Rows.Add(dr);
}
}
catch
{ }
finally
{
oleDbConnection1.Close();
}
return
resultTable;
}
protected
INImage CreateImage(NDocument document, NSize size, NPngImageFormat imageFormat)
{
INImageFormatProvider imageFormatProvider =
new
NChartRasterImageFormatProvider(document);
return
imageFormatProvider.ProvideImage(size, NResolution.ScreenResolution, imageFormat);
}
}
}
[VB.NET]
Imports
Microsoft.VisualBasic
Imports
System.Data
Imports
System.Data.OleDb
Imports
System.Drawing
Imports
System.IO
Imports
System.Web
Imports
Nevron.Chart.WebForm
Imports
Nevron.GraphicsCore
Imports
Nevron.Chart
Public
Class
PieChart
Implements
IHttpHandler
Public
Sub
New
()
End
Sub
#Region "IHttpHandler Implementation"
Private
Sub
ProcessRequest(
ByVal
context
As
HttpContext)
Implements
IHttpHandler.ProcessRequest
Dim
continent
As
String
= context.Request(
"continent"
)
Dim
ms
As
MemoryStream =
New
MemoryStream()
Dim
chartSize
As
NSize =
New
NSize(250, 200)
Dim
document
As
NDocument = CreateDocument(continent)
document.BackgroundStyle.FrameStyle.Visible =
True
document.BackgroundStyle.FillStyle =
New
NGradientFillStyle(GradientStyle.Horizontal, GradientVariant.Variant2, Color.AliceBlue, Color.LightGray)
document.Settings.JitterMode = JitterMode.Enabled
document.Settings.JitteringSteps = 16
Dim
imageFormat
As
NPngImageFormat =
New
NPngImageFormat()
Using image
As
INImage = CreateImage(document, chartSize, imageFormat)
image.SaveToStream(ms, imageFormat)
End
Using
Dim
bytes
As
Byte
() = ms.GetBuffer()
context.Response.ContentType =
"image/png"
context.Response.OutputStream.Write(bytes, 0, bytes.Length)
context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate)
End
Sub
Private
ReadOnly
Property
IsReusable()
As
Boolean
Implements
IHttpHandler.IsReusable
Get
Return
True
End
Get
End
Property
#End Region
Private
Function
CreateDocument(
ByVal
continent
As
String
)
As
NDocument
Dim
table
As
DataTable = ReadData(continent)
Dim
NChartControl1
As
NChartControl =
New
NChartControl()
NChartControl1.BackgroundStyle.FrameStyle.Visible =
False
NChartControl1.Panels.Clear()
Dim
chart
As
NPieChart =
New
NPieChart()
NChartControl1.Charts.Add(chart)
chart.Enable3D =
True
chart.Width = 70
chart.Depth = 10
chart.Size =
New
NSizeL(
New
NLength(98, NRelativeUnit.ParentPercentage),
New
NLength(99, NRelativeUnit.ParentPercentage))
chart.Location =
New
NPointL(
New
NLength(2, NRelativeUnit.ParentPercentage),
New
NLength(0, NRelativeUnit.ParentPercentage))
chart.Projection.SetPredefinedProjection(PredefinedProjection.Perspective)
chart.LightModel.SetPredefinedLightModel(PredefinedLightModel.MetallicLustre)
Dim
pie
As
NPieSeries =
CType
(chart.Series.Add(SeriesType.Pie), NPieSeries)
pie.PieStyle = PieStyle.CutEdgeRing
pie.InnerRadius =
New
NLength(15)
pie.PieEdgePercent = 30
pie.LabelMode = PieLabelMode.SpiderNoOverlap
pie.DataLabelStyle.Format =
"<label>"
& Constants.vbLf &
"<percent>"
pie.DataLabelStyle.TextStyle =
New
NTextStyle(
New
Font(
"Verdana"
, 7), Color.Black)
NChartControl1.DataBindingManager.EnableDataBinding =
True
NChartControl1.DataBindingManager.AddBinding(0, 0,
"Values"
, table,
"Column3"
)
NChartControl1.DataBindingManager.AddBinding(0, 0,
"Labels"
, table,
"Column2"
)
Dim
document
As
NDocument =
New
NDocument()
document.RootPanel.Charts.Clear()
Dim
styleSheet
As
NStyleSheet = NStyleSheet.CreatePredefinedStyleSheet(PredefinedStyleSheet.BrightMultiColor)
styleSheet.Apply(NChartControl1.Document)
document.Charts.Add(chart)
Return
document
End
Function
Private
Function
ReadData(
ByVal
continent
As
String
)
As
DataTable
Dim
resultTable
As
DataTable =
New
DataTable()
Dim
connectionString
As
String
=
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
& HttpContext.Current.Server.MapPath(
"~\App_Data\chartData.xls"
) &
";Extended Properties=Excel 8.0;"
Dim
oleDbConnection1
As
OleDbConnection =
New
OleDbConnection(connectionString)
Dim
oleDbCommand1
As
OleDbCommand =
New
OleDbCommand(
"SELECT * From [Country$] where [Continent] = '"
& continent &
"'"
, oleDbConnection1)
Dim
oleDbDataReader1
As
OleDbDataReader =
Nothing
Try
oleDbConnection1.Open()
oleDbDataReader1 = oleDbCommand1.ExecuteReader()
Dim
columns
As
Integer
= oleDbDataReader1.FieldCount
'Creates columns in result table
Dim
i
As
Integer
= 0
Do
While
i < columns
Dim
dc
As
DataColumn =
New
DataColumn()
resultTable.Columns.Add(dc)
i += 1
Loop
'adds the data from excel file in the result table.
Do
While
oleDbDataReader1.Read()
Dim
dr
As
DataRow = resultTable.NewRow()
i = 0
Do
While
i < columns
dr(i) = oleDbDataReader1(i).ToString()
i += 1
Loop
resultTable.Rows.Add(dr)
Loop
Catch
Finally
oleDbConnection1.Close()
End
Try
Return
resultTable
End
Function
Protected
Function
CreateImage(
ByVal
document
As
NDocument,
ByVal
size
As
NSize,
ByVal
imageFormat
As
NPngImageFormat)
As
INImage
Dim
imageFormatProvider
As
INImageFormatProvider =
New
NChartRasterImageFormatProvider(document)
Return
imageFormatProvider.ProvideImage(size, NResolution.ScreenResolution, imageFormat)
End
Function
End
Class
Related ASP.NET AJAX Examples:
Nevron Chart for .NET: http://examplesaspnetchart.nevron.com/
Contents > AJAX
For more details, take a look at the Online Documentation
Framework > Web FormsArticle ID: 176, Created On: 2/16/2011, Modified: 2/16/2011