Deserialization error only on remote IIS - json

When executing an ajax call to a WCF on my local IIS it works fine. The json object i send is the following:
var entity = {};
entity.LogicalName = "new_subsidiedossier";
entity.Id = "63772FDA-9B0A-E511-8270-005056B04A46";
entity.Attributes = [
{ key: "new_aantalurenperdeelnemer", value: { __type: "Decimal:http://schemas.microsoft.com/xrm/2011/Contracts", Value: 11.3 } }
];
With the exact same call i just change the url to our production server. It has the same version of the WCF but only on https. This fails with 'Bad Request' and the following description:
The server encountered an error processing the request. The exception message is 'There was an error deserializing the object of type TamSys.Integration.Contract.Models.UpdateRequest. Input string was not in a correct format.'. See server logs for more details. The exception stack trace is:
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver) at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName) at
Anyone experienced this before?
Regards

Related

Why is my HTTP response both 502 on my side but 401 on the server?

I am making an HTTP POST of a JSON from an Android app to my server (server code was not set by myself).
Most of the times this works correctly and I get a response of 200. However sometimes I get a 502 error code on the phone, but it logs as a 401 error code on the server.
The JSON is generated using unknown data from another source, however I have reviewed the JSON and it appears to be correct. The issue has only been seen when the JSON is particularly big.
Below is the code to set credentials and attach JSON to the HTTP post:
//set httpClient
httpClient = new DefaultHttpClient(httpParameters);
httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password"));
//create http post
HttpPost httpPost = new HttpPost(ServerURL);
//TODO SET THE JSON
try {
JSONObject thisObject = new JSONObject(query);
StringEntity se = new StringEntity(thisObject.toString());
httpPost.setEntity(se);
}
catch (JSONException ex)
{
longInfo("JSONException - JSON error" + ex.getMessage(), 0);
}
Why are the error codes different? Is it because the credentials are not verified by the server when it gets a 401 error?
Is there a common cause for this pairing of error codes which is known?
(NOTE the username and password are definitely correct as they are successful when sending small JSON file)

Bitcoind JSON-RPC : Java Jersey Client : Unexpected end of file from server Error

I am very new to bitcoin and this is my first experiment with bitcoind.
We have been trying to develop an Java based application on BTC using bitcoind (using testnet). We are using simple HTTP Post using Jersey client with basic authentication like given below. We already have jersey client as part of project dependencies. We are running on Mac OS. The bitcoind and java client are hosted in the same system.
Client client = Client.create();
String url = "http://"+username+':'+password+"#localhost:18333";
//String url = "http://localhost:18333";
System.out.println("URL is : "+url);
WebResource webResource = client.resource(url);
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (username, password.toCharArray());
}
});
String input = "{\"method\":\"getblockcount\",\"params\":[],\"id\":\"1\"}";
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
When we execute this, we are getting
Caused by: java.net.SocketException: Unexpected end of file from server
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:772)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:633)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:769)
From the exception what I understand is, there are some server side errors but i am not able to see errors in the log files. The degug.log does not give any details.
The entries in the bitcoin.conf file is as follows:
rpcuser=bitcoinrpc
rpcpassword=5UKQTzWTf7EEJnkShZhr9tbjpDVNmLMgQkFfWsnZhLey
testnet=1
server=1
Also I tried integrating with bitcoind using json-rpc client as well which resulted in the same error.
Really appreciate any help in resolving this error. Thank you in advance. Let me know if you need any further details.
Regards,
Manjunath
====== EDIT ======
When I inspect the request and response, its giving "Remote server closed the connection before sending response header" error as part of HTTP failure scenario. Following is the request data content :
URL : http://192.168.2.111:18333/
Request Data:
{
"method": "getblockcount",
"params": [],
"id": "1"
}
Please help me in understanding where the mistake is.
================ EDIT =================
Added below entries to bitcoin.conf to allow connections from client. But still facing the same error:
rpcallowip=192.168.2.111
rpcallowip=127.0.0.1
Regards,
Manjunath
After all tweaking, I am able to get it working properly. For the benefit of others, here is the Java Code for making JSON-RPC calls to bitcoind (Using Jersey Client):
bitcoin.conf entries :
rpcuser=bitcoinrpc
rpcpassword=5UKQTzWTf7EEJnkShZhr9tbjpDVNmLMgQkFfWsnZhLey
testnet=1
server=1
#txindex=1
rpcallowip=192.168.2.*
rpcallowip=127.0.0.1
rpcport=8999
#rpctimeout=60000
Make sure you change the port number and dont forget to provide rpcallowip entry pointing to respective IP address.
Client Code:
DefaultClientConfig config = new DefaultClientConfig();
config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING,
Boolean.TRUE);
Client client = Client.create(config);
client.addFilter(new HTTPBasicAuthFilter(username, password));
WebResource webResource = client.resource(url);
String input = "{\"id\":\"jsonrpc\",\"method\":\"listaccounts\",\"params\":[]}";
ClientResponse response = webResource.accept("application/json").type("application/json")
.post(ClientResponse.class, input);
Thats it. Your good to start with bitcoind integration.
Regards,
Manjunath

Uncaught SyntaxError: Unexpected token B on live but not local server

So i am making some ajax post and it seems to work fine on the localhost, but when I publish it to ec2 server on amazon, I get Uncaught SyntaxError: Unexpected token B. Which seems to point to JSON parsing failure. Exact same database, same browser, and same methods being called. Why would it work on local and not on the server.
$.ajax({
url: '#Url.Action("Action")',
type: "POST",
data: ko.toJSON(viewModel),
dataType: "json",
contentType: "application/json; charset:utf-8",
success: function (result) {
},
error: function (xhr, textStatus, errorThrown) {
var errorData = $.parseJSON(xhr.responseText);
var errorMessages = [];
for (var key in errorData)
{
errorMessages.push(errorData[key]);
}
toastr.error(errorMessages.join("<br />"), 'Uh oh');
}
});
Here is the basic layout on the server side:
[HttpPost]
public JsonResult Action(ViewModel model)
{
try
{
Response.StatusCode = (int)HttpStatusCode.OK;
return Json("Successfull");
}
catch (Exception ex)
{
logger.Log(LogLevel.Error, string.Format("{0} \n {1}", ex.Message, ex.StackTrace));
Response.StatusCode = (int)HttpStatusCode.BadRequest;
List<string> errors = new List<string>();
errors.Add(ex.Message);
return Json(errors);
}
}
Within the try statement, I do a couple of queries to the database and post some calculations on Authorize.Net (https://api.authorize.net/soap/v1/Service.asmx)
If there are any error with Authorize.net web service calls then I return errors like this:
if (profile.resultCode == MessageTypeEnum.Error)
{
logger.Log(LogLevel.Error, string.Join(",", profile.messages.Select(x => x.text)));
Response.StatusCode = (int)HttpStatusCode.BadRequest;
List<string> errors = new List<string>();
profile.messages.ToList().ForEach(x => errors.Add(x.text));
db.SaveChanges();
return Json(errors);
}
This error that I am logging:
A public action method 'AddPromoCode' was not found on controller 'Flazingo.Controllers.PositionController'. at
System.Web.Mvc.Controller.HandleUnknownAction(String actionName) at
System.Web.Mvc.Controller.ExecuteCore() at
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) at
System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.b__5() at
System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.b__0() at
System.Web.Mvc.MvcHandler.<>c__DisplayClasse.b__d() at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously)
You have another post at can't find action only on live server, works fine in local server, so I'm guessing that this post is specifically related to the javascript pieces, not the server-side pieces.
It sounds like something bad happens on the server, the server sends back some type of error, and the your error handler (in javascript) dies when trying to handle that response.
I get Uncaught SyntaxError: Unexpected token B. Which seems to point
to JSON parsing failure.
That sounds quite reasonable. Let's look at the code:
.ajax({
...
error: function (xhr, textStatus, errorThrown) {
var errorData = $.parseJSON(xhr.responseText);
var errorMessages = [];
...
},
...
});
I would highly recommend taking a look at what xhr.responseText is. My guess it that it does not contain valid JSON, so the parseJSON method throws the 'Unexpected token B' error.
To look at this value, you could put console.log(xhr.responseText); or you could use a tool like the javascript debugger in your web browser or fiddler to see what is there.
My guess is that the server is sending back a string with something like There was an error on the server instead of JSON like you are expecting. I see that you have error handling built in - my guess is that there is an error within your error handling, and there is nothing to catch it. I would recommend doing debugging on the server side to see if there is an error somewhere that you are not expecting.
Perhaps profile.messages is something that can only be enumerated once, and when you try to do it again it throws an error. Or maybe DB.SaveChanges is throwing an error for some reason. Either of these would result in the logged message that you see with the behavior you see on the client side.
You are attempting to return a 400 response (Bad Request) with your own custom response content.
I think that IIS by default doesn't allow you to do this, and as CodeThug mentioned, may be replacing your custom JSON content with a server message.
But it appears that you can override this behaviour:
http://develoq.net/2011/returning-a-body-content-with-400-http-status-code/
<system.webServer>
<httpErrors existingResponse="PassThrough"></httpErrors>
</system.webServer>
I have received similar mysterious errors in the past when using ASP.NET script bundling on knockout and bootstrap, especially when including the already-minified versions in a bundle.
If you are running in DEBUG mode on localhost, then ASP.NET will not be minifying the javascript libraries. However, once you deploy, you are presumably no longer in DEBUG mode and now minifying/bundling the scripts. Sometimes the bundling/minification of these scripts can result in syntax errors similar to the one you posted.
If so, you may be able to load knockout from a CDN to avoid the need for bundling.
It seems JSON sending as the response from the server is badly generated
ex: if a value in the database is hi "my" friends
JSON file will be generated as text:"hi "my" friends"
so value for property text is badly generated.
double check values in production/development server for such values.
best practice is replace quotes with escape character
ex: text:"hi \"my\" friends"

How to read the json response when a 422 (Unprocessable Entity) error occur in C# Visual Studio

I'm sending some JSON data to a web service using "PUT" method, but I'm having 422 unprocessable entity error. How can I actually see the server response in JSON? I digged deep into the exception but i still can't find the json response.
Ex:
JSON Request:
{
customer:
{
name: "asd",
address: "test"
}
}
and if everything was ok it should response to me some JSON data.
Ex:
{
customer:
{
id: 1,
name: "asd",
address: "test"
}
}
You can catch WebExpection and get Response from that and extract the correct error message:
Code :
catch (WebException ex)
{
using (var sr = new StreamReader(ex.Response.GetResponseStream()))
{
var data = sr.ReadToEnd();
throw new ApplicationException(data);
}
}
You could manually test this rest service with Fiddler.
422 HTTP error explanation: The request was well-formed but was unable to be followed due to semantic errors.
So check for example if JSON data you're sending is in the right format.
To answer your question: You cannot get a detailed answer in json specifying the syntax error than you have. It will be a manual trial and error process, to find the error.
As mentionned by user3470814, you should catch this kind of error and do something with it in your application.
And as mentionned by lucask, Fiddler will help you to see the exact string sent in your request.

Having issues with node.save service between drupal and appcelerator titanium

I am writing my first app using Appcelerator Titanium and I've hit a snag that I can seem to shake. Every other service I have used is working through the JSON server (node.get, view.get,system.connect) but I cannot for the life of me get a working solution of node.save. I've tried searching for people in my same boat and can't really find anything but I also cannot find a working solution anywhere.
I used the following blog post as a starting point:
http://civicactions.com/blog/2010/may/02/tutorial_code_developing_apps_iphoneipadandroid_using_drupal_base_system
I've tried both JSON and XMLRPC but I get no response with JSON and Access Denied with XMLRPC. If I plug my JSON into the services page through drupal admin it will create a node (not a CCK node but it worked with story) but going through the app I get nothing.
The following is my output trying with XMLRPC:
Node object -
[INFO] {
sessid = b03429453c85d4bf3d600dff6511f70f;
title = "This is a new node.";
type = story;
}
[INFO] xmlrpc: begin
[INFO] xmlrpc: url: http://mysite/services/xmlrpc
[INFO] xmlrpc: method: node.save
[INFO] xmlrpc: p: story
[INFO] xmlrpc: p: This is a new node.
[INFO] xmlrpc: p: b03429453c85d4bf3d600dff6511f70f
XML being sent -
[INFO] xmlrpc: xml: <methodCall><methodName>node.save</methodName><params><param><string>story</string></param><param><string>This is a new node.</string></param><param><string>b03429453c85d4bf3d600dff6511f70f</string></param></params></methodCall>
[INFO] xmlrpc: end
Response -
[INFO] Received: <?xml version="1.0"?>
<methodResponse>
<fault>
<value>
<struct>
<member>
<name>faultCode</name>
<value><int>401</int></value>
</member>
<member>
<name>faultString</name>
<value><string>Access denied</string></value>
</member>
</struct>
</value>
</fault>
</methodResponse>
Here is what I am getting with JSON:
[INFO] {"method":"node.save","type":"story","title":"This is a new node.","sessid":"b03429453c85d4bf3d600dff6511f70f"}
[INFO] node.save response: undefined
[WARN] Exception in event callback. {
line = 90;
message = "Unable to parse JSON string";
name = SyntaxError;
sourceId = 204738256;
sourceURL = "file://localhost/Users/justin/Sites/Apps/appname/Resources/add.js";
}
I'm not getting access denied but it isn't sending a response back to the app.
Has anyone else ran into this issue and if so have you been able to find a fix for it?
There are a few problems with the modified JSON server from Sumit's blog at this moment. The patch was made to work with a previous version of services 2. Two days ago I was dealing with the same issue. I was working quite frantically and unfortunaly don't remember anymore how everything unfolded. One of the issues is that the outdated json server module makes services crash. Again, I don't remember the details anymore, but here is the solution I found. It's php 5.2 + only , as it uses json_encode and json_decode. First pull the latest stable version of JSON Server.
Main point is that json_decode should return associative arrays instead of php objects, as that is what Drupal is expecting. So you call json_decode($json_string,TRUE), using the boolean switch makes json_decode return assoc arrays. So below a quick and very dirty solution:
function json_server_server() {
$_POST = json_decode($_POST['data'],true);
$_POST = (array)$_POST;
if (!isset($_POST)) {
return drupal_to_js(array('error' => TRUE, 'data' => "JSON server accepts POST requests only."));
}
$methods = services_get_all();
services_strip_hashes($methods);
$request = $_POST['method'];
$args = array();
foreach ($methods as $method) {
if ($method['method'] == $request) {
unset($_POST['q']);
unset($_POST['method']);
$args = array();
foreach($method['args'] as $arg) {
if(isset($_POST[$arg['name']])) {
$args[] = $_POST[$arg['name']];
}
elseif($arg['optional'] == 0) {
return drupal_to_js(array("error" => TRUE, "data" => "Argument ". $arg['name'] ." not recieved"));
}
else {
$args[$arg['name']] = NULL;
}
}
$result = services_method_call($method['method'], $args);
if (is_array($result) && $result['error'] === TRUE) return drupal_to_js(array('error' => TRUE, 'data' => $result['message']));
return(json_encode($result)); //json encode the result, not including the error
}
}
return drupal_to_js(array('error' => TRUE, 'data' => "Invalid method $request"));
}
Try wrapping your parameters between quotes; like "node.save"; it worked for me.
node.get, view.get and system.connect use different permissions than node.save. Its likely that they are all authorized for the anonymous user while node.save isn't. Since you mention system.connect, I guess you already try to start an authenticated session before calling node.save. Are you sure the session is properly maintained between calls?
Also,
Exception in event callback. {
line = 90;
message = "Unable to parse JSON string";
name = SyntaxError;
sourceId = 204738256;
sourceURL = "file://localhost/Users/justin/Sites/Apps/appname/Resources/add.js";
}
This looks more like an exception in the application code handling the server response than an error server-side. It is likely that this is caused by the server returning an HTTP 403 error without a JSON body on access denied.