HttpWebRequest.BeginGetResponse results in System.NotSupportedException on Windows Phone - silverlight

I realise that similar questions have been asked before however none of the solutions provided worked.
Examining the token returned from the BeginGetResponse method I see that the following exception is thrown there:
'token.AsyncWaitHandle' threw an exception of type 'System.NotSupportedException'
This page tells me that this exception means the Callback parameter is Nothing, however I'm passing the callback - and the debugger breaks into the callback method when I insert a breakpoint. However the request object in the callback is always null. I can view the same exception detail in the result object in the callback method.
I've tried using new AsyncCallback(ProcessResponse) when calling BeginGetResponse
I've tried adding request.AllowReadStreamBuffering = true;
I've tried this in-emulator and on-device, with no luck on either.
public static void GetQuakes(int numDays)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://magma.geonet.org.nz/services/quake/geojson/quake?numberDays=" + numDays);
// Examining this token reveals the exception.
var token = request.BeginGetResponse(ProcessResponse, request);
}
static void ProcessResponse(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
if (request != null)
{
// do stuff...
}
}
So I'm at a bit of a loss as to where to look next.

'token.AsyncWaitHandle' threw an exception of type
'System.NotSupportedException'
This page tells me that this exception means the Callback parameter is
Nothing
The documentation you are looking at http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse%28v=vs.95%29.aspx is for BeginGetResponse. Silverlight does not use the AsyncWaitHandle, and correctly throws a NotSupportedException. You are seeing the exception System.NotSupportedException is for call to IAsyncResult.AsyncWaitHandle you are making when you inspect token.
The documentation on IAsyncResult.AsyncWaitHandle says explicitly that it is up to the implementation of IAsyncResult whether they create a wait handle http://msdn.microsoft.com/en-us/library/system.iasyncresult.asyncwaithandle(v=vs.95).aspx. Worrying about this is sending you down th wrong path.
I think you need to descibe the actual problem you are seeing. It is great to know what you have investigated, but in this case it does help resolve the problem.
The code should work and in ProcessResponse request should not be null when you test it in the if statement. I just copied the code you have provided into a windows phone application and ran it with no problems.

Related

CXF's readEntity() got "Entity is not available"

I am working on a piece of code that uses CXF (3.1.2)
I am seeing this error intermittently:
java.lang.IllegalStateException: Entity is not available
at org.apache.cxf.jaxrs.impl.ResponseImpl.checkEntityIsClosed(ResponseImpl.java:481)
at org.apache.cxf.jaxrs.impl.ResponseImpl.doReadEntity(ResponseImpl.java:333)
at org.apache.cxf.jaxrs.impl.ResponseImpl.readEntity(ResponseImpl.java:320)
at org.apache.cxf.jaxrs.impl.ResponseImpl.readEntity(ResponseImpl.java:310)
To improve performance, the Response objects are held through a Google Guava LoadingCache (com.google.common.cache.LoadingCache). It seems like I would get this error after an object has been in the cache for a few minutes. Could the Response object because invalid
after a few minutes?
private static LoadingCache<String, Response> cachedLdapRespMap
= CacheBuilder.newBuilder()
.maximumSize(Constants.LDAP_RESP_CACHE_SIZE)
.expireAfterWrite(Constants.LDAP_RESP_CACHE_KEEP_ALIVE_MINUTE
, TimeUnit.MINUTES)
.build(
new CacheLoader<String, Response>() {
#Override
public Response load(String uid)
throws Exception {
Response res = makeLdapRequest(uid);
return res;
}
}
);
(I am answer the question myself)
The problem was that I have concurrent processes that attempted to readEntity(), the first process consumed the input stream (or may have even closed the stream), and the second process would either get thrown an IllegalStateException or got an empty message. Here is what the JavaDoc of javax.ws.rs.core.Response (which org.apache.cxf.jaxrs.impl.ResponseImpl extends) says:
Throws:
IllegalStateException - if the entity is not backed by an
input stream, the response has been closed already, or if the entity
input stream has been fully consumed already and has not been buffered
prior consuming.
So to fix the problem, I changed my design to cache not the Response object but rather the string message that is the result of the readEntity() call. The call would be done exactly once when the response comes back:
Response resp ...
String respStr = resp.readEntity(String.class);
and the problem is solved.

codenameone: how to handle exception java.net.ConnectionException explicitly

codenameone: how to handle exception java.net.ConnectionException explicitly
I want to handle exception explicitly.Currently when I am handling exception It handled implicitly first in which shows the exception message on screen in detail.I don't want to show in detail error message on screen(pop up dialog).
right now it shows the exception Java.net.Connection Exception: Connection refused for URL http:localhost/login connection refused.instead of this message i just want to show "connection refused" message on pop-up dialog
Can you please let me know how to resolve it.
On mobile devices the error might be quite different to the one on the simulator since we are dealing with native API's under the surface. See the error handling section of the networking section in the developer guide:
There are two distinct placed where you can handle a networking error:
The ConnectionRequest - by overriding callback methods
The NetworkManager error handler
Notice that the NetworkManager error handler takes precedence thus allowing you to define a global policy for network error handling by consuming errors.
E.g. if I would like to block all network errors from showing anything to the user I could do something like this:
NetworkManager.getInstance().addToQueue(request);
NetworkManager.getInstance().addErrorListener((e) -> e.consume());
The error listener is invoked first with the NetworkEvent matching the error. Consuming the event prevents it from propagating further down the chain into the ConnectionRequest callbacks.
We can also override the error callbacks of the various types in the request e.g. in the case of a server error code we can do:
ConnectionRequest request = new ConnectionRequest(url, false) {
protected void handleErrorResponseCode(int code, String message) {
if(code == 444) {
// do something
}
}
protected void handleException(Exception err) {
// handle exception that occurred. Notice you can either have this or have the listener on the NetworkManager
}
protected void readResponse(InputStream input) {
// just read from the response input stream
}
};
NetworkManager.getInstance().addToQueue(request);

WCF service in WPF self host application crash when I throw a fault exception (async methods)

I have a service hosted in a WPF application with an async method with the Begin/end methods, and when I catch an exception in the service, I want to throw a faultException to warn to the client.
However, when I try to throw the faultException, the host application crash, shutdown suddenly.
In my repository, I catch the UpdateException, then, I create a custom exception, UniqueKeyException, that is throw to the caller. The caller is an auxiliar method that is called in the Begin method.
This auxiliar method, catch the UniqyeKeyException and only do a "throw", that is capture in the try/catch block of my end method. Here there is something that I don't understand, why in the end mehod this exception is catched in the block of AgregateException instead of the UniqueKeyException.
Well, anyway, in the catch block of the end method, in the AgregateException block, I check if the innerException is UniqueKeyException, if it is true, I create an object UniqueKeyArgs (a custom class with the information to send to the client), create a FaultException and finally do the throw FaultException. It is in this step, the throw, where the host application crash.
I think that I have all configure correctly, because my custom class UniqueKeyArgs is decorate as Datacontract and its properties as DataMember, in the app.config of my host application I configure the behavior to include exception details and in the contract I decorate it with faultContract.
Why the application crash?
My code is the following:
REPOSITORY
public List<Usuers> updateUsers(List<Users> paramUsers)
{
....
catch(UpdateException ex)
{
SqlException innerEx = (SqlException)ex.InnerException;
//Code 2627 is Unique Key exception from SQL Server.
if (innerEx != null && innerEx.Number == 2627)
{
//I create the conditions of searching
ConditionsUsers conditions = new conditions();
conditions.UserName = (Users)ex.StateEntries[0].Entity).userName;
//Search for the existing user
Users myUser = getUser(conditions);
string message = "the user " + conditions.userName + " exists.";
throw new UniqueKeyException(message, myUser);
}
throw;
}
SERVICE IMPLEMENTATION
//This is my auxiliar method, called in the Begin method.
private submitUpdates()
{
....
catch(UniqueKeyException ex)
{
//The code enter here
throw;
}
}
public IAsyncResult BeginUpdateUsers(List<users> paramUsers, AsyncCallback callback, object state)
{
Task<List<Users>> myTask= Task<List<Users>>.Factory.StartNew(p => sumbmitUpdates(paramUsers), state);
return myTask.ContinueWith(res => callback(myTask));
}
public List<Users> EndUpdateusers(IAsyncResult result)
{
try
{
return ((Task<List<Users>>)result).Result;
}
//Why agregateException and not is catched in the UniqueKeyException ???
catch(AgregateException ex)
{
if (innerExceptions[0] is UsuariosValorUnicoException)
{
//I assign manually the data to debug, to discard other problems.
Users myUser = new Users();
myUser.UserName = "Jhon";
myUser.Password = "pass123";
UniqueKeyArgs myArgs = new UniqueUserArgs("unique key error", myUser);
FaultException<UniqueKeyArgs> myException = new FaultException<UniqueKeyArgs>(myArgs);
//Crash here, in the throw myException
throw myException;
}
}
throw;
}
MY CONTRACT
[FaultContract(typeof(UniqueKeyArgs))]
IAsyncResult BeginUpdateUsers(List<Users> paramUser, AsyncCallback callback, object state);
List<Users> EndUpdateUsers(IAsyncResult result);
Crash when I throw myException in the End method.
I see in this post that the solution is catch the exception in the host application too, not only in the service object. However, this solution uses Application.ThreadException, that belong to System.Windows.Forms namespace, and I am using a WPF application.
How could I send the exception to the client from a service hosted in a WPF application?
Thanks.
EDIT1: well, I am use a try/catch block in the line where I throw the exception and I see that the error is that I have not indicated a reason, so when I create my FaultException I do:
FaultException<UniqueKeyArgs> myException = new FaultException<UniqueKeyArgs>(myArgs, new FaultReason("DummyReason");
In this case, the exception message is "DummyReason", the message that I set in the FaultReason, so it says me nothing. The FaultException is not throw, and throw the generic exception to the client.
In this case the host application does not shutdown, but close the connection with the client and I have to reconnect.
It seems that the problem is the creaton of the FaultException, but I don't see the problem.
#Roeal suggests that perhaps is only possible to use faultException with synch methods, but in this link I can see an example in which is used with async methods. I have seen others examples, is not the unique.
Thanks.
EDIT2: I solve my problem. My problem is that in the FaultException, T is an object that have a property that was a self tracking entity, and this is a problem, if I am not wrong, I only can use basic types as properties of the exception.
Then, in the exception, I have implmemented ISerialize. It's needed to be able to send the information to the client, without this, the client receives an exception.Detail with null properties.
Did you also declare the synchronous operation in your service contract? In that case, maybe this helps:
If fault contracts are defined on the service operation contract, the FaultContract attribute should be applied only on the synchronous operations.
-- Juval Lowy, "Programming WCF Services 3rd Edition" (p456)
I solve my problem. My problem is that in the FaultException, T is an object that have a property that was a self tracking entity, and this is a problem, if I am not wrong, I only can use basic types as properties of the exception.
Then, in the exception, I have implmemented ISerialize. It's needed to be able to send the information to the client, without this, the client receives an exception.Detail with null properties.

GWT RequestFactory not firing properly after using edit()

I have a problem using "fire()" with a GWT RequestFactory after I've used it to unfreeze and edit a proxy.
If I have two request factory objects and their associated contexts like this:
private SyntheticRequest req1 = requestFactory.someRequest();
private Request<xProxy> sendRequest1 = req1.something();
private SyntheticRequest req2 = requestFactory.someRequest();
private Request<xProxy> sendRequest2 = req2.something();
using "fire()" on the first request works fine:
sendRequest1.fire(new Receiver<xProxy>() {
#Override
public void onSuccess(xProxy response) {
...
if (somethingIsTrue){
xProxy x = req2.edit(response); //<-- **I think this causes a problem later, although the proxy "x" works as expected here.**
x.setSomething("something");
update();
}
});
that part runs ok because I get to the "onSuccess". But when this one runs "update()", which looks like this:
private void update(){
sendRequest2.fire(new Receiver<xProxy>(){
...onFailure...
...onSuccess...
});
}
sendRequest2 always fails, with the error
Server Error Index:0 Size:0
and I put a breakpoint in the code for the "something()" service and it never even gets to that code! There must be something about the "req2.edit()" that hurts req2 and sendRequest2, but what?
Thanks.
what is 'b'? the line xProxy x = req2.edit(b); is the first time it's mentioned? is it supposed to be xProxy x = req2.edit(response);
Anyway.. that is not the problem..
'Server Error' indicates that RequestFactory caught an exception during the processing of a request, server-side. Something (but maybe not something()) is throwing an IndexOutOfBounds exception.
If you have a look at RequestFactoryServlet.java (which you can replace with your own very easily btw) you can see it setting up a try catch block that catches all exceptions when processing a request. It passes them to 'DefaultExceptionHandler' which wraps them in a ServerFailure, and that gets returned to you GWT code as an onFailure() call.
An easy way to find where the exception is being thrown is set a breakpoint on IndexOutOfBoundsException, making sure to catch 'caught' exceptions as well as uncaught.

Random System.NotSupportedException on WP7

Sporadically, I receive an error in my WP7 Silverlight application. The error is a random "System.NotSupportedException". This error is thrown occassionally when the following code is executed:
// 1. Build the url
string serviceURL = "http://www.mydomain.com/service.svc/param1/param2";
// 2. Asynchronously execute the query using HttpWebRequest instead of WebClient. There is a UI performance issue with the WebClient currently
WebRequest request = HttpWebRequest.Create(serviceUrl);
request.BeginGetResponse(new AsyncCallback(MyService_Completed), request);
...
private void MyService_Completed(IAsyncResult result)
{
// Do stuff
}
I have verified that the URL I am sending is correct. Please note, that this request is part of my view model, which may have other network requests fired off at the same time. I have no idea why this happens ocassionally. Can anybody point out any potential reasons?
Thank you!
When this happens, make sure you look at the View Detail part of the exception report. It might be that your service is refusing connection or the data passed is invalid. NotSupported is a very general exception that covers many possible situations.
A similar question has been asked previously. If you look at the comments the original poster added to the answer, he claims to have solved the problem by replacing
request.BeginGetResponse(new AsyncCallback(MyService_Completed), request);
with
request.BeginGetResponse( MyService_Completed, request);

Resources