Google chart is not loading in asp.net using JSON - asp.net

I am trying to visualize data using google charts.But the chart is not displaying.I want to display data which is retrieved from sqlserver database
here is my code.
<div id="chart_div" style="width:500px;height:400px">
<%-- Here Chart Will Load --%>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var jdata = $.ajax({
url: "GetData.aspx",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jData);
var options = {
title: 'Chess opening moves',
width: 900,
legend: { position: 'none' },
chart: {
title: 'Chess opening moves',
subtitle: 'popularity by percentage'
},
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'amount' } // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, options);
};
</script>
</div>
GetData.aspx
public partial class GetData : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string arr = JsonConvert.SerializeObject(get(), Formatting.None,
new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
Response.Write(arr);
}
private object get()
{
List<object> ls = new List<object>();
SqlConnection con = new SqlConnection("Data Source=dell-pc;Initial Catalog=hospital;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select top(5) p_id, amount from payments", con);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
ls.Add(dr);
}
return ls;
}
}
The JsonArray loads as follows.
[{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT1",7000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT2",35000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT8",95000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT10",51000.0000],"HasErrors":false},{"RowError":"","RowState":2,"Table":[{"p_id":"PT1","amount":7000.0000},{"p_id":"PT2","amount":35000.0000},{"p_id":"PT8","amount":95000.0000},{"p_id":"PT10","amount":51000.0000},{"p_id":"PT3","amount":1200.0000}],"ItemArray":["PT3",1200.0000],"HasErrors":false}]
I think there is something wrong when json is loading. please help

The main reason here that you fail to load json data is probably because you use a full aspx page GetData.aspx (and there you send wrong header, content type)
Change that to a handler, make a new handler not just rename the page, something like getdata.ashx and place there your code.
Be sure to send the correct content type context.Response.ContentType, and check that you send only the correct json data
the answers here can help : ASP.NET Returning JSON with ASHX

Related

How can I know the type of change happened to the database using SQL Dependency

I have the following code which displays live data using SignalR. The table gets updated instantly using SignalR once a row is inserted, updated, or deleted. However, I would like to know in particular the type of change that happened to the database (whether it's an update, delete, or insert). I understand that the onchange() method detects changes on the database, but how can I determine what type of change it is?
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionCustomer"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [Id],[CustomerName] FROM [CustomerInfoes] ", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
SqlDataReader reader = command.ExecuteReader();
var listCus = reader.Cast<IDataRecord>()
.Select(x => new
{
Id = (int)x["Id"],
CustomerName = (string)x["CustomerName"],
}).ToList();
return Json(new { listCus = listCus }, JsonRequestBehavior.AllowGet);
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
CustomerHub.Show();
}
Hub:
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<CustomerHub>();
context.Clients.All.displayCustomer();
}
View
<script src="~/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var cus = $.connection.customerHub;
// Declare a function on the job hub so the server can invoke it
cus.client.displayCustomer = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblInfo');
$.ajax({
url: $("#Get").val(),
type: 'GET',
datatype: 'json',
success: function (data) {
$tbl.empty();
$.each(data.listCus, function (i, model) {
$tbl.append
(
'<tr>' +
'<td>' + model.Id + '</td>' +
'<td>' + model.CustomerName + '</td>' +
'<tr>'
);
});
}
});
}</script>
You can easily find out the change type by looking at eventArgs.Info property.

signalR - how to show realtime chart

finally I know how to call the method in the server and the client will refresh the chart. if you update data on table, the chart will adjust automatically. the code as below:
this is my html code:
<div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="Scripts/jquery.signalR-2.2.1.min.js"></script>
<script src="../signalR/hubs"></script>
<script type="text/javascript">
$(function () {
//proxy created on the fly
var job = $.connection.statisticsHub;
//declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
//start the connection
$.connection.hub.start()
.done(function () {
console.log('now connected');
//execute function in client from server
job.server.show();
})
.fail(function (error) {
console.log('error nih: ' + error);
});
});
function getData() {
//alert("from getData");
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var options = {
title: 'USA City Distribution'
};
$.ajax({
type: "POST",
url: "Default.aspx/GetChartData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r.d);
var chart = new google.visualization.PieChart($("#chart")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
}
</script>
<div id="chart" style="width: 900px; height: 500px;">
</div>
this is Hub:
using Microsoft.AspNet.SignalR;
namespace TutorialGooglePieChart
{
public class StatisticsHub : Hub
{
public void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<StatisticsHub>();
context.Clients.All.displayStatus();
}
}
}
this is my cs file:
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
namespace TutorialGooglePieChart
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<object> GetChartData()
{
string query = "SELECT Name, Quantity FROM [dbo].[Products]";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
List<object> chartData = new List<object>();
chartData.Add(new object[]
{
"Name", "Quantity"
});
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Notification = null;
SqlDependency.Start(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
chartData.Add(new object[]
{
sdr["Name"], sdr["Quantity"]
});
}
}
con.Close();
return chartData;
}
}
}
private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
StatisticsHub myHub = new StatisticsHub();
myHub.Show();
}
}
}
}
thank you for your help
Without testing it, the java script looks okay.
Your method needs to be updated, remove static from your method, not positive but I think that is where your main problem is. Comment out the IHubContext as I don't believe it is needed since you are within the hub. I think that is for calling methods (in your hub) from other classes.
Also, changing Clients.All to Clients.Caller. It would not make sense to update everyone's chart when anyone connects. Rather only the calling client.
Try changing to this:
using Microsoft.AspNet.SignalR;
namespace TutorialGooglePieChart
{
public class StatisticsHub : Hub
{
public void Show()
{
//IHubContext context = GlobalHost.ConnectionManager.GetHubContext<StatisticsHub>();
//context.Clients.All.displayStatus();
context.Clients.Caller.displayStatus();
}
}
}

Signalr and Devexpress

I want to create a grid and automatic update it, when data changes in the database. It works with a simple table control.
public partial class index : System.Web.UI.Page
{
static string connectionString = #"Data Source=*******;initial catalog=Test;persist security info=True; Integrated Security=SSPI;";
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static IEnumerable<Person> GetData()
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [Id],[Name] FROM [dbo].[Persons]", connection))
{
command.Notification = null;
SqlDependency.Start(connectionString);
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(Dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new Person(x.GetInt32(0), x.GetString(1))).ToList();
}
}
}
private static void Dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
MyHub.Show();
}
public void FillGrid()
{
List<Person> persons = new List<Person>();
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [Id],[Name] FROM [dbo].[Persons]", connection))
{
if (connection.State == ConnectionState.Closed)
connection.Open();
using (SqlDataReader rdr = command.ExecuteReader())
{
while (rdr.Read())
{
var id = rdr.GetInt32(0);
var name = rdr.GetString(1);
persons.Add(new Person(id, name));
}
}
}
}
grid.DataSource = persons;
grid.DataBind();
}
}
public class MyHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.displayStatus();
}
}
And the apsx Page :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.6.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var job = $.connection.myHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData()
{
var $tbl = $('#tbl');
$.ajax({
url: '/index.aspx/GetData',
contentType: 'application/json;charset=utf-8',
datatype: 'json',
type: 'POST',
success: function (data) {
if (data.d.length > 0) {
var newdata = data.d;
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th></tr>');
var rows = [];
for (var i = 0; i < newdata.length; i++) {
rows.push(' <tr><td>' + newdata[i].Id + '</td><td>' + newdata[i].Name + '</td><td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="tbl"></table>
<dx:ASPxGridView ID="grid" runat="server"></dx:ASPxGridView>
</div>
</form>
</body>
</html>
However I want to use a Devepress Aspxgridview. The Devexpress Site states they don't support SignalR. However since the Javascript function is triggered when data changes in the database, is it possible somehow to force the client to get the data from the server? Force a postback and/or call the FillGrid method? ( To create the grid from js is not possible since the AspxgridView Control is much more complicated).
SOURCE: https://www.youtube.com/watch?v=30m-7wpmbrc
Although SignalR is not supported out of the box, it should be possible to manually notify the server side about the update using the existing API. You can send a callback to the server using the ASPxClientGridView.PerformCallback method, and handle the server side ASPxGridView.CustomCallback event to reload data from the SQL server.

Binding Lable from webmethod using ajax

Hi guyes i am trying to read data from webmethod and pass the value to my lable in aspx page. for this i take a use of Ajax and webmethod. my problem is when i am not able to bind data on success to my lable controle.
my .asmx page.
public static string str;
[WebMethod]
public string GetEmployeeDetail(string name)
{
str = name;
Get(str);
string daresult;
daresult = Get(str);
return daresult;
}
[WebMethod]
public string Get(string str)
{
List<string> rst = new List<string>();
using (SqlConnection con = new SqlConnection("..."))
{
using (SqlCommand cmd = new SqlCommand("select practice_short_name from PRACTICE_DETAIL where Practice_Name = '" + str + "'",con))
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
rst.Add(string.Format("{0}", dr["practice_short_name"]));
}
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return jSearializer.Serialize(rst);
}
}
}
and here is my ajax call function in aspx page.
function fun() {
var ddlpsn = document.getElementById("<%=ddlPSN.ClientID%>");
$(ddlpsn).change(function () {
var s = $(this).val();
$.ajax({
type: 'POST',
url: 'AutoCompleteService.asmx/GetEmployeeDetail',
data: '{name: "' + s + '" }',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//i think i need to do some changes in here but not getting what to do.
$('#lblpriority').text(data.val);
},
error: function (error) {
console.log(error);
}
});
});
};
You need to change data.val to data.d. Data returned from WebMethod is contained in d property if you have not explicitly defined your own property for returned data.
$('#lblpriority').text(data.d);
You need to make your WebMethod static in order to called by ajax.

accessing data using ajax page methods directly

I want to access data and show in label ajax page methods but data is not displaying.
PageMethods.GetDataFromDB(OnSucceeded, OnFailed);
//}
function OnSucceeded(result, userContext, methodName) {
var jsonData = eval(result.d);
$get('Label1').innerHTML = jsonData.FirstName;
}
[WebMethod]
public static string GetDataFromDB()
{
System.Collections.Generic.Dictionary<string, string> DictionaryGetPerson = new Dictionary<string, string>();
using (OracleConnection con = new OracleConnection("server=xe; uid=system; pwd=;"))
{
string Command = "Select * from tblSavePerson"; //selecting Top 1 Row in Oracle
OracleCommand cmd = new OracleCommand(Command, con);
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DictionaryGetPerson.Add("FirstName",dr["FirstName"].ToString());
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(DictionaryGetPerson).ToString();
}
table has only one row.
Since you have given the tags as jQuery and jQuery Ajax I am deviating a little from the solution.
Do these things
1.Wrap your WebMethod in a try-catch block. try-catch are there for a reason.
[WebMethod]
public static string GetDataFromDB()
{
try
{
System.Collections.Generic.Dictionary<string, string> DictionaryGetPerson = new Dictionary<string, string>();
using (OracleConnection con = new OracleConnection("server=xe; uid=system; pwd=;"))
{
string Command = "Select * from tblSavePerson"; //selecting Top 1 Row in Oracle
OracleCommand cmd = new OracleCommand(Command, con);
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DictionaryGetPerson.Add("FirstName", dr["FirstName"].ToString());
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(DictionaryGetPerson).ToString();
}
catch (Exception exception)
{
//Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
throw new Exception(exception.Message);
}
}
Please note that this Dictionary will fail with Duplicate Key error if you have more than one row. If there are no errors lets move to step 2.
2.Do not use PageMethods.GetDataFromDB. It very ancient. Using jQuery one can consume ASP.NET Ajax Page Methods directly. Call Page method like this.
function LoadNames() {
$.ajax({
contentType: "application/json;",
data: "{}",
type: "POST",
url: 'Test1.aspx/GetDataFromDB',
success: function (msg) {
OnSucceeded(msg);
},
error: function (xhr, status, error) {
//alert("error");
//OnFailed(a, b, c);
}
});
}
function OnSucceeded(dict) {
var jsonData = dict.hasOwnProperty("d") ? dict.d : dict;
var json = $.parseJSON(jsonData);
alert(json.FirstName);
}
Also, don't eval(result.d) when we have $.parseJSON in jQuery.
Hope this helps.

Resources