Invoke operation 'myMethod' failed in RIA Services in Silverlight - c#

I have a server-side WCF RIA Service that is intentionally throwing an exception because the user entered an invalid value. This exception comes across the wire, however, I can't figure out how to catch it. I currently have the following code:
try
{
DomainContext.CalculateRequest(OnCalculateCompleted, null);
}
catch (Exception ex)
{
MessageBox.Show("here");
}
...
private void OnCalculateCompleted(InvokeOperation response)
{
try
{
if (response.HasError == false)
{
// Do stuff with result
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How do I handle exceptions thrown by a server-side operation on the client side? None of my catch statements are being triggered. Thank you!

On the client side the InvokeOperation.HasErrors will be true and you can get the Exception object from the InvokeOperation.Error. Note, if you handled the error you should also call MarkErrorAsHandled().
Your OnCalculateCompleted might looks something like this.
private void OnCalculateCompleted(InvokeOperation response)
{
if (response.HasError == false)
{
// Do stuff with result
}
else
{
MessageBox.Show(response.Error.Message);
response.MarkErrorAsHandled();
}
}

Yes, because in the callback (OnCalculateCompleted), exception will not be marshalled. The exception will reside in the response.Error property.
But take care, because your server-side thrown exception will NOT be found in the response.Error!
You should override your DomainService's OnError method, package your server-side exception via errorcodes or something, and on the client (SL) side, you have to unpack it again.

Related

How to resume second method after first method throws an exception C#

While looking on C# try catch tutorial, I got following question. My sample code as follows,
Inside mainMethod() , I need to call three separate methods. Inside testMethodOne(), I need to handle exception as. If testMethodOne() throws exception, without executing testMethodTwo(dt), mainMethod() throwing exception. I need to call testMethodTwo(dt); and testMethodThreee(dt); if testMethodOne() throws exception, how can I do it.
public void MainMethod(data dt){
try{
testMethodOne(dt);
testMethodTwo(dt);
testMethodThreee(dt);
}catch(Exception ex){
throw ex;
}
}
public void testMethodOne(dt){
try
{
// Block of code to try
}
catch (Exception e)
{
// Block of code to handle errors
}
}
I understood your question as follows (but I might be wrong, your questions is not very clear):
Even if one of your testMethods throws an exception, you still want to continue in the normal program flow with the other methods. If at least one of the method failed, mainMethod could then report this as AggregateException.
public void MainMethod(data dt)
{
var exceptions = new List<Exception>();
try
{
testMethodOne(dt);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
try
{
testMethodTwo(dt);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
try
{
testMethodThreee(dt);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
if (exceptions.Count > 0)
{
throw new AggregateException(exceptions);
}
}
It seems as if you want exceptions to alter the flow of your main method without breaking everything. One easy method is to make each 'testmethod' return a boolean.
public bool testMethodOne(dt){
try
{
// Block of code to try
return true;
}
catch (Exception e)
{
// Block of code to handle errors
return false;
}
}
Then in your main code you can go
if(!testMethodOne(dt))
if(!testMethodTwo(dt))
if(!testMethodThree(dt))
//log that all methods failed
The above snippet would try each method until it finds one that succeeds. If that's not the behaviour you are looking for can you reword your question to make it clearer? If you want the opposite to happen just get rid of the ! and it will go until one fails. Alternatively you could put a throw in your catch statement in each of the testMethods, and that would stop execution once one is reached as well.

System.Threading.ThreadAbortException on generic redirection

I am working on an ASP.Net project where we have an centralized redirection method. But some times it throws an exception:
System.Threading.ThreadAbortException
The main problem is that often the code execution is not stopping after calling SBA.Redirect("AnotherPage.aspx") and the following code is still executing.
My generic function:
public static class SBA
{
public static void Redirect(string Url)
{
try
{
HttpContext.Current.Response.Redirect(Url, false);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
if (ex.GetType() != typeof(System.Threading.ThreadAbortException))
{
throw;
}
}
}
}
Redirect raises a ThreadAbortException specifically in order to stop any following code from being run.
You are handling the ThreadAbortException.
Thus the following code is being run.
If you don't want the following code to be run, don't handle the ThreadAbortException.
Simply make the following call to make a redirect:
HttpContext.Current.Response.Redirect(Url);
There are two problems with your code:
You use an overload of Redirect where you decide to not end the response by supplying false for the endResponse parameter. Hence the code after the redirect executes.
You try to catch ThreadAbortException. When using the normal redirect as described above this exception is thrown. It is not an error condition but simply a way for ASP.NET to ensure proper termination of the current request. You can catch the exception but it is rethrown at the end of the catch block so your catch block will not do anything useful.
Because an exception is thrown when redirecting you should be aware of the following explained in the comment:
void HandleRequest() {
try {
Response.Redirect(" ... url ... ");
}
catch (Exception) {
// Code here will execute after the redirect.
}
}
To avoid problems the best thing is to catch a more specific exception type in the catch handler or at least not do anything in the handler that interferes with the redirect (like writing to the response stream).
I protected the redirection using the code below. It's working.
public static class SBA
{
public static void Redirect(string Url)
{
try
{
//redirect only when 'IsRequestBeingRedirected' is false
if (!HttpContext.Current.Response.IsRequestBeingRedirected)
{
Uri uri = null;
bool isUriValid = Uri.TryCreate(Url, UriKind.RelativeOrAbsolute, out uri);
if (!isUriValid)
{
throw new SecurityException("Invalid uri " + Url);
}
//Below check is not required but checked
//to make obsolate security check
if (uri.OriginalString == null)
{
throw new SecurityException("Invalid uri " + Url);
}
// check if host is from configured trusted host list
if (uri.IsAbsoluteUri)
{
var tempAppSetting = ConfigBLL.GetAppSetting(AppSettingSectionType.OtherSetting).Other;
if (!tempAppSetting.RedirectTrustedUrls.Contains(uri.Host))
{
throw new SecurityException("Untrusted url redirection detected. Can not redirect.");
}
}
var tempUrl = uri.OriginalString;
//Few more logical check
HttpContext.Current.Response.Redirect(tempUrl, true);
}
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
if (ex.GetType() != typeof(System.Threading.ThreadAbortException))
{
throw;
}
}
}
}

How to catch a web service exception

How do you catch exceptions from a Web Service that is returning a custom object?
I've seen this post but it doesn't seem to show how to get the exception that was thrown by the service.
I can pull the SOAP Exception, but I want to be able to get the original exception that the web service returned. I've looked at the variables that are set at this time and can't seem to see the exception anywhere, I just see:
"Server was unable to process request. ---> Exception of type
'RestoreCommon.ConsignmentNotFoundException' was thrown."
try
{
Consignment cons = WebServiceRequest.Instance.Service
.getConsignmentDetails(txtConsignmentNumber.Text);
lblReceiverName.Text = cons.Receiver.Name;
}
catch (ConsignmentNotFoundException)
{
MessageBox.Show("Consignment could not be found!");
}
Is this possible?
In short, no.
Web services will always throw SOAP fault. In your code,
MessageBox meant to be used in Windows forms and nowhere else.
You can throw this exception and in the client application, you will have to handle a SOAP fault.
Edit: If you do not want to send exceptions across to the client, this what you could do:
class BaseResponse
{
public bool HasErrors
{
get;
set;
}
public Collection<String> Errors
{
get;
set;
}
}
Each WebMethod response must inherit from this class. Now, this is how your WebMethod blocks would look like:
public ConcreteResponse SomeWebMethod()
{
ConcreteResponse response = new ConcreteResponse();
try
{
// Processing here
}
catch (Exception exception)
{
// Log the actual exception details somewhere
// Replace the exception with user friendly message
response.HasErrors = true;
response.Errors = new Collection<string>();
response.Errors[0] = exception.Message;
}
finally
{
// Clean ups here
}
return response;
}
This is just an example. You may need to write proper exception handling code rather than simply using generic catch block.
Note: This will take care of exceptions occurring in your application only. Any exceptions occurring during communication between client and service, will still be thrown to the client application.

Get more error detail info from WCF in Silverlight client

In Silverlight client I get error but it always looks like :
An exception occurred during the operation, making the result invalid.
Check InnerException for exception
details.
at
System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
at
SecretaryAppNav.ClientService.GetChildAndOpiekunByFirstnameLastnameCompletedEventArgs.get_Result()
at
SecretaryAppNav.Views.FindChild.Client_GetChildAndOpiekunByFirstnameLastnameCompleted(Object
sender,
GetChildAndOpiekunByFirstnameLastnameCompletedEventArgs
e) at
SecretaryAppNav.ClientService.Service1Client.OnGetChildAndOpiekunByFirstnameLastnameCompleted(Object
state)
In client files I always use try catch to catch erorrs but it never invoke, :
void Client_GetChildAndOpiekunByFirstnameLastnameCompleted(object sender, GetChildAndOpiekunByFirstnameLastnameCompletedEventArgs e)
{
try
{
this.dataForm1.ItemsSource = e.Result.Collection;
}
catch (FaultException ex)
{
System.Windows.Browser.HtmlPage.Window.Alert(ex.Reason.ToString() + ex.Code.ToString() );
throw new FaultException(ex.Reason, ex.Code, "Klikanie");
}
}
Should I put this catch in my service files to catch SOAP errors ? Without more info I always searching for mistake in my code like in the dark ... :/
If you're debugging your application and you want to simply catch every exception, you do this:
catch (Exception ex)
{
System.Windows.Browser.HtmlPage.Window.Alert(ex.Reason.ToString())
}
You may want to re-throw the exception after that or check to see what type of exception it is, but this can be a useful way to catch exceptions in Debug mode.
You also might put a break point on the line of code that catches the general exception. This will allow you to "watch" the exception when it is thrown and then look at its nested inner exception(s).

Cannot handle FaultException

i have a wcf service that does an operation. and in this operation there could be a fault. i have stated that there could be a fault in my service contract.
here is the code below;
public void Foo()
{
try
{
DoSomething(); // throws FaultException<FooFault>
}
catch (FaultException)
{
throw;
}
catch (Exception ex)
{
myProject.Exception.Throw<FooFault>(ex);
}
}
in service contract;
[FaultException(typeof(FooFault))]
void Foo();
when a FaultException was thrown by DoSomething() method while i was running the application, firstly the exception was caught at "catch(Exception ex)" line and breaks in there. then when i pressed f5 again, it does what normally it has to. i wonder why that break exists? and if not could it be problem on publish?
Are you consuming the WCF service from Silverlight? If so, a special configuration is needed to make the service return a HTTP 200 code instead of 500 in case of error. The details are here: http://msdn.microsoft.com/en-us/library/dd470096%28VS.96%29.aspx
Actually your exception is caught but you fail to notice it since visual studio highlights the next line, not the line throwing the exception. Replace
throw;
with some other lines and see them in action.
Take a closer look at catched exception. Was it FaultException< FooFault> or FaultException ? There are 2 version of FaultException class: generic and non-generic
#yapiskan,
C# is a strong typed language Foo< X> != Foo. So if you need to catch some exception, provide exact type in catch clause.
You can learn more on exception handling reading this MSDN article.
The problem is that exceptions are checked in the order they are declared. Try putting the Exception catch block first and you will see that the compiler complains: other catch blocks will NEVER be evaluated. The following code is generally what .Net is doing in your case:
// Begin try
DoSomething(); // throws FaultException<FooFault>
// End try
if (exceptionOccured)
{
if(exception is FaultException) // FE catch block.
{
throw;
// Goto Exit
}
if(exception is Exception) // EX catch block
{
throw new FaultException<FooFault>();
// Goto Exit
}
}
// Exit
As you can see your FaultException never re-enters the try-catch-finally (i.e. try-catch-finally is not recursive in nature).
Try this instead:
try
{
try
{
DoSomething(); // throws FaultException<FooFault>
}
catch (Exception ex)
{
if (ex is FaultException<FooFault>)
throw;
else
myProject.Exception.Throw<FooFault>(ex);
}
}
catch (FaultException)
{
throw;
}
HTH.

Categories