Catching unhandled exceptions

August 18th, 2010 — 07:46 am

As a rule, in every application I write, I always implement both the Application.ThreadException and AppDomain.UnhandledException events, to catch exceptions which were not caught by a try..catch block.

There are three reasons behind this:

  1. Present a custom failure message to the user (something like Twitter’s fail whale message) instead of the default ugly (and unclear) error dialog, i.e. “XXX.exe has encountered a problem and needs to close. We are sorry for the inconvenience.
  2. Log the exception so it may be resolved in future releases.
  3. Although it’s not considered as a good practice, some exception may be ignored so the application may keep on running, instead of crashing.

However, I recently came across a case in which the application crashed ungracefully although I implemented those methods. Some research led to me to realize my code is not as full-proof as I thought it was.

The code below will crash your application even if you hooked the two events mentioned above. The UnhandledException event WILL be executed, but afterwards the application will crash anyway, presenting Microsoft’s default error dialog:

private void MyThreadProc()
{
    throw new Exception(”Bad wolf”);
}

private void ClickMe()
{
    Thread myThread = new Thread(new ThreadStart(MyThreadProc));
    myThread.Start();
}

Turns out I was not aware that during the transition between Framework 1.1 and 2.0 (and beyond), Microsoft changed the way the CLR deals with exception that don’t occurs in the application’s main thread, meaning that if you want the application to remain alive even after an external thread exception, you need to tell the CLR to revert to the Framework 1.1 exception handling mechanism, by adding this section to your app.config file:

<configuration
  <
runtime

    <
legacyUnhandledExceptionPolicy enabled=”1″
/> 
  <runtime
>
<configuration>

Again, not a best practice, but if you can’t afford to having

Another footnote is related to using the Application.SetUnhandledExceptionModeMethod. If you try setting it from a Winform application running inside the Visual Studio, you’ll get the following error: “Application exception mode cannot be changed once any Controls are created in the application“, even if that’s the first line of code in the application. This is because the Visual Studio runs a host environment prior to running your application. The methods works just fine when you run it from outside the Visual Studio.

Comment » | Programming, Winforms

So you got over a million followers on Twitter

September 20th, 2009 — 04:22 am

( * Originally posted as “The Million Followers Fallacy” on “Pravda on Media and Tech” )

Twitter is getting more and more attention from “old media” lately. Whether it’s a news-story mentioning Twitter, a Twitter competition between a celebrities, or using Twitter to gather reports on the Iran elections, the average person sees the word “Twitter” more and more often lately.

But with the Twitter rush a new bubble seems to be forming.

Remember the days of the 2000 Dot-Com bubble, in which every site displaying a million page-views could raise money as though it had already become profitable?
I feel we are repeating the same mistake, only in social media.

The new fashion among some Twitter users, individuals or companies, is to brag about the number of “followers” they have for their Twitter account, or the number of followers their employees have. Encouraged by this there is a host on new “services”, promising user to boost their followers count for a small fee. There is also a new buzz-word: “Reach”. Those self-proclaimed Twitter experts will use tools like TwitterAnalyzer to show others that their Tweets are supposedly read by even more people than their Twitter followers, using a repeat publication (”Retweets”).

And there lies the illusion.


The number of Twitter followers (or reach) is usually meaningless

Twitter usage is based on the magic principle of following/followers. You follow other users that may interest you, and being followed in turn by others who find your updates interesting.
But suppose you just opened an account on Twitter - how do you get followers?

If you are a celebrity like Ashton Kutcher, have a TV show like Opera, a successful blogger like Robert Scoble, or simply a leading TV channel like CNN, than you have it easy - you just need to mention your new Twitter account and the masses will follow you.
But you need to be well-known to the public prior to opening a Twitter account.

But what if you are an average Joe, looking to become a superstar on Twitter?
You can use an unwritten rule, saying that if someone is following you, it’s polite to follow that person back. Twitter users interested in inflating the number of followers they have simply need to follow thousands of others, hoping those others will follow them back.
The less ethical among them wait for another to follow, and than stop following that person.
To sum it up: such a user has 20000 followers, not because he is THAT interesting to them, but simply out of politeness.

The principle behind “Reach” is similar: if you wrote an update, and one of your 20000 followers repeats it, and that person has another 10000 followers (not shared by you), your message could have been read by 30000 folks. But again, people exploit the technology, and open multiple accounts, each of them having thousands of followers (as previously mentioned), and than repeat that message from all their accounts. Twitter defines this as Spam.

In addition to all that, there is the face that 10-50% of all followers are either dormant/inactive accounts, bots, spammers, or other irrelevant accounts.

Million follower don’t actually read your updates

And suppose Mr. Kutcher writes something on his Twitter account, does that mean all of his million (plus) followers actually read it? Of course not!

On my personal Twitter account I follow only about 200 people. Each one publishes a number of updates during the day, reaching thousands of updates each day. Since I’m not sitting glued to the screen, when I check for updates I usually see only updates from the past 30-60 minutes. Written something when I wasn’t checking for updates? I’ll probably miss your update.

To put it differently, if you wrote an update and have a reach of 100000 users, it’s 100000 of users with the potential to read your update, but most likely most of them will never see it.

So don’t be tempted by false promises from Twitter “experts”. We are light years away from a reliable, measurable advertising model on Twitter.

Comment » | Technology

Looking back on social media and myself

August 20th, 2009 — 01:40 pm

More than 2 years ago, Ayelet Noff (AKA Blonde 2.0)  wrote a post on social networks vs. blogs (with Myspace as an example for a social network). She claimed there is room for both in the life of a blogger.

I disagreed with her:

“Blogging takes effort, time and at least a little talent.
MySpace requires choosing a template.
Blogging is about sharing your view, opinions and (some times) personal life with your readers.
MySpace is about sharing links to your “friends”, meaning other pages in which the only meaningful data is links to more “friends” and so on.
(Why do I use quotes? ask Samy)

If a blog is the equivalent of an autobiography, MySpace page is the equivalent of a phone book.”

And

“I think that with some social networks (MySpace again) you need to do most of the work OUTSIDE the site by mails, IM, phone, etc.
In other words, the SN site itself gives very few tools to help you make new friends, while a blog gives you information on the writer on it’s own.

Bloggers must invest more effort, while people on social networks can do it.
The result is that the chance of encountering a social network page containing meaningfull information is lower.
Blogging has a much higher entry bar than most social networks.”

Funny reading it now.

I can’t image my life today without social networks. I’m still not using Myspace, but constantly use Facebook and Twitter. I have met many fascinating people through social networks, went to events I would have never heard of without them, and learned a lot using them.

In fact, using social networks to that extent also affected my writing, as after channeling creativity using Twitter I’m often left without any for a new blog post. On the other hand, I have recently wrote a post on my Hebrew blog, posted on Twitter - and got a tremendous response, as people liked the content and promoted it on their own.

In fact, the focus of the problem today has shifted from “Social networks vs. blogs” to large vs. small communities on social networks, but that’s a topic for another post.

4 comments » | Blogging

Rotating Graphics

March 29th, 2009 — 10:12 am

This is a fairly simple issue, but I had to rotate a drawn shape recently.

Initial searches led me to the TranslateTransform method, but I learned there is a simpler way to achieve this, using the RotateAt method of the Matrix class:

Graphics g = this.CreateGraphics(); //get a graphics object for the form
g.DrawRectangle(new Pen(Color.Black), 50, 50, 100, 100); //normal drawingMatrix oldMatrix = g.Transform; //save the old Matrix objectMatrix myMatrix = new Matrix(); //create a new Matrix object

myMatrix.RotateAt(15, new PointF(200.0f, 200.0f)); //rotate the matrix in relation to a specific point (200, 200) by 15 degrees
g.Transform = myMatrix; //assign the new (rotated) matrix to the graphics object
g.DrawRectangle(new Pen(Color.Black), 100, 100, 100, 100); //perform the drawing

g.Transform = oldMatrix; //restore the original matrix

The result:

Comment » | Useful .Net classes

The role of Clients and Services in WCF

February 13th, 2009 — 11:08 am

I have seen this question in Stackoverflow.com, and I want to answer it here:

Greetings readers! So I am trying to develop a client server system.. Since I have not designed a client server system before, I thought that I would post a question and see what the experts here have to say.

Requirements: .NET 3.5 WCF minimum of 2 computers, Master and Slave.

The use case is a testing environment, where the slave runs tests at the request of the master.

Questions: I would prefer that the slaves locate and connect to the master, and then the master takes control and is the one that initiates the tests to be run. The slave also makes progress reports: new test data, unexpected events, etc.

The part that I am confused about is that if the slave initiates contact with the master, doesn’t that make him the master?

Does this mean that I need servicehosts on both slave and master so that they can initiate activity?

Most channels in WCF are basically a one-way communication, in a sense only one side (WCF Client) can initiate requests - the other side (WCF Service) cannot initiate calls, only respond to them.

There are two possible solutions to the problem presented here:

  1. The tester slave (WCF client) initiates the connection to the tester master (WCF service). Afterwards it polls the tester master periodically to receives a list of tests to run.
  2. The tester slave (as a WCF client) initiates the connection to the tester master (as a WCF service). In response, the tester master (now as a WCF client) initiates a second connection to the tester client (now as a WCF service). The tester master than sends tests requests to the tester slave.

Both architectural approaches can be implemented regardless of the channel type, MSMQ, Tcp/Ip or otherwise.

2 comments » | Uncategorized

Garbage collector, gen2 and memory abuse

January 28th, 2009 — 01:43 pm

There are limits most application developers never encounter. One of them is the 2GB memory limit for applications running on a 32bit operating system.

But what happens if your application is a memory consumer (and most GIS applications are)?

You may find out your application tends to crash and burn once reaching a memory signature of a little over 1GB.

It’s a common knowledge for developers (I hope) that a useful way to measure application’s true memory consumption is using the Task manager’s “VM Size” column (as the “Mem Usage” column only indicates the size of the application’s Working Set). So why does the application crash when supposedly there is still plenty of free memory?

There are 2 possible answers:

  1. Although a certain size of memory is allocated to the application, fragmentation to the memory may cause the application to actually consume more than that. This may also be related to the GC behavior in relation to 2nd generation objects, which I’ll discuss later.
  2. The VM Size column does not represent the actual Virtual address space allocated to the application, which is limited to 2-3GB on a 32bit OS. In addition to the allocated memory the OS may have designated addition shared memory (shared with other applications, but still counts towards the 2GB limit). To view the actual size of memory allocated by the OS to the application, use the Perfmon.exe tool’s Virtual Size counter:

The .Net Garbage Collector and 2nd generation (gen2) collections

The GC algorithm divides the allocated objects to 3 generations (0-2), when generation 0 objects are retrieved most frequently and “live” for the shortest amount of time. Generation 1 objects are collected less frequently and generation 2 collections are truely a rare occasion.

But when does the GC collects generation 2 allocations (”full” collection)? What triggers such a collection?

Surprisingly I found very little information of this subject, but the information I did find, combined with experimentation led to the conclusion such collection occurs when the overall system is low on physical memory.

Now, let’s consider the implications for a 4GB computer running a 32bit OS. While the gen2 heap may inflate over time (especially considering large objects are also collected only in gen2 collections), the GC will never trigger as a single application can never consume the entire amount of memory on the computer (being limited to 2GB). However, this may lead to a memory leak and eventually crashing the application (once it’s virtual address space reaches 2GB).

The solution? Call the GC.Collect() method yourself to trigger a full collection.

1 comment » | Programming, Windows

Juval Lowy and .NET Service Bus

January 12th, 2009 — 01:21 pm

I have recently been to an Israeli user group meeting in which iDesign’s Juval Lowy gave a lecture about the new Azure .Net Service Bus for web services written in WCF.

Basically a service bus is a router, similar to the one you use in your office network. Instead of needing to update the configuration for multiple clients each time a service they are connected to is moved to a new location or changes channel, all clients/services connect to a central hub. In this case the service bus is located online, somewhere on Microsoft servers.

Here is what the meeting’s page says about the lecture:

The .NET services bus is part of the new Microsoft Cloud Computing Windows Azure initiative, and arguably, it is the most accessible, ready to use, powerful, and needed piece. The service bus allows clients to connects to services across any machine, network, firewall, NAT, routers, load balancers, virtualization, IP and DNS as if they were part of the same local network, and doing all that without compromising on the programming model or security. The service bus also supports callbacks, event publishing, authentication and authorization and doing all that in a WCF-friendly manner. This session will present the service bus programming model, how to configure and administer service bus solutions, working with the dedicated relay bindings including the available communication modes, relying on authentication in the cloud for local services and the various authentication options, and how to provide for end-to-end security through the relay service. You will also see some advanced WCF programming techniques, original helper classes, productivity-enhancing utilities and tools, as well as discussion of design best practices and pitfalls.

Although Juval clearly know a lot on the subject, and apparently is currently doing a tour lecture on the subject (at least in Israel and Belgium), I have to say the talk was not very interesting for experienced WCF developers. This is due to the fact the interface is almost identical to that of a simple WCF service, therefor I kept getting a feeling of “been there, done that“. It’s very easy to work the .NET service bus.

The .NET service bus supports both TCP/IP and HTTP based connections (highlight of the lecture: “to add WS support just add an ass“), and allows both connectivity through the cloud or P2P (after negotiation). There is a limited usage to SSL transport level security, something that alarms me a bit, as this is the best performance/security ratio option in WCF.

I do have to wonder regarding the usability of this platform. Many companies I know moved to SOA architecture, splitting central servers to many services. Such systems need a service bus residing inside the local network due to two reasons:

  1. Local network is more secure. Although Mr. Lowy waved his hands and replied “message level security is NP complete” to a question on the subject, I doubt IT managers or security officers in large firms would accept that.
  2. Local network is faster. Although a large downwards bandwidth is easily obtained, for a true 2 way communication you need a decent outgoing bandwidth (unlike ADSL lines, for example), and that’s not cheap.

There are local alternatives, both commercial (Microsoft Biztalk server) and open source (Udi Dahan’s NServiceBus).

I guess only time will tell if this new technology is successful.

5 comments » | Programming, Technology, WCF

Nach oben

« Previous Entries