Silverlight | Correct way to do exception handling - silverlight

Hello All,
I would like to know how to handle the exception in the Silverlight
? Since it is the code which runs
at Client side , So if some
exception happens in the client nor related to web service . So should I show
user friendly message and again make a
call to the server and store the exception details there.
Is it the correct approach ? If not
please suggest a better one
Regards,
Phani

The standard seems to be to expose a method in your webservice (such as logEvent(exception ex)) and handle it the same way you would any other .NET error.
The Silverlight Integration Pack for Enterprise Library apparently provides for a lot more support for error logging too, so that may be worth a look, though I haven't used it myself.

Related

Using elmahr.elmah in winform application

I have recently shown to my team leader the ElmahR Dashboard and now he wants to implement ExceptionsLog with ElmahR in all of our current projects, including those that are Winform Applications, and after many days of searching I can't find a way to add a Winform Application as "ElmahR source".
Does anyone have a clue?
ErrorPostModule in ElmahR.Elmah does not support Winforms apps because it's been written to be an ELMAH module, so it's tied to an ASP.NET lifecycle and cannot be easily adapted. That said, ErrorPostModule does not do anything so magic and can be easily taken as a guideline to write a small "handler" to be used in a Winforms app. Take a look at its code here, what you should do is:
replace what's in the OnInit method, which simply reads configuration bits and attaches the error handler
when an error occurs, handle it like it's done in the SetError method to post it to the right destination reading the configuration parameters you read before. You would reference ELMAH and create an Error instance from your exception, and then use ErrorJson.EncodeString to encode it
You may want to borrow the W3.cs file to simplify the http form compilation.
At some point I might generalize this work and put it in ElmahR.Elmah, but not sure when I'll be able to do it.
I just forked the elmahr source code to work on this, I want to post errors from console applications, so I'm going to remove the dependency on Elmah and create the "error" objects and send them to the dashboard.
It's a work in progress but can be used as starting point for solving your problem.
https://bitbucket.org/rudygt/elmahr
Update: the fork now include full support to post to ElmahR using a ServiceStack endpoint, using json over http. This remove the dependency over the original Elmah to publish errors to the dashboard. The first example is a C# Console Application

How can I detect whether my WPF client application is offline?

In WPF (in code behind) is there a way to detect whether the computer that the client application is running on has access to the internet?
I'm not sure if there is a simple dedicated method / property to check this or whether I would have to try an HttpGet or similar to determine this.
Is there a property or method for this purpose?
-- Lee
It depends on what you consider "access to the internet"
Safest is to add a 'ping' service to the server you wish to connect to and poll that service.
Trying to keep track of the network status is much harder because it is hard to find out whether it is an intranet other type of network.
See this post too
I don't think there's a simple dedicated method or property.
The simplest solution would be to try to connect to your server and then check the error state.

Silverlight, WCF and NotFound, oh my

I know this is a hot topic on StackOverflow, but do bear with me.
We have a Silverlight 3 application talking to a WCF service. Every now and then, calls to the WCF service return a NotFound exception.
I've read pretty much every post on SO and Google on this subject but I can't figure out what's going wrong. Here are some of my findings:
The exception happens on random calls and at random moments. Sometimes a method will work for 50 times and suddently it bugs out. I have a feeling it's related to a timeout, since it's most reproducable if I let the application idle for a while before invoking a call, but this is not always the case - sometimes the one of the first calls in the application fails.
We use the SilverlightFaultBehavior to convert the HTTP error code to 200 and we have plenty of instances where throwing an exception on the serverside actually bubbles up to the client side, so I can confirm this should be working as expected.
Fiddler shows nothing special at the moment the exception occurs. I don't even see the call in question. This worries me, but it might mean that the exception is a result of a call that happened minutes ago and timed out?
Service Trace Viewer shows nothing.
I attach Visual Studio to to Silverlight project and to the WCF services project, set debugging to break on all exceptions (thrown or handled) and it doesn't break (except in Silverlight to tell me about the NotFound problem). This causes me to think that maybe the NotFound is not in response to an exception on the WCF service side?
I really have no idea where to go from here. Any help at all, any pointers or ideas of things to try are welcome.
Here are some thoughts for the points you mentioned:
1) The exception happens on random calls and at random moments - Make sure the data being sent as a return value of method is valid. I had a case when sending an object with some empty properties caused a failure in serialization. I found this out using IIS logs/ Service Trace Logs.
2) So, did you find anything useful?
3) I don't think fiddler can help with this kind of an error.
4) Are you sure about this? Did you set up Trace Logs correctly?
5) You won't find any exceptions that can help you here. The actual exception (when you see 'Not Found' error) is raised while wrapping the message/data from server side or unwrapping message/data on client side.
So, to summarize make sure the data is in correct format (may seem to be correct for you but not WCF, just play with it for a while with different values) and verify the Trace Logging again.
What is a binding of the service? Where is it hosted: IIS or VS Deployment server?
I have seen this problem recently, something was wrong with IIS. It couldn't even open *.svc files.
So here is a plan of activities:
Try to open svc file using http address like http://localhost/MyApp/MyService.svc
If it opens, write a console application and test the service.
If it works, write a silverlight simple application.
I hope this will help.
I fixed this by adding
minFreeMemoryPercentageToActivateService="1"
to Web.config. By default it is
minFreeMemoryPercentageToActivateService="5"
which sometime causes this error.

Logging when application is running as XBAP?

Anybody here has actually implemented any logging strategy when application is running as XBAP ? Any suggestion (as code) as to how to implement a simple strategy base on your experience.
My app in desktop mode actually logs to a log file (rolling log) using integrated asop log4net implementation but in xbap I can't log cause it stores the file in cache (app2.0 or something folder) so I check if browser hosted and dont log since i dont even know if it ever logs...(why same codebase)....if there was a way to push this log to a service like a web service or post error to some endpoint...
My xbap is full trust intranet mode.
I would log to isolated storage and provide a way for users to submit the log back to the server using either a simple PUT/POST with HttpWebRequest or, if you're feeling frisky, via a WCF service.
Keep in mind an XBAP only gets 512k of isolated storage so you may actually want to push those event logs back to the server automatically. Also remember that the XBAP can only speak back to it's origin server, so the service that accepts the log files must run under the same domain.
Here's some quick sample code that shows how to setup a TextWriterTraceListener on top of an IsolatedStorageFileStream at which point you can can just use the standard Trace.Write[XXX] methods to do your logging.
IsolatedStorageFileStream traceFileStream = new IsolatedStorageFileStream("Trace.log", FileMode.OpenOrCreate, FileAccess.Write);
TraceListener traceListener = new TextWriterTraceListener(traceFileStream);
Trace.Listeners.Add(traceListener);
UPDATE
Here is a revised answer due to the revision you've made to your question with more details.
Since you mention you're using log4net in your desktop app we can build upon that dependency you are already comfortable working with as it is entirely possible to continue to use log4net in the XBAP version as well. Log4net does not come with an implementation that will solve this problem out of the box, but it is possible to write an implementation of a log4net IAppender which communicates with WCF.
I took a look at the implementation the other answerer linked to by Joachim Kerschbaumer (all credit due) and it looks like a solid implementation. My first concern was that, in a sample, someone might be logging back to the service on every event and perhaps synchronously, but the implementation actually has support for queuing up a certain number of events and sending them back to the server in batch form. Also, when it does send to the service, it does so using an async invocation of an Action delegate which means it will execute on a thread pool thread and not block the UI. Therefore I would say that implementation is quite solid.
Here's the steps I would take from here:
Download Joachim's WCF appender implementation
Add his project's to your solution.
Reference the WCFAppender project from your XBAP
Configure log4net to use the WCF appender. Now, there are several settings for this logger so I suggest checking out his sample app's config. The most important ones however are QueueSize and FlushLevel. You should set QueueSize high enough so that, based on how much you actually are logging, you won't be chattering with the WCF service too much. If you're just configuring warnings/errors then you can probably set this to something low. If you're configuring with informational then you want to set this a little higher. As far as FlushLevel you should probably just set this to ERROR as this will just guarantee that no matter how big the queue is at the time an error occurs everything will be flushed at the moment an error is logged.
The sample appears to use LINQ2SQL to log to a custom DB inside of the WCF service. You will need to replace this implementation to log to whatever data source best suits your needs.
Now, Joachim's sample is written in a way that's intended to be very easy for someone to download, run and understand very quickly. I would definitely change a couple things about it if I were putting it into a production solution:
Separate the WCF contracts into a separate library which you can share between the client and the server. This would allow you to stop using a Visual Studio service reference in the WCFAppender library and just reference the same contract library for the data types. Likewise, since the contracts would no longer be in the service itself, you would reference the contract library from the service.
I don't know that wsHttpBinding is really necessary here. It comes with a couple more knobs and switches than one probably needs for something as simple as this. I would probably go with the simpler basicHttpBinding and if you wanted to make sure the log data was encrypted over the wire I would just make sure to use HTTPS.
My approach has been to log to a remote service, keyed by a unique user ID or GUID. The overhead isn't very high with the usual async calls.
You can cache messages locally, too, either in RAM or in isolated storage -- perhaps as a backup in case the network isn't accessible.
Be sure to watch for duplicate events within a certain time window. You don't want to log 1,000 copies of the same Exception over a period of a few seconds.
Also, I like to log more than just errors. You can also log performance data, such as how long certain functions take to execute (particularly out-of-process calls), or more detailed data in response to the user explicitly entering into a "debug and report" mode. Checking for calls that take longer than a certain threshold is also useful to help catch regressions and preempt user complaints.
If you are running your XBAP under partial trust, you are only allowed to write to the IsolatedStorage on the client machine. And it's just 512 KB, which you would probably want to use in a more valuable way (than for logging), like for storing user's preferences.
You are not allowed to do any Remoting stuff as well under partial trust, so you can't use log4net RemotingAppender.
Finally, under partial trust XBAP you have WebPermission to talk to the server of your app origin only. I would recommend using a WCF service, like described in this article. We use similar configuration in my current project and it works fine.
Then, basically, on the WCF server side you can do logging to any place appropriate: file, database, etc. You may also want to keep your log4net logging code and try to use one of the wcf log appenders available on the internets (this or this).

Silverlight 2 Webservices

I'm developing a silverlight application that consumes a webservice. Calls to this webservice are made Asynchronously. But when an exception occurs during a procedure of the async call, I get an error on the completed event but i lost my original exceptions information. Independent of what the original exception was, I always get "The remote server returned an error: NotFound" back, with stack that points to "external" code.
Any advice?
When the service throws an exception it's translated to a 40(x) HTTP response that gets handled by the browser before the Silverlight plugin can handle it. To avoid this, wrap your WCF calls in a try/catch block and send exception data back to the client through an HTTP response that can be handled by Silverlight, such as 200. Here's a terrific implementation of this strategy on codeproject:
http://www.codeproject.com/KB/silverlight/SilverlightExceptions.aspx
This happens with any exception in your SL to WCF, sometimes you can find the innerexception with Fiddler2 in the transfered data or you might see the HTTP error code which can give you a hint , other times it's harder to find. This is my big request item for SL 4.0, better WCF debugging.
http://www.fiddler2.com
Follow James Cadd's advice above. Getting more informative error messages will certainly help and, unfortunately, you can't rely on the debugger to generate them for you.
Even if you're not a big fan of unit testing, this is a place where it's more than worthwhile. Constructing a set of tests that will purposefully send your webservice bad data and making sure that you get back informative errors will help set you up to figure out why it's not working with the Silverlight app. Writing these kinds of tests takes a different way of thinking, but it will give you a lot of confidence in your code if you know that you've tried to break the webservice in every possible way and it always gives you back something you can use to trace the problem.

Resources