javascriptserilizer not serializing properly - web-services

i have a webservice whih has only one method in it
[WebMethod]
public string GetMovies()
{
using (var dataContext = new MovieCollectionDataContext())
{
var query = dataContext.Movies.Select(m =>new{m.Title,m.ReleaseDate}).Take(20);
var serializer = new JavaScriptSerializer();
return serializer.Serialize(query);
}
}
it serilize the object but when i get the result in firebug it look like this
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">[{"Title":"SQL","ReleaseDate":"\/Date(1224007200000)\/"},{"Title":"Termonator Salvation","ReleaseDate":"\/Date(1224007200000)\/"}]</string>
iam using Kendo and my jquery method is
var dataSource = new kendo.data.DataSource(
{
transport: {
read: {
type: "POST",
dataType: "json",
url: "/MovieService.asmx/GetMovies"
//contentType: "application/json; charset=utf-8",
}
},
change: function (e) {
alert(e);
},
error: function (e) {
alert(e[2]);
},
pageSize: 10,
schema: {
data: "d"
}
in the above jquery there is an error even when it calls i got this error
SyntaxError: JSON.parse: unexpected character
please help me to get the proper JSON plz i really neeed proper JSON to do my work

What exactly are you trying to parse? The whole response won't parse because it's XML, not json. If you are trying to parse just the value of the string element then you probably need to wrap it in quotes.
Update:
JSON.parse('[{"Title":"SQL","ReleaseDate":"\/Date(1224007200000)\/"},{"Title":"Termonator Salvation","ReleaseDate":"\/Date(1224007200000)\/"}]')

This blog post shows how to return JSON from an ASMX service: http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
And here is a running project showing how to bind a Kendo Grid to an ASMX service: https://github.com/telerik/kendo-examples-asp-net/tree/master/grid-web-service-crud

Related

How to set the request body via Postman's pre-request script?

I use Postman 6.0 to send an HTTP request. To send a request, I use a pre-request script to get a token and put it into the environment so that it will be used in the succeeding requests.
The script below doesn't work because the body is not sent. Is there anything wrong with the script below?
const getTaxAccessToken={
url: 'http://dev.xxx.com:4001/api/v1/portal/account/tax-login',
method: "post",
body: {
'loginIdentity': 'admic',
'password': 'abc123'
},
header: {
'Content-Type': 'application/json'
}
};
pm.sendRequest(getTaxAccessToken, function (err, response) {
console.log("get accesstoken");
console.log(response.access_Token);
pm.environment.set("taxAccessToken", response.access_Token);
});
If the request needs to be of type application/x-www-form-urlencoded:
const options = {
url: 'http://some/url',
method: 'POST',
header: {
'Accept': '*/*',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
mode: 'urlencoded',
urlencoded : [
{ key: 'loginIdentity', value: 'admic'},
{ key: 'password', value: 'abc123'},
]
}
};
pm.sendRequest(options, function (err, res) {
// Use the err and res
// ...
pm.environment.set("my-token", res.json().access_token);
});
Postman Javascript API references:
Request
RequestBody
Try this.
body: {
mode: 'raw',
raw: JSON.stringify({'loginIdentity': 'admic', 'password': 'abc123'})
}
For Postman > v8.3.0
With Postman v8.3.0 the update() method was introduced which allows you to set the request body directly from the pre-request script.
For your use case you could simply use:
pm.request.body.update({
mode: 'raw',
raw: JSON.stringify({'loginIdentity': 'admic', 'password': 'abc123'})
});
or even shorter:
pm.request.body.update(JSON.stringify({'loginIdentity': 'admic', 'password': 'abc123'}));
Strings, form-data, urlencoded and other Content-Types
As the title is not specifically tailored to JSON request bodies I thought I'd add some examples for how to handle this for other data as many might find this page when searching on Google and run into this issue for other Content-Types.
Raw
raw in Postman expects a string and therefore you can transmit anything that can be expressed as a string e.g. plain text, HTML, XML, JSON etc. .
// plain text
pm.request.body.update(`Hello World!`);
// HTML
pm.request.body.update(`<html>...</html>`);
// XML
pm.request.body.update(`<xml>...</xml>`);
// JSON
pm.request.body.update(JSON.stringify({ key: `value` }));
URL-encoded
pm.request.body.update({
mode: "urlencoded",
urlencoded: [{
key: "key",
value: "value with spaces and special chars ?/ and umlaute öüä"
}]
});
Form data
pm.request.body.update({
mode: "formdata",
formdata: [{
key: "key",
value: "value with spaces and special chars ?/ and umlaute öüä"
}]
});
GraphQL
pm.request.body.update({
mode: 'graphql',
graphql: {
query: `
query {
hero {
name
friends {
name
}
}
}`
}
});
Example based on GraphQL Tutorial for Fields.
Files from local file system as form-data
pm.request.body.update({
mode: "formdata",
formdata: [
{
key: "file", // does not need to be "file"
type: "file", // MUST be "file"
src: "/C:/Users/MyUser/Documents/myFile.zip"
}
]
})
Please note: This will only work for files in your current working directory. Otherwise you will receive an error like this Form param 'file', file load error: PPERM: insecure file access outside working directory in the Postman console.
You can see where your working directory is when you go to Settings | General | Working Directory. There also is an option Allow reading files outside working directory which you can enable to read files from anywhere, but be aware that this can allow others to steal data from your computer e.g when you execute untrusted collections.

calling datasnap webservice from javascript into variable

I have created a Datasnap REST server.
A ReverseString method gets created by default that simply reverses the string passed to the method.
When I invoke the method using the browser URL:
http://dummydomain.com:81/datasnap/rest/TServerMethods1/ReverseString/ABC
I receive {"result":["CBA"]} as result. (server runs on port 81 and the parameter passed to the method is ABC)
I have tried the following code to get the result into a variable in javascript, but without success:
var options={
type: "GET",
url: "http://dummydomain.com:81/datasnap/rest/TServerMethods1/SayHello",
data: "ABC",
dataType: "json",
success: function(data) {
var json = JSON.stringify(data);
$("p").after('<div id="data1">Your result is: ' + json.result + '</div>');
}
}
$.ajax(options);
What am I doing wrong? In the end I need 'CBA' in a variable. If there are some good resources out there, please advise. I have been googling but everybody seem to do it in their own way.

webservice call keeps returning json

I'm just trying to test a very simple ajax call to a simple webservice. I'm using .net 4, iis 6. My webservice code looks like this...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
namespace ABCNamespace {
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
return new JavaScriptSerializer().Serialize("Hello World");
}
}
}
My call looks like this
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../../MyService.asmx/HelloWord",
data: "{}",
dataType: "json",
success: function () { alert('done'); },
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
I'm keep getting 500 error and after taking a closer look, I'm getting a string back instead of json data. I think if correct this, it will fix my issue. However, I can't get it to return json data.
Here is a response check by invoking my webmethod
<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://tempuri.org/"> "Hello World" </string>
Note: please ignore the fact that I'm using ../../ in my url instead of resolveURL. This is just for quick simple testing purposes. I also play around with the web.config handlers and no luck. Not sure what I miss...

call ASP.net 1.1 service in asp.net using Jquery

I am trying to call ASP.net 1.1 service in asp.net using Jquery, can't figure put what I am doing wrong here, Pleaseeeee help
Javascript Method
function YesCheckChanged(vSRID) {
var para = {
SRID: vSRID
};
jQuery.ajax({
type: "POST",
url: serviceUrl + "/YesRdoClicked",
dataType: "xml",
data: para,
contentType: "application/xml; charset=utf-8",
success: function(data, status) {
alert(data);
edata = $(data).find("string").text();
alert(edata);
},
error: function(e, status) {
alert(status);
}
});
}​
Error
System.InvalidOperationException: Request format is invalid:
application/xml; charset=utf-8.
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
Service method Code
[WebMethod(true)]
public string YesRdoClicked(int SRID)
{
clsEntity obj = new clsEntity();
obj.New_DeleteTempEntity(SRID);
return "yes";
}
http://www.codeproject.com/Articles/1231/ASP-NET-Web-Service
I finally resorted to native Activex calls as no other way seem to work for me. Personally I wanted to avoid using it. But It works well.
A word of caution here, activeX are not very well supported in browsers other than IE so you need to either have IE Only application or convince the client to upgrade to higher version of asp.net.

Mobile Application Using Sencha Touch - JSON Request Generates Syntax Error

I started playing a bit with Sencha Touch.
So I've built a really simple application based on one of the examples just to see how it goes.
Basically it creates a JSON Request which executes a Last.FM web service to get music events near the user's location.
Here's the JSON code:
var makeJSONPRequest = function() {
Ext.util.JSONP.request({
url: 'http://ws.audioscrobbler.com/2.0/',
params: {
method: 'geo.getEvents',
location: 'São+Paulo+-+SP',
format: 'json',
callback: 'callback',
api_key: 'b25b959554ed76058ac220b7b2e0a026'
},
callback: function(result) {
var events = result.data.events;
if (events) {
var html = tpl.applyTemplate(events);
Ext.getCmp('content').update(html);
}
else {
alert('There was an error retrieving the events.');
}
Ext.getCmp('status').setTitle('Events in Sao Paulo, SP');
}
})
};
But every time I try to run it, I get the following exception:
Uncaught SyntaxError: Unexpected token :
Anyone has a clue?
A couple of things. First of all the "Uncaught SyntaxError: Unexpected token :" means the browser javascript engine is complaining about a colon ":" that has been put in the wrong place.
The problem will most likely be in the returned JSON. Since whatever the server returns will be run though the eval("{JSON HTTP RESULT}") function in javascript, the most likely thing is that your problem is in there somewhere.
I've put your code on a little sencha test harness and found a couple of problems with it.
First: My browser was not too happy with the "squiggly ã" in location: 'São+Paulo+-+SP', so I had to change this to location: 'Sao+Paulo,+Brazil', which worked and returned the correct results from the audioscribbler API.
Second: I notice you added a callback: 'callback', line to your request parameters, which changes the nature of the HTTP result and returns the JSON as follows:
callback({ // a function call "callback(" gets added here
"events":{
"event":[
{
"id":"1713341",
"title":"Skank",
"artists":{
"artist":"Skank",
"headliner":"Skank"
},
// blah blah more stuff
"#attr":{
"location":"Sao Paulo, Brazil",
"page":"1",
"totalpages":"1",
"total":"2"
}
}
}) // the object gets wrapped with extra parenthesis here
Instead of doing that I think you should be using the callbackKey: 'callback' that comes with the example in http://dev.sencha.com/deploy/touch/examples/ajax/index.js.
Something like this for example:
Ext.util.JSONP.request({
url: 'http://ws.audioscrobbler.com/2.0/',
params: {
method: 'geo.getEvents',
location: 'Sao+Paulo,+Brazil',
format: 'json',
api_key: 'b25b959554ed76058ac220b7b2e0a026'
},
callbackKey: 'callback',
callback: function(result) {
// Output result to console (Firebug/Chrome/Safari)
console.log(result);
// Handle error logic
if (result.error) {
alert(result.error)
return;
}
// Continue your code
var events = result.data.events;
// ...
}
});
That worked for me so hopefully it'll work for you too. Cherio.