Live HighChart not displaying data - c#

I am trying the code of highstocks which is given below
<script type="text/javascript">
$(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
// Create the chart
$('#container').highcharts('StockChart', {
chart: {
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = <%=chartData%>
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title: {
text: 'Sensor Data'
},
exporting: {
enabled: false
},
series: [{
name: 'Sensor Value',
data: (function () {
//generate an array of random data
var data = [], time = (new Date()).getTime(), i;
for (i = -999; i <= 0; i++) {
data.push([
time + i * 1000,
<%= chartData%>
]);
}
return data;
})()
}]
});
});
</script>
and displaying it in to the container
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto; width: 733px;"></div>
The code behind is
public string chartData
{
get;
set;
}
protected void Page_Load(object sender, EventArgs e)
{
GetData();
List<int> _data = new List<int>();
foreach (DataRow row in dt.Rows)
{
_data.Add((int)row["Id"]);
}
JavaScriptSerializer jss = new JavaScriptSerializer();
chartData = jss.Serialize(_data); //this make your list in jSON format like [88,99,10]
Response.Write(chartData);
}
private void GetData()
{
StringBuilder str = new StringBuilder();
SqlConnection con = new SqlConnection("Data Source=INBDQ2WK2LBCD2S\\SQLEXPRESS;Initial Catalog=MCAS;Integrated Security=SSPI");
SqlDataAdapter adp = new SqlDataAdapter("select top 1 Id from Monitoring order by Id desc ", con);
adp.Fill(dt);
}
Here I have created a JSON and I am transferring it to the javascript for highchart.
The problem I am having is that it is showing only one point. The values which are also updated in the database it is not updating in the chart.
What is wrong with it?

In your code I can see this:
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = <%=chartData%>;
series.addPoint([x, y], true, true);
}, 1000);
I guess, that chartData variable is where you have stored new point? At least you expect to have there. However your variable chartData is assigned in HTML once, after page is loaded from server. That you will update value on server, doesn't mean value get updated on client side.
I advice to use AJAX calls, for example: http://www.highcharts.com/studies/live-server.htm (see sources for code example).

Related

ASP.NET MVC: Bar Chart from JSON Data ViewBag

I have a JSON data from database like below to build a dashboard in dashboard ASP.NET MVC. I would like to draw a daily and monthly bar chart with x-axis as datetime (Day) and y-axis as count of activities in a day.
JSON Data:
[{"count":42,"datetime":"2020-07-18T00:00:00"},{"count":49,"datetime":"2020-07-16T00:00:00"},{"count":90,"datetime":"2020-07-14T00:00:00"},{"count":85,"datetime":"2020-07-17T00:00:00"},{"count":100,"datetime":"2020-07-13T00:00:00"},{"count":38,"datetime":"2020-07-19T00:00:00"},{"count":53,"datetime":"2020-07-15T00:00:00"}]
and i want something like this
I've tried the following javascript code but can't. JSON data obtained from ViewBag.dataItems
<script type="text/javascript" >
window.onload = function () {
var result = #Html.Raw(ViewBag.dataItems);
var DataItem =[];
for (var i = 0; i < result.length; i++){
DataItem.push({
x: new Date(result[i].datetime),
y: result[i].count
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
data: [{
type: "column",
DataItem: DataItem
}]
});
chart.render();
};
</script>
ThankYou
As I referred to some samples from https://canvasjs.com/docs/charts/chart-types/html5-column-chart/, they used dataPoints property instead of DataItem.
Here is a sample following your data. Hope to help, my friend :))
1. Controllers
public ActionResult Add()
{
ViewData["data"] = #"[{'count':42,'datetime':'2020-07-18T00:00:00'},{'count':49,'datetime':'2020-07-16T00:00:00'},{'count':90,'datetime':'2020-07-14T00:00:00'},{'count':85,'datetime':'2020-07-17T00:00:00'},{'count':100,'datetime':'2020-07-13T00:00:00'},{'count':38,'datetime':'2020-07-19T00:00:00'},{'count':53,'datetime':'2020-07-15T00:00:00'}]";
return View();
}
2. Views
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var result = #Html.Raw(ViewData["data"]);
this.console.log(result);
var DataItem = [];
for (var i = 0; i < result.length; i++) {
DataItem.push({
x: new Date(result[i].datetime),
y: result[i].count
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title: {
text: "Date Time Formatting"
},
data: [{
type: "column",
dataPoints: DataItem
}]
});
chart.render();
}
</script>

how to display Highcharts from database in C# .Net

I have seen this http://codepedia.info/chartjs-asp-net-create-pie-chart-with-database-calling-jquery-ajax-c/ link and followed every steps but dint get the output(i have used "public class cityPopulation") in code behind instead of asmx page will it be the error
</head>
<body>
<script>
function drawPieChart(seriesData) {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Population percentage city wise'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: "Brands",
colorByPoint: true,
data: seriesData
}]
});
}
$("#btnCreatePieChart").on('click', function (e) {
var pData = [];
pData[0] = $("#ddlyear").val();
var jsonData = JSON.stringify({ pData: pData });
$.ajax({
type: "POST",
url: "aspchartjsdemo.aspx/getCityPopulation",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
var arr = []
$.map(aData, function (item, index) {
var i = [item.city_name, item.population];
var obj = {};
obj.name = item.city_name;
obj.y = item.population;
arr.push(obj);
});
var myJsonString = JSON.stringify(arr);
var jsonArray = JSON.parse(JSON.stringify(arr));
drawPieChart(jsonArray);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
e.preventDefault();
});
</script>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlyear" runat="server" >
<asp:ListItem>2010</asp:ListItem>
<asp:ListItem>2011</asp:ListItem>
<asp:ListItem>2012</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnCreatePieChart" runat="server" Text="Button" />
<br />
<div>
<div id="container" style="width: 500px; height: 500px"></div>
</div>
</div>
</form>
</body>
</html>
here is my Code Behind..Im Unable to Fetch the data from database.
[WebMethod]
public List<cityPopulation> getCityPopulation(List<string> pData)
{
List<cityPopulation> p = new List<cityPopulation>();
using (NpgsqlConnection con = new NpgsqlConnection("Server=Localhost;Port=5432;User Id=postgres;Password=postgres;Database=database4;"))
{
string myQuery = "SELECT id_, city_name, population FROM tb_city_population WHERE year_of = #year";
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.CommandText = myQuery;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#year", pData[0]);
cmd.Connection = con;
con.Open();
NpgsqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
cityPopulation cpData = new cityPopulation();
cpData.city_name = dr["city_name"].ToString();
cpData.population = Convert.ToInt32(dr["population"].ToString());
p.Add(cpData);
}
}
}
return p;
}
public class cityPopulation
{
public string city_name { get; set; }
public int population { get; set; }
public string id { get; set; }
}
Any Help Highly appreciated..
This is how I build the Pie:
<div id="pieChart"></div>
<script type="text/javascript" src="highcharts.js"></script>
<script>
var myPieData = [ ['AAA', 34.03], ['BBB', 27.01], ['CCC', 18.77], ['DDD', 11.01], ['EEE', 5.91], ['FFF', 3.27] ];
chart = new Highcharts.Chart({
chart: {
renderTo: 'pieChart',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'My PieData'
},
tooltip: {
pointFormat: '<b>{point.percentage:.2f}%</b>',
percentageDecimals: 2
},
plotOptions: {
pie: {
allowPointSelect: false,
cursor: 'default',
dataLabels: {
enabled: false,
color: '#000000',
connectorColor: '#000000',
formatter: function () {
return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
}
}
}
},
series: [{
type: 'pie',
name: '',
data: myPieData
}]
});
</script>
The part you have to replace with your own data is [ ['Label A', 34.03], ['Label B', 27.01], ['Label C', 18.77], ['Label D', 11.01], ['Label E', 5.91], ['Label F', 3.27] ]
Of course the total value of all the data should be 100.00%
You can do that with a Literal or a string that is filled with content from code behind: var myPieData = [ <%= pieData %> ] or get it from an external source.
Depending on your localization settings, a numeric value can contain a "," instead of a "." (23,59 or 23.59). If your localization uses a "," you will have to replace that with a dot.
UPDATE
As requested an example of how to get a correct string that you can use to build the pie. This should get you started... Just make sure that population is in percentages, not absolute numbers.
public string getCityPopulation(List<string> pData)
{
StringBuilder sb = new StringBuilder();
string myQuery = "SELECT city_name, population FROM tb_city_population WHERE (year_of = #year)";
using (SqlConnection connection = new SqlConnection(Common.connectionString))
using (SqlCommand command = new SqlCommand(myQuery, connection))
{
command.Parameters.AddWithValue("#year", pData[0]);
try
{
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
sb.Append("[");
sb.Append("'" + dr["city_name"].ToString() + "'");
sb.Append(", ");
sb.Append(dr["population"].ToString().Replace(",", "."));
sb.Append("],");
}
}
}
catch
{
//error connecting\reading the database
}
}
return "[ " + sb.ToString().TrimEnd(',') + " ]";
}

google.visualiztion.ColumnChart() dont work

Here is my Jquery Ajax code to create a column chart using the Google API.
$(document).ready(function () {
//load Data Here
var chartData = null;
$.ajax({
url: '/Dashboard/GetData',
type: 'GET',
dataType: 'json',
data: '',
success: function (d) {
chartData = d;
},
error: function () {
alert('Error!');
}
}).done(function () {
google.charts.load("current", { packages: ['corechart'] });
drawChart(chartData);
}).fail(function () {
alert("Sorry. Server unavailable. ");
});
});`
function drawChart(d) {
var charData = d;
var data = null;
data = google.visualization.arrayToDataTable(charData);
var view = new google.visualization.DataView(data);
view.setColumns([0, {
type: 'number',
label: data.getColumnLabel(0),
calc: function () { return 0; }
}, {
type: 'number',
label: data.getColumnLabel(1),
calc: function () { return 0; }
}, {
type: 'number',
label: data.getColumnLabel(2),
calc: function () { return 0; }
}, {
type: 'number',
label: data.getColumnLabel(3),
calc: function () { return 0; }
}
]);
var options = {
title: 'Bodily Analysis',
legend: 'bottom',
hAxis: {
title: 'Year',
format: '#'
},
vAxis: {
minValue: 0,
maxValue: 1000,
title: 'Measurements'
},
chartArea: {
left: 100,
top: 50,
width: '70%',
height: '50%'
},
animation: {
duration: 1000
}
};
alert(data);
var chart = new google.visualiztion.ColumnChart(document.getElementById('visualization'));
alert(data);
var runFirstTime = google.visualization.events.addListener(chart, 'ready', function () {
google.visualization.events.removeListener(runFirstTime);
chart.draw(data, options);
});
chart.draw(view, options);
}
And here is my MVC controller which return data from the database in form of JSON.
public JsonResult GetData()
{
List<BusinessContact> Bc = new List<BusinessContact>();
using (BusinessContContext db = new BusinessContContext())
{
Bc = db.BusinessContacts.OrderBy(a => a.birthDate).ToList();
}
var charData = new object[Bc.Count + 1];
charData[0] = new object[]
{
"Birth",
"height",
"ChestMeasurement",
"Weight"
};
int j = 0;
foreach (var i in Bc)
{
j++;
charData[j] = new object[]
{
Convert.ToDateTime(i.birthDate).Year,
Convert.ToUInt32(i.height),
Convert.ToUInt32(i.ChestMeasurement),
Convert.ToUInt32(i.Weight)
};
}
return new JsonResult{Data = charData, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
The problem I have is that the chart does not render after the JsonResult is gotten from database. I noticed that alert is not prompted right after the
var chart = new google.visualiztion.ColumnChart(document.getElementById('visualization'));
Please i need help with this.

Array equivalent of Jquery in c#

I am trying to show a Pie Chart in my web application. Here is the data that was showing the Pie Chart in jquery.
var piedata = [
{ label: "Pending", data: 0 },
{ label: "In Progress", data: 65 },
{ label: "Cancelled", data: 15 },
{ label: "Submitted", data: 110 },
{ label: "Open", data: 60 },
{ label: "On Hold", data: 57 }
];
Here is the jquery Script to Show the Pie Chart
<script>
$(document).ready(function () {
var isPostBackObject = $("#hdnIsPostback");
alert(isPostBackObject.val());
if ($("#piechart").length) {
$.plot($("#piechart"), isPostBackObject.val(),
{
series: {
pie: {
show: true
}
},
grid: {
hoverable: true,
clickable: true
},
legend: {
show: false
}
});
function pieHover(event, pos, obj) {
if (!obj)
return;
percent = parseFloat(obj.series.percent).toFixed(2);
$("#hover").html('<span style="font-weight: bold; color: ' + obj.series.color + '">' + obj.series.label + ' (' + percent + '%)</span>');
}
$("#piechart").bind("plothover", pieHover);
}
});
</script>
Since this was in Jquery, so these are hard coded values. I have the status ifnormation in database that I want to set above. How do I set the data from code behind file so that I can show the Pie chart based on values from db.
I have tried to set like this
var data = new Dictionary<string, string>();
data.Add("Pending", "10");
data.Add("New", "40");
data.Add("Overdue", "50");
hdnIsPostback.Value = new JavaScriptSerializer().Serialize(data);
This code does show the Piechart but the labels like "Pending"/"New" dont show up in the Pie chart. Undefined appears instead. How do I do this?
You can use a normal C# array or IEnumerable..
You define a C# class;
public class PieModel {
public string label { get; set; }
public double data { get; set; }
}
And save the data to a list instead;
var data = new List<PieModel> {
new PieModel { label = "Pending", data = 10d }
new PieModel { label = "New", data = 40d }
new PieModel { label = "Overdue", data = 50d }
};
hdnIsPostback.Value = new JavaScriptSerializer().Serialize(data);
It is not tested code
With your updated answer you are going to need to parse the value of your textbox to JSON.. JSON.parse..
var isPostBackObject = $("#hdnIsPostback");
if ($("#piechart").length) {
$.plot($("#piechart"), JSON.parse(isPostBackObject.val()),
The JavaScriptSerializer will serialize your dictionary into an array of objects that contain Key and Value pairs ([{Key:"Pending", Value:"0"}...]) and that's definitely not the format you expect.
You need to project your dictionary into an array of objects containing label and data fields:
var pieData = data.Select(x => new
{
label = x.Key,
data = x.Value
}).ToArray();
Then serialize it to JSON:
hdnIsPostback.Value = new JavaScriptSerializer().Serialize(pieData);
The best equivalent IMO is the dynamic List as of C#4.0+ and anonymous types (objects)
var data=new List<dynamic>(){
new { label = "Pending", data = 10d },
new { label = "New", data = 40d },
new { label = "Overdue", data = 50d }
};
var serialised = new JavaScriptSerializer().Serialize(data);

how to import JSON data into VS2012 to plot highcharts

I want to import the data from JSON file into my VS2012 c# code so that I can plot my highcharts based on the data in JSON file.
I have checked many video on youtube and file docs but couldnt locate single code that runs and give an output as required.
Do give me a sample code that will map a data from JSON file, use it in vs2012 and plot the highcharts.
----------------Updated Question-------------
Below is the function I am trying to call in java-script where I want to evoke data from JSON format, but I am not able to call my function, below is my code
<script>
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
alert("outside");
$.getJSON('data.json', function (data) {
alert("INside");
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
and want to pass the data to the highcharts ,Since I am novice, any help will be greatly appreciated.
==============EDIT 2 =====================================
the Json file am trying to use for the data is in following format.
[
[1,12],
[2,5],
[3,18],
[4,13],
[5,7],
[6,4],
[7,9],
[8,10],
[9,15],
[10,22]
]
Thank You.
If JSON file is not rendering on the browser and your are getting 404 error then you might be facing the mime type handling problem, please refer the below link which resolves the issue,
getJSON method does not work
ASP.NET MVC Server Code:
namespace ABPMVCTest.Web.Controllers
{
[AbpMvcAuthorize]
public class HomeController : ABPMVCTestControllerBase
{
static Random _ran=new Random();
public ActionResult Index()
{
return View();
}
public ContentResult GetJsonResult()
{
var dataList = new List<ChartDataFormat>();
GetData(dataList, "总收入");
GetData(dataList, "投币收入");
GetData(dataList, "扫码充电收入");
GetData(dataList, "售线收入");
var dataJsonStr=JsonConvert.SerializeObject(dataList,new JsonSerializerSettings(){ContractResolver = new CamelCasePropertyNamesContractResolver()});
return Content(dataJsonStr);
}
private static List<ChartDataFormat> GetData(List<ChartDataFormat> dataList, string key)
{
var list = new List<int>();
for (int i = 0; i < 7; i++)
{
list.Add(_ran.Next(1, 3000));
}
dataList.Add(new ChartDataFormat
{
Name = key,
Data = list
});
return dataList;
}
}
class ChartDataFormat
{
public string Name { get; set; }
public List<int> Data { get; set; }
}
}
Client javascript Code:
$(function() {
Highcharts.setOptions({
lang: {
printChart: '打印图表',
downloadJPEG: '下载为JPEG图片',
downloadPDF: '下载为PDF',
downloadPNG: '下载为PNG图片',
downloadSVG: '下载为SVG矢量图',
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
weekdays: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
shortMonths: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
}
});
var nowDate = new Date();
var option = {
chart: {
type: 'area'
},
title: {
text: '收入趋势图'
},
subtitle: {
text: '没有选择时间范围的话,默认显示当日/月前后3天/月的数据'
},
credits: {
enabled:false
},
xAxis: {
type: 'datetime',
tickmarkPlacement: 'on',
title: {
enabled: false
},
dateTimeLabelFormats: {
day: "%Y-%m-%d",
week: "%A",
month: "%Y-%m",
year: "%Y"
}
},
yAxis: {
title: {
text: '单位:元'
},
labels: {
formatter: function() {
return this.value;
}
}
},
tooltip: {
shared: true,
valueSuffix: ' 元',
dateTimeLabelFormats: {
day: "%Y-%m-%d,%A",
week: "%A开始, %Y-%m-%d",
month: "%Y-%m",
year: "%Y"
}
},
plotOptions: {
area: {
stacking: 'normal',
lineColor: '#666666',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#666666'
}
},
series: {
pointStart:Date.UTC(nowDate.getFullYear(),nowDate.getMonth(),nowDate.getDate()-3) ,
pointInterval: 24 * 36e5 //一天
}
},
series: [{}]
}
var url = "/Home/GetJsonResult";
$.getJSON(url, function(data) {
option.series = data;
$('#container').highcharts(option);
});
});

Categories

Resources