Can a NServiceBus message have an anonymous type property? - nservicebus4

I have a Payload property of type object.
I fill Payload with an anonymous type, and send it off, I then get this ugly error:
2014-03-12 15:50:25,649 [7]
ERROR NServiceBus.Unicast.Transport.TransportReceiver [(null)] <(null)> -
Failed to serialize message with ID: fc8d44c1-3750-4658-ba91-a2ec010507aa`
System.Runtime.Serialization.SerializationException:
An error occurred while attempting to extract logical messages from
transport message NServiceBus.TransportMessage --->
Newtonsoft.Json.JsonSerializationException:
Error resolving type specified in
JSON '<>f__AnonymousType2`2[[System.String, mscorlib],[System.Int32,mscorlib]], MyProject'.
Path '[0].Payload.$type', line 1, position 366. ---> Newtonsoft.Json.JsonSerializationException: Could not load assembly 'MyProject'.

I ran into this problem - the issue is with json.net not really NServiceBus.
Json.Net is requiring being able to deserialize the type into a strict object, which it just can't.
There are a couple ways you can do this, you can change your payload object into an interface which will force NServiceBus to use TypeNameHandling.None which in turn will cause Json.Net to deserialize even if doesn't know the type.
Or you can write your own serializer, probably based heavily off their Json.Net one but with TypeNameHandling.None always on.
I have not found a reason to keep TypeNameHandling on, I think maybe the particular team made a decision to do it that way.

Related

Cannot Retry a Request Which Hasn't Previously Been Completed

I had to copy some existing beans and their remote interfaces within an existing working application. Now whenever I call one of the methods, I get the following exception:
java.lang.IllegalStateException: EJBCLIENT000032: Cannot retry a request which hasn't previously been completed
at org.jboss.ejb.client.EJBClientInvocationContext.retryRequest(EJBClientInvocationContext.java:203)
at org.jboss.ejb.client.EJBInvocationHandler.sendRequestWithPossibleRetries(EJBInvocationHandler.java:256)
at org.jboss.ejb.client.EJBInvocationHandler.sendRequestWithPossibleRetries(EJBInvocationHandler.java:265)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:198)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:144)
at com.sun.proxy.$Proxy27.createRawSTRProfiles(Unknown Source)
at org.acme.project.CreateSomethingRunnable.run(CreateSomethingRunnable.java:76)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)
The same bean works for other method calls. There is no other exception on neither client nor server side, a breakpoint inside the server method in question is never called. I have no idea how to debug, and Google is oblivous to this error message. We are using WildFly 8.1.0.Final.
Can anybody help shed light on this issue? Thanks.
The root exception for us was a ClassNotFoundError because an entirely unrelated JAR inside the EAR had the wrong version number.
Double-check everything. We dismantled the value that was sent (setting all fields to null). When that worked, we set the fields to objects again one by one, checking the classes in question for Serializable (because sometimes a missing Serializable causes similar exceptions).
In short, ensure that all classes going over the wire implement the Serializable interface.

HttpClient 4.1.x - Handling protocol error with body content

I've been doing some digging with an application system utilizing HttpClient 4.1.x to handle RESTful calls under Spring.
While I've got this working great under both directly dealing with the httpclient as well as using as the transport for the RestTemplate, I've found that I have a need for something that I'm not sure was covered in execution.
The "BasicResponseHandler" treats the content response as a string and returns it provided that the response from the server is less than 300. The RESTful system I'm working with provides an XML document as part of an error response (status code >= 400). This XML response contains some information that may be of use to the client developer.
What I'd like to see if anyone has any experience dealing with this via the ResponseHandler interface. Essentially, the BasicResponseHandler will toss a ClientProtocolException in the case that there is a status >= 300. The handling AbstractHttpClient implementation will trap that exception, consume the entity silently, then re-throw the IOException (ClientProtocolException) that was thrown.
Would it be advisable to create a sub-class of ClientProtocolException to contain the additional information?
In the case of the error status, unmarshal any existing document into its respective type (if available) and then throw it thus preserving the content of the response.
Or is there another mechanism that I'm missing to handle this case?
The purpose of the ResponseHandler interface is to enable the caller to digest HTTP responses without buffering message content in memory. An extra benefit of using this interface is not having to worry about resource deallocation which is taken care of automatically by HttpClient.
In your particular case you should consider building a higher level domain object from the low level HTTP response content instead of returning a simple, unrepresentative string.
So, instead of throwing an exception, consider returning back to the caller an object consisting of the request status (success, failure, partial response, etc), and a parsed XML document or an JAXB object representing a message content.

How can I tell if Deserialization failed in protobuf.net?

I had protobuf.net deserialize invalid (random) bytes into a KeyValuePair (i.e. not nullable). Instead of (as expected) an exception being thrown, an empty struct was returned.
Since this default struct could be valid data, I don't see a way to tell if the source data are actually valid. Is this a bug, or is there a way I'm missing?
(protobuf-net 2.0.0.480, 2011.12.11)
Update:
There were scenarios in v2 where it wouldn't spot this, but would instead terminate as though it had reached the end of the stream - in particular if the "field number", after applying shifts, was non-positive. However, this is not valid in a protobuf stream, and this will be fixed next build.
That depends on quite how random it was ;p Actually, getting that to do anything without throwing an error is pretty impressive - the protobuf spec is pretty specific about layout, and normally it will throw a big exception there (probably mentioning "unexpected wire-type" or similar).
Emphasis: in almost all cases it will throw an exception. If you fluke some data of the right spec, but different field numbers, then it will silently ignore the unexpected data, and you'll get an all-zero struct. If you fluke some data of the right spec, but with the right field numbers and layout, you'll get garbage. But that is like saying
if I randomly generate data that by pure chance happens to be {"foo":"0"}, JavascriptSerializer doesn't complain!!! bug!!!
Are you sure you actually deserialized some data here? and that the stream wasn't already the EOF position? For example, the following won't error, as you haven't rewound the stream - you are effective deserializing zero bytes:
var ms = new MemoryStream();
ms.Write(randomBytes, 0, randomBytes.Length);
var obj = Serializer.Deserialize<Foo>(ms);
(and zero bytes is perfectly valid for a protobuf object)
If you want to test a stream for validity, you can use ProtoReader, just skipping (SkipField() or something similar) every field until ReadNextHeader() (or whatever) returns a non-positive integer.

Are exceptions from RPCs the same as normal exceptions?

Trying to understand more about RPCs to answer a homework question: Are exceptions handle the same way for the caller? Are the details of how exceptions are raised on the server any different? Are there any additional differences if you have to rethrow?
OR, can someone just explain what the main differences are between local and remote exceptions? And maybe give an idea of what things to look out for if I wanted to implement remote exceptions.
Here's a simple version of an RPC server / client library:
Server:
try
receive message
deserialize arguments
invoke appropriate method
serialize result
transmit result
catch any Exeption
serialize Exception
transmit Exception
Client (Library code, not the caller):
try
serialize arguments
make remote call
receive "something"
deserialize "something" (could be serialized exception or result)
catch Timeout,Network,Other exceptions not from server
handle whatever the library handles
if deserialized "something" is an exception
rethrow exception from server for caller to catch
else, good/expected results
return results
So, if you want exceptions to be caught by the caller, they possibly differ from regular exceptions in that they must be serialized and transmitted over the network to be re-thrown for the caller.
The caller need not do anything special if the Client library exists. If the client library doesn't exist, then the caller needs to also take the role of the client library. This means that the caller needs to distinguish between serialized results and serialized exceptions (at which point the programmer would probably implement an ad-hoc version of the client library code anyway just to avoid having ugly caller code).
Obviously you can't just use type signatures to distinguish between Exceptions and results (otherwise, what happens if the return type and the exception types for an RPC method were the same?). So there's a tiny bit of overhead in the serialization code for the server to label the different responses.

error handling vs exception handling in objective c

I am not able to understand the places where an error handling or where an exception handling should be used. I assume this, if it is an existing framework class there are delegate methods which will facilitate the programmer to send an error object reference and handle the error after that. Exception handling is for cases where an operation of a programmer using some framework classes throws an error and i cannot get an fix on the error object's reference.
Is this assumption valid ? or how should i understand them ?
You should use exceptions for errors that would never appear if the programmer would have checked the parameters to the method that throws the exception. E.g. divide by 0 or the well known "out of bounds"-exception you get from NSArrays.
NSErrors are for errors that the programmer could do nothing about. E.g. parsing a plist file. It would be a waste of resources if the program would check if the file is a valid plist before it tries to read its content. For the validity check the program must parse the whole file. And parsing a file to report that it is valid so you can parse it again would be a total waste. So the method returns a NSError (or just nil, which tells you that something went wrong) if the file can't be parsed.
The parsing for validity is the "programmer should have checked the parameters" part. It's not applicable for this type of errors, so you don't throw a exception.
In theory you could replace the out of bounds exception with a return nil. But this would lead to very bad programming.
Apple says:
Important: In many environments, use of exceptions is fairly commonplace. For example, you might throw an exception to signal that a routine could not execute normally—such as when a file is missing or data could not be parsed correctly. Exceptions are resource-intensive in Objective-C. You should not use exceptions for general flow-control, or simply to signify errors. Instead you should use the return value of a method or function to indicate that an error has occurred, and provide information about the problem in an error object.
I think you are absolutely right with your assumption for Errors and for it framework provide a set of methods (UIWebView error handling ), But your assumption for Exception partially right because the exception only occurred if we do something wrong which is not allowed by the framework and can be fixed. (for example accessing a member from an array beyond its limit).
and will result in application crash.