Pass JSON from SQL Server to D3 Javascript - javascript

I'm building an ASP.NET using C#, Visual Studio, SQL Server, D3.JS.
I have values in a SQL Server that I'm getting from the database and the results are:
[
{"AMOUNT":1.000000000000000e+002},{"AMOUNT":1.000000000000000e+003},
{"AMOUNT":1.000000000000000e+004},{"AMOUNT":5.000000000000000e+003}, {"AMOUNT":2.000000000000000e+003},{"AMOUNT":1.000000000000000e+003},
{"AMOUNT":5.000000000000000e+003},{"AMOUNT":3.000000000000000e+003},{"AMOUNT":8.000000000000000e+003},{"AMOUNT":1.200000000000000e+004},
{"AMOUNT":5.000000000000000e+003},{"AMOUNT":1.300000000000000e+004},
{"AMOUNT":1.500000000000000e+004}
]
Okay so my Json output is correct, below is code I'm using to get the json output above:
public string jsonString = "";
public string JasonGet()
{
var queryWithForJson = "SELECT AMOUNT FROM PeopleTable WHERE Bal = 'Acc' FOR JSON AUTO";
var conn = new SqlConnection(#"MyConnectSource!");
var cmd = new SqlCommand(queryWithForJson, conn);
conn.Open();
var jsonResult = new StringBuilder();
var reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0).ToString());
}
}
Label1.Text = jsonResult.ToString();
// jsonString = (new JavaScriptSerializer()).Serialize(jsonResult);
return (new JavaScriptSerializer()).Serialize(jsonResult);
}
And this works fine above I believe since I am putting the results on a label1.Text from a jsonString to see it for myself but the last return line is where I'm part confused because now I wish to pass the JSON result to my D3.JS. Let me show what I'm doing in D3...
<script>
d3.json('<%= JasonGet() %>').then(function (data) {
console.log("Json string: " + data);
});
</script>
Okay so I believe in my C# function that I have the correct results but I think the error is when I'm passing the values to my Javascript. Below is the error code I'm getting:
Uncaught SyntaxError: Unexpected end of JSON input
and
Failed to load resource: the server responded with a status of 400 (Bad Request)
I appreciate any suggestions, sorry if it's not explained properly but to sum it up, we are getting json values from the database from a C# function and then want to pass it into Javascript.

Related

Convert JSON response to Google Sheet ( Google Apps Script)

I have been trying to figure out to insert the JSON response into google Sheet in Google Apps Script with below code but for some reason I am getting error while trying to run.
please see screenshot and below code.
function myFunction() {
var key_67 = 'YYYYYYYYYYYYYYYYYY';
var ss_67 = SpreadsheetApp.openById(key_67);
var sheet_67 = ss_67.getActiveSheet();
sheet_67.getRange('A1:AZ10000').clearContent();
var url = 'https://creator.zoho.com/api/json/arfater/view/Leads_Report?authtoken=XXXXXXXXXXXXXXXXXXXX&scope=creatorapi&zc_ownername=ipekuet';
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
var stats=[]; //create empty array to hold data points
//The following lines push the parsed json into empty stats array
stats.push(data.Yearly_Sales); //temp
stats.push(data.Email); //dewPoint
stats.push(data.Phone); //visibility
//append the stats array to the active sheet
sheet_67.appendRow(stats)
}
So your JSON response based on postman app is
var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test#zoho.com","Phone":"123-032-03323","P‌otentially":50,"Stat‌e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]};
When I use that response as is:
function JsonResponse(){
var json ='var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test#zoho.com","Phone":"123-032-03323","P‌​otentially":50,"Stat‌​e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]} '
var data = JSON.parse(json);
Logger.log(data);
}
I get the same error as you:
SyntaxError: Unexpected token: v
Which leads me to believe your response from API has this term var zohoipekuetview65 (Not really sure as to why? a bug perhaps)
The below code splits the response string to give you the JSON response only
function trialParse(){
var json ='var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"test#zoho.com","Phone":"123-032-03323","P‌​otentially":50,"Stat‌​e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]} '
Logger.log(JsonResponse(json))
}
function JsonResponse(response){
Logger.log(response)
var json = response.split("=")[1]
var data = JSON.parse(json);
Logger.log(data);
return data
}
Just call the above function in your code using var data = JsonResponse(json)
Final Note: As mentioned by Jordan Rhea you can use Logger.log(json) to output the response to your logs. To view your logs goto Views>Logs, it will show you the response you receive from Api.

AngularJS Services call .asmx webservice - TypeError: Cannot convert object to primitive value

I am very sorry to ask this question. I am very sorry if my question is not clear. I am trying to call .asmx webservice from my AngularJS Services.
In my AngularJS Services, I have the following code snippet:
.factory('BoothDesignatedCoordsService', ['$http',function ($http) {
return {
// Might retrieved from db eventually
fnGetBoothDesignatedCoords: function (strBoothName, intFloorPlanID) {
try
{
var JSONObj = {
BoothName: strBoothName,
FloorPlanID: intFloorPlanID
};
var sendToWS = JSON.stringify(JSONObj)
}
catch(e)
{
alert("error from fnGetBoothDesignatedCoords " + e)
}
$http.post('http://localhost:4951/wsIPS.asmx?op=fnGetBoothDesignatedCoords', sendToWS).then(function (response) {
if (response.data)
alert("Post Data Submitted Successfully!");
}, function (response) {
alert("Service not Exists");
alert(response.status);
alert(response.statusText);
alert(response.headers());
});
}
}
}])
In my .asmx file, I have the following code snippet:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true)]
public void fnGetBoothDesignatedCoords(string objJSONRequest)
{
wsIPS objRequest = JsonConvert.DeserializeObject<wsIPS>(objJSONRequest);
string strBoothName = objRequest.ClientBoothName;
string strFloorPlanID = objRequest.ClientFloorPlanID;
int intFloorPlanID = int.Parse(strFloorPlanID.ToString());
double[] arrBoothDesignatedCoords = new double[0];
string strConnectionString = ConfigurationManager.ConnectionStrings["IPSConnection"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT DesignatedCoords FROM Booth WHERE Name = #Name AND FloorPlanID = #FloorPlanID";
SqlCommand selectCmd = new SqlCommand(strCommandText, myConnect);
selectCmd.Parameters.AddWithValue("#Name", strBoothName);
selectCmd.Parameters.AddWithValue("#FloorPlanID", intFloorPlanID);
myConnect.Open();
SqlDataReader reader = selectCmd.ExecuteReader();
if (reader.Read())
{
string strBoothDesignatedCoords = reader["DesignatedCoords"].ToString();
arrBoothDesignatedCoords = Array.ConvertAll(strBoothDesignatedCoords.Split(','), double.Parse);
}
myConnect.Close();
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(arrBoothDesignatedCoords));
}
}
}
Note : my .asmx web service is running, so I can use the url to access it directly on my local computer.
However, I receive alert error that say "service not exists", and the error code is 500, and it is internal server error. And the console log gives me this error: TypeError: Cannot convert object to primitive value. Can someone please help me?
This is the screenshot of my .asmx webservice and its url:

MobileFirst POST javascript array to java array

I have an array in javascript that I am trying to pass to my mobilefirst java adapter. I call my adapter like so,
myArr = [1,2,3];
var sendPost = new WLResourceRequest(
"/adapters/MyAdpater/path",
WLResourceRequest.POST
);
var formParam = {"arr":myArr};
sendTicketPost.sendFormParameters(formParams);
Then in my adapter I can have my method and get the param
public JSONObject postAdapterFx(#FormParam("arr") List<Integer> myArray) {}
Currently when I send this I just get a 400 error and it is because the adapter doesnt like the form param as that type, so what else could I set myArray to in the adapter? I can send it as a string and then convert the string to a List<Integer> in the java but that is really messy and I would like to avoid doing that.
So how can I pass this array?
Thanks for the help
you can do it in body with request.send(yourArray). Then you can read it in Java with buffer.
Example from knowledge center
var request = WLResourceRequest(url, method, timeout);
request.send(json).then(
function(response) {
// success flow
},
function(error) {
// fail flow
}
);
You will need to take an extra step before sending the form data to the adapter. sendFormParameters only accepts objects with simple values i.e., string, integer, and boolean; in your case arr is an array.
Create a utility function that will encode the form data, you can use the following:
function encodeFormData(data) {
var encoded = '';
for(var key in data) {
var value = data[key];
if(value instanceof Array) {
encoded += encodeURI(key+'='+value.join('&'+key+'='));
} else {
encoded += encodeURI(key+'='+value);
}
encoded += '&';
}
return encoded.slice(0, -1);
}
Then you will need to update your code as follows:
var myArr = [9,2,3];
var sendPost = new WLResourceRequest("/adapters/Cool/users/cool", WLResourceRequest.POST);
var formParam = {"arr" : myArr};
sendPost.sendFormParameters(encodeFormData(formParam));

WebApi read exsisting JSON file - C#

I am trying to create a webapi that reads an exsisting JSON file and then returns it as json object so i can use Javascript to populate the data as HTML to this site. http://pptlbhweb.azurewebsites.net/
The JSON file gets updated as i have a temperaturelogger that logs the events to an eventhub - Streamanalytics - saves as JSON in blob storage (Azure)
Here is the JSON file: https://pptlbhstorage.blob.core.windows.net/temperature/0_7622a22009224c78a46c0b2bc0a3fd82_1.json
If you look on the JSON file it needs to append "]" at the end (This is what i think) in this way i can get a valid JSON object that the WebApi returns.
I have already created a WebApi so i can use URL to get data. http://pptlbhwebapi.azurewebsites.net/api/test
Something similar for getting temperature would be for example:
http://pptlbhwebapi.azurewebsites.net/api/temperature
The fix:
Add this to your api controller:
[System.Web.Http.Route("api/readandreturnjson")]
[System.Web.Http.HttpGet]
public async Task<IHttpActionResult> ReadAndReturnJsonAsync()
{
// object to return through the API (it'll be serialized by WebAPI)
object obj = null;
// WebClient used to download the JSON file
using (var wc = new WebClient())
{
var url =
"https://pptlbhstorage.blob.core.windows.net/temperature/0_7622a22009224c78a46c0b2bc0a3fd82_1.json";
// Used to hold and add a ']' to the downloaded JSON
StringBuilder builder = new StringBuilder();
builder.Append(await wc.DownloadStringTaskAsync(url));
builder.Append("]");
// Deserialize the now valid JSON into obj
obj = JsonConvert.DeserializeObject(builder.ToString());
}
// return the json with 200 Http status.
return Ok(obj);
}
In Global.assax:
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configu‌​ration.Formatters.XmlFormatter);
You could do this:
[System.Web.Http.Route("api/readandreturnjson")]
[System.Web.Http.HttpGet]
public async Task<IHttpActionResult> ReadAndReturnJsonAsync()
{
// object to return through the API (it'll be serialized by WebAPI)
object obj = null;
// WebClient used to download the JSON file
using (var wc = new WebClient())
{
var url =
"https://pptlbhstorage.blob.core.windows.net/temperature/0_7622a22009224c78a46c0b2bc0a3fd82_1.json";
// Used to hold and add a ']' to the downloaded JSON
StringBuilder builder = new StringBuilder();
builder.Append(await wc.DownloadStringTaskAsync(url));
builder.Append("]");
// Deserialize the now valid JSON into obj
obj = JsonConvert.DeserializeObject(builder.ToString());
}
// return the json with 200 Http status.
return Ok(obj);
}

Internal server error 500 in backbone

while saving form details using backbone i m getting error as
POST http://localhost:8080/gamingengine/restful-services/badges 500 (Internal Server Error)
st.ajaxTransport.sendjquery.js:4
st.extend.ajaxjquery.js:4
Backbone.ajaxbackbone.js:1197
Backbone.syncbackbone.js:1178
_.extend.syncbackbone.js:284
_.extend.savebackbone.js:490
Backbone.Form.extend.saveBadgesbadges.js:219
st.event.dispatchjquery.js:3
st.event.add.y.handle
Uncaught SyntaxError: Unexpected token <
st.extend.parseJSONjquery.js:2
window.clearErrorscommon.js:386
st.event.dispatchjquery.js:3
st.event.add.y.handlejquery.js:3
st.event.triggerjquery.js:3
rjquery.js:4
st.ajaxTransport.send.r
my backbone code is as follows
this.model.save(this.getValue(), {
//beforeSend : setHeader, //added
iframe : true,
wait : true,
files : $file,
elem : this,
data : _.omit(this.getValue(), ['iconFile']),
silent : true,
success : function(model, response, options) {
alert("inside save..");
var error = false;
_.each(response, function(val, key) {
if (app.BadgesView.fields[key]
&& val instanceof Object
&& val.error) {
error = true;
app.BadgesView.fields[key]
.setError(val.message);
}
});
if (!error) {
app.BadgesView.model.set(model);
app.BadgesListCollection.add(model);
return;
}
return false;
},
error : function(model, response, options) {
console.log("error while save in badges.js : ");
}
});
and server side code is as follows which is using resteasy
#POST
#Consumes("multipart/form-data")
#Produces("text/html")
#Cache(noStore = true)
public final Response saveBadges(
#MultipartForm final BadgesForm badgesForm) throws IOException {
System.out.println("saveBadges called........");
final int no_of_coins = badgesForm.getNo_of_coins();
final String badge_name = badgesForm.getBadge_name();
final int score = badgesForm.getScore();
final int badge_id = badgesForm.getBadge_id();
final byte[] iconFile = badgesForm.getIconFile();
final Validator validatorNumeric = ValidationFactory
.getTextFieldNumericValidator();
validatorNumeric.validate("no_of_coins", no_of_coins,
threadlocalExceptions.get());
System.out.println("iconFile :" + iconFile);
if (iconFile.length >= GamingConstants.ONE) {
ValidationFactory.getImageContentValidator().validate("iconFile",
iconFile, threadlocalExceptions.get());
ValidationFactory.getImageSizeValidator().validate("iconFile",
iconFile, // added size // validator
threadlocalExceptions.get());
}
if (threadlocalExceptions.get().isEmpty()) {
try {
final Badges badges = new Badges();
badges.setNo_of_coins(no_of_coins);
badges.setBadge_name(badge_name);
badges.setScore(score);
badges.setBadge_id(badge_id);
final Coin coin = new Coin();
coin.setId(badgesForm.getCoin());
badges.setCoin(coin);
Badges.save(badges);
final Badges badgesObj = new Badges();
badgesObj.setBadge_id(badges.getBadge_id());
badgesObj.setCoin(coin);
badgesObj.setBadge_name(badges.getBadge_name());
badgesObj.setNo_of_coins(badges.getNo_of_coins());
badgesObj.setScore(badges.getScore());
if (iconFile.length >= GamingConstants.ONE) {
final String imgPath = "restful-services/badges/"
+ badges.getBadge_id() + "/image";
badgesObj.setIconPath(imgPath);
final String fileName = path + badges.getBadge_id()
+ ".png";
CommonUtils.writeIcon(iconFile, fileName);
} else {
badgesObj.setIconPath(defaultPath);
}
Badges.update(badgesForm.getBadge_id(), badgesObj);
final gamingengine.bind.Badges bindBadges = new gamingengine.bind.Badges();
bindBadges.setBadge_id(badgesObj.getBadge_id());
bindBadges.setCoin(badgesObj.getCoin());
bindBadges.setNo_of_coins(badgesObj.getNo_of_coins());
bindBadges.setBadge_name(badgesObj.getBadge_name());
bindBadges.setIconPath(badgesObj.getIconPath());
bindBadges.setScore(badgesObj.getScore());
final ObjectMapper mapper = new ObjectMapper();
final String jsonString = mapper.writeValueAsString(bindBadges);
return Response.ok().entity(jsonString).build();
} catch (DBException e) {
if (e.getMessage().startsWith(DBException.PARENT_NOT_EXISTS)) {
final String fieldName = e.getMessage()
.substring(e.getMessage().indexOf("-") + 1).trim()
.toLowerCase();
e.getValidationException()
.setMessage(
"The "
+ fieldName
+ " is already deleted.Please refresh the page ");
threadlocalExceptions.get().put(fieldName,
e.getValidationException());
}
}
}
final Map<String, ValidationException> exceptions = threadlocalExceptions.get();
threadlocalExceptions.remove();
final ObjectMapper mapper = new ObjectMapper();
final String exceptionJsonString = mapper
.writeValueAsString(exceptions);
return Response.ok().entity(exceptionJsonString).build();
}
while saving data of the form, backbone does not call the saveBadges() method of server side code
in chrome network it shows as
badges
/gamingengine/restful-services
POST
500
Internal Server Error
text/html
now i tried as
data:this.getvalue() in save() its sending all values to server except for iconPath
**iconPath : {
type : "FilePicker",
title : "Icon"
}**
and in save() of backbone
**var $file = $('input[name="iconPath"]', this.el);** this two lines are not sending iconPath, its empty any guesses
any help appreciated!!! thanks
The issue could be related to the content-type expected by your service, "multipart/form-data". Backbone by default does not provide an implementation to send a multipart request on the "save" method.
Here is a link with information about how you can send the multipart-request:
multipart form save as attributes in backbonejs
Also, message that you are receiving about the unexpected character ">" could be related to the "dataType" associated to the request, try to change it to "text" to avoid parsing to JSON, adding that you should be getting the correct error.
this.model.save(this.getValue(), {
//beforeSend : setHeader, //added
iframe : true,
wait : true,
files : $file,
dataType: "text",
elem : this,
data : _.omit(this.getValue(), ['iconFile']),
silent : true..
}
I will suggest to review your developer console as well in Chrome, Safari or Firefox to see how the request is been sent to the server, that could give you a better understanding how your request is been received by the server.
Also, try testing your service by external "Restful" tool, chrome provided the "Advance Restful Client" where you can test your service.
Hope this information helps to solve your issue or guide you in the right direction.

Categories