MonoTouch - WCF Services made by Silverlight tool - Can't catch exceptions - silverlight

Using the Silverlight service generator a service class is created:
slsvcutil.exe http://localhost/zzz/zzzz.svc?wsdl
/namespace:"*,General" /d:z:\desktop /noConfig /ser:DataContractSerializer
This class then is created and the async methods called.
Even with all calls and constructions wrapped in Exception try/catches, we can not catch errors like "System.ServiceModel.EndpointNotFoundException"
We have the exact same code running in Silverlight clients, and errors are caught in try/catch blocks.
Question: Is there another place/method I need to use in order to catch WCF errors when consuming in MonoTouch?

I don't know if I understood your question well... :)
In my opinion, in the handler for the async request, check if the error is null or not.
if(e.Error != null)
{
// insert code here to fix the error
// in a similar way you do with catch block
}
else
{
// normal execution
}
Hope it helps you!! Best regards.

This appears to be a bug. The framework team is fixing it.

Related

Camel - Handling irrecoverable errors

I’m working on Camel and focusing on Error Handling.
For irrecoverable errors (those that won’t be fixed by retries), Camel In Action says you should use exchange.getOut().setFault(true) and exchange.getOut().setBody("Error Occurred").
What is the best way to actually handle these errors? Right now I’m thinking there’s two ways:
Using handleFaults(true) on the route or context then handling like any other errors
The original message sender could handle it if Request Reply pattern is used
1 is straight forward to me (except at that point, might as well use Exceptions/Recoverable errors?). 2 is a little trickier – I’m not sure how the original sender will know that the message that they get back is an error (vs. the expected return message).
What I’m thinking could happen is this using Exception to indicate that it’s an error:
In route:
// error occurred
exchange.getOut().setFault(true);
exchange.getOut().setBody(new Exception(“error”));
In sender (jms example using QueueRequestor for Request Reply):
responseMessage = qRequestor.request(msg);
if(responseMessage instanceof ObjectMessage && ((ObjectMessage)responseMessage).getObject() instanceof Exception) {
// AN ERROR OCCURRED IN ROUTE
} else {
// NORMAL PROCESSING OF MESSAGE
}
This just seems like a lot of work on the original sender. Is there a better way of handling this?
Camel can handle the exception well out of box with the help of ErrorHandler, which means your camel route don't need to do much thing about it.
But for the fault message, it's a part of Application level message, Camel ErrorHandler don't want to touch it, so the developer should think about how to handle it.

SqlServer SMO Scripting.ScriptingError event handler not firing

I have a SQL Sever 2008 R2/64-bit database server for which I'm writing some fairly basic scripting utilities with the Sql Server Management Objects (SMO). My project is a 32-bit VS2010 executable written in C#.
Most of the effort has been fairly simple and successful. The only problem I'm having is in the firing of my custom event handler that should be called in response to a Scripting Error.
The Scripter object exposes a ScriptingError event, which I have attempted to leverage thusly:
//srv contains a valid server name
Scripter scrp = new Scripter(srv);
//scrp_ScriptingError is my handler
scrp.ScriptingError += new ScriptingErrorEventHandler(scrp_ScriptingError);
My handler is declared thusly:
static void scrp_ScriptingError(object sender, ScriptingErrorEventArgs e)
{
// my handler goes here, just printing e.Current.Urn to the console
// This is merely representative, have had other things here, but
// the handler never fires
Console.WriteLine(e.Current.Value);
}
All this compiles cleanly.
My code is invoked via simple scrp.Script(urns); where urns is just an array of the database objects being scripted out. Nothing fancy:
try
{
sc = scripter.Script(urns);
}
catch (Exception e)
{
WriteLog(String.Format("Failure during scripting: {0}: Inner exception message (if any): {1}",e.Message,((e.InnerException==null)?"[None]":e.InnerException.Message)));
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName,true))
{
foreach(String currentLine in sc)
{
file.WriteLine(currentLine);
file.WriteLine("GO");
}
}
The problem is that, no matter what I've tried so far, when errors occur during scripting, my ScriptingError handler never fires.
Even in debug mode within VS2010, when I set a breakpoint within the handler, and fire my scripting code, and know an error will occur, only an exception will be thrown, but the breakpoint in my ScriptingError handler never trips.
I'm in trees-for-forest mode now, not sure what I've done wrong. Am I expecting the wrong things for the ScriptingError handler?
I have searched the MSDN docs on the SMO objects and found virtually nothing on ScriptingError handlers other than the basic API calls themselves, and precious few examples on the Internet. It seems incredibly simple and straightforward to me - just assigning an event handler to the event - but there's some battery-not-included notice I've failed to note.
Pointers to my error are greatly appreciated, with a polite request for minimal brickbats if the error is exceptionally stupid on my part :)
I am not at a pc right know, but I think you should try to set the ContinueScriptingOnError option. Otherwise there would be no reason for SMO to invoke the event, but rather through an exception instead.

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);

Windows Phone 7 close application

Is there any possibility to programatically close Silverlight application on Windows Phone 7?
If you write an XNA Game, you will have access to an explicit Exit() method. If you are writing traditional Silverlight project, then NO, there is no way to programatically close your app. See also Peter Torr's Blog entry on Exiting Silverlight Apps in Windows Phone 7. There he also mentions the option of throwing an unhandled exception, which IMO is a terrible programing style.
An option you may try, is using the WP7 Navigation Service to programatically navigate back out of the application. Not sure if that would work though. Why do you need to Exit?
You can always call an exit by doing this at your landing page use this code on click of your application back button:
if (NavigationService.CanGoBack)
{
while (NavigationService.RemoveBackEntry() != null)
{
NavigationService.RemoveBackEntry();
}
}
This will remove back entries from the stack, and you will press a back button it will close the application without any exception.
Short answer for Silverlight is No.
You should not provide a way to close the applicaiton. Closing the applicaiton should be the users choice and implemented by using the back button the appropriate number of times. This is also a marketplace requirement.
That said, a silverlight application will close if there is an unhandled exception. I have seen a few people try and create programmatic closing by throwing a custom error which is explicitly ignored in error handling. This can work but there is still the marketplace issue.
XNA applications can explictly call Exit().
Some good info here already. Adding to this..
The platform is fully capable of managing closure of apps. The more apps don't provide an exit, the quicker users will become accustomed to not thinking about app house keeping, and let the platform manage it.
The user will just navigate their device using start, back, etc.
If the user wants out of the current app to go do something else quickly - easy - they just hit start.
.Exit(), whilst available for xna, really isn't required anymore either. There was a cert requirement during CTP that games had to provide an exit button. This is now gone.
Non game apps never had the need to implement this.
The more this topic's discussed (and it really has been given a good run around the block), the more the indicators to me suggest there is no need to code an exit.
Update: For those thinking of an unhandled exception as a suitable way of closing an app intentionally or letting the app close due to subpar operating conditions, I would recommend reviewing the comments concerning Application Certification Requirements in this answer. Is there a way to programmatically quit my App? (Windows Phone 7)
Here is another solution.
If you have an error page that i.e. displays error to the end user you can use the
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
base.OnBackKeyPress(e);
e.Cancel = true;
}
And you can instruct user to press start button to exit application.
Add a reference to Microsoft.Xna.Framework.Game, then call:
new Microsoft.Xna.Framework.Game().Exit();
private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
{
while (NavigationService.CanGoBack)
NavigationService.RemoveBackEntry();
}
That works for me fine.
You can close the app using this statement
Application.Current.Terminate();
This worked perfectly on Windows phone 7
System.Reflection.Assembly asmb = System.Reflection.Assembly.Load("Microsoft.Xna.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553");
asmb = System.Reflection.Assembly.Load("Microsoft.Xna.Framework.Game, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553");
Type type = asmb.GetType("Microsoft.Xna.Framework.Game");
object obj = type.GetConstructor(new Type[] { }).Invoke(new object[] { });
type.GetMethod("Exit").Invoke(obj, new object[] { });
Link - source
My 2 pence worth, reasons for an exit
1) there is no interent connection the first time it is run and it needs to create an account on a web service somewhere to run.
2) You need to force an upgrade for the user, again when tied to a web service, you may discover a bug in your app, or have web service changes that mean the user needs to be forced to upgrade, at that point you will want to inform the user that they must upgrade and then exit the app.
Currently in my app I am forced to take the user to a form that says "they" must exit, and if they click back they are again forced back to this page. not very nice.
In Silverlight, I throw an un-handled exception when I have to exit the application. I know that this isn't the graceful method to handle this but it is still the most convenient and easiest solution.
I know that according to the guidelines there shouldn't be any un-handled exceptions in the code but I write why I am explicitly throwing an un-handled exception in the Exception Request document at the time of submission.
Till now this method has always worked and never failed me.
Easiest way to do this is to add a reference to Microsoft.Xna.Framework.Game, then add
using Microsoft.Xna.Framework.GamerServices; before namespace. Then we have a button in our Example.xaml with Click="quit_button". In out Example.xaml.cs we put this code inside our page-class:
private void quit_Click(object sender, EventArgs e)
{
new Microsoft.Xna.Framework.Game().Exit();
//This will close our app
}
var buttonInfo = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButton.OKCancel);
if (buttonInfo == MessageBoxResult.OK)
{
if (NavigationService.CanGoBack)
{
while (NavigationService.RemoveBackEntry() != null)
{
//
}
}
e.Cancel = false;
}
else
{
//Stop page from navigating
e.Cancel = true;
}
Navigate to App.xaml.cs in your solution explorer and
add a static method to the App class
public static void Exit()
{
App.Current.Terminate();
}
so that you can call it anywhere from your application , as below
App.Exit();

WCF RIA Services: overriding DomainService.AuthorizeChangeSet - who cares?

I am overriding the AuthorizeChangeSet method and return false. The change set is not applied to the data context as expected, but how is the client notiied about this authorization error? The returned SubmitOperation has no error, and I cannot find any information elsewhere inside.
(Still using the Nov 2009 beta with VS2008 and net3.5)
Actually, no one cares. With reflector I finally found the place in the framework, where my false is being swallowed: DomainService.AuthorizeChangeSet is called by DomainService.Submit, which is still returning the outcome of DomainService.AuthorizeChangeSet. But see what the ChangeSetProcessor.Process is doing with it:
public static IEnumerable<ChangeSetEntry> Process(DomainService domainService, IEnumerable<ChangeSetEntry> changeSetEntries)
{
ChangeSet changeSet = CreateChangeSet(changeSetEntries);
domainService.Submit(changeSet);
return GetSubmitResults(changeSet);
}
... nothing.
I'd highly suggest using the version that builds on .net 4.
Essentially what I'd expect to see is an error on the SubmitOperation that you can inspect on your Submit callback. The error should indicate there was an authorization failure.

Resources