Virtual events in C#

by Marcel Veldhuizen 11. June 2014 08:06

Yesterday I ran into an interesting (and dangerous) little detail about the C# compiler regarding virtual (field-like) events; they do not behave as you might expect. Consider this code, which I've simplified from a real world example of some refactoring gone wrong:

public abstract class MyClassBase
{
    public virtual event EventHandler<EventArgs> MyEvent;

    public void DoStuff()
    {
        if (MyEvent != null)
        {
            MyEvent(this, EventArgs.Empty);
        }
    }
}

public class MyClassDerived : MyClassBase
{
    public override event EventHandler<EventArgs> MyEvent;
}

To my surprise, when one subscribes to MyEvent, it will never be called:

More...

Tags: , , ,

Programming | .NET

XapReduce 1.1

by Marcel Veldhuizen 1. June 2014 14:06

Last December I created a small utility to reduce the size of XAP files for modular Silverlight applications. It served my purpose at the time, but more recently I've been using the tool in the context of a new application, which revealed a problem related to localization. In some cases the application could crash because of satellite assemblies that are embedded into the XAP files.

The new version takes satellite assemblies into consideration: they are removed whenever the main assemblies is also removed. There are a small number of other issues that were fixed, like an incorrectly described command line parameter.

More...

Tags: , ,

Programming | Silverlight

XapReduce: Optimizing Modular Silverlight Applications

by Marcel Veldhuizen 15. September 2013 05:30

Even though Silverlight has fallen out of grace with the powers that be, there are still some companies using it today for entertainment or line of business applications. Particularly for that last category, modularity can be a powerful tool in creating a flexible solution.

Over the past few years, I've worked with modular Silverlight applications based on Microsoft Prism. Every module is it's own XAP file, which is loaded on demand by the framework. Over the years, people have also rolled their own lightweight modular applications, also making use of XAP files. This article is about a specific problem with building these types of applications: optimization of the total application download size.

More...

Tags: , ,

Programming | Silverlight

Advanced base constructor calls in C#

by Marcel Veldhuizen 5. September 2013 14:00

Every now and then you run into a situation where you wish your programming language of choice was just a tad more flexible than it actually is. For example, constructors in C# always have to directly call one of the base type constructors as the first thing they do (or do they? keep reading).

Yesterday I ran into a situation where I would like my derived class to always use the same implementation* for a certain injectable dependency. No problem:

public class FooBase
{
    public FooBase(IDependency dependency)    { /* stuff here */ }
}

public class MyFoo
{
    public MyFoo() : base(new MyDependency()) { }
}

The dependency is created on the fly and my base class constructor is happy. However, my derived class also needed to make use of this dependency and my base class does not expose any property or field for me to access it. So before calling the base constructor, I would have liked to store a reference to this newly created MyDependency object.

More...

Tags: ,

Programming | .NET

The CAPTCHA reinvented: PlayThru

by Marcel Veldhuizen 14. August 2013 00:42

The evolution of spam

Many blog owners will be familiar with one particular pest on the internet: spam bots. This blog is no exception, but I was determined to keep my pages clear of digital graffiti even when I don't have much time to post regularly.

Fortunately there are some nice and unobtrusive countermeasures available, like Akismet. They work pretty much like the spam detection for your email. For some time, this used to be enough to keep the spam bots at bay, but spammers are constantly changing their angle of attack. Many comments that are posted nowadays don't even contain any links anymore. With some luck, they can even pass for a comment from an interested reader. I'm not completely sure how exactly this helps the spammer, but no doubt they are trying to raise the reputation level of the IP address or email used to post the comment with, so t hey are more likely to pass through filters like Akismet later. In any case, spam filters are not as effective against these messages as they are against something containing one or more actual links.

More...

Tags: ,

Programming | .NET

Updates to the Website

by Marcel Veldhuizen 27. June 2013 04:17

Just a quick note: I've updated the software for this website to BlogEngine.NET 2.8. Not a lot has changed since I've kept my original theme, but it does fix a few issues.

It also means that from now on you'll need to enter a CAPTCHA (provided by reCAPTCHA) in order to post comments. This is unfortunately necessary to stop excessive spamming that has been going for a while now. On BlogEngine 2.7 the reCAPTCHA plugin refused to work properly, but this seems to be fixed now.

If you happen to run into issues trying to post a comment – or anything else – drop me a note using the Contact form or on Twitter (@mveldhui). Also, authenticated users don't need to fill in a CAPTCHA for the moment, so you could also create an account. Thanks!

Tags:

General

Preserving the Stack Trace

by Marcel Veldhuizen 21. February 2013 16:11

Rethrowing Exceptions

Normally, if you have to rethrow and existing exception in .NET, you should use the throw keyword without any parameters:

try
{
    // Code that can generate exceptions here
}
catch (Exception ex)
{
    // Do some logging or whatever
    throw;
}

Using throw ex; would cause the stack trace of the exception to be lost, in which case we lose some valuable information. However, this only works inside the catch block that caught the exception in the first place.

Sometimes, you need to rethrow the exception at a later point outside the catch block, but of course we want to preserve the stack trace.

More...

Tags: , ,

.NET

Code Golf

by Marcel Veldhuizen 18. February 2013 14:13

Every now and then I just want to do something silly with code, like some code golf. Just for a moment to forget about best practices and write the shortest possible program to solve a problem.

Today I happened to run into one of those projects on my hard disk, which happened to be in C# (it's not exactly the tersest language there is, so it may be a little unusual). It's an exercise from an old Google Code Jam. The problem to be solved and some solutions can be found in this StackOverflow question, including my own. It measures 398 characters after removing insignificant whitespace, the longest solution between a host of different languages.

Today I realized that there was a slightly shorter solution than the one below, but perhaps you can come up with something even better?

More...

Tags: , ,

Coding4Fun

Unity lifetime management for IDisposable, part 3

by Marcel Veldhuizen 17. February 2013 07:59

Contents:

Limitations

In hindsight to the created solution, there is an issue that cannot be addressed in this way: When a consumer fails to call Teardown properly at the right time for constructed objects, the DisposingSharedLifetimeManager will not behave as expected. For some, this may be a big issue, because it may not be very customary to bother to call Teardown when using Unity, precisely because it usually does nothing useful anyway.

Alternative Solutions Using Unity

One alternative is to use a wrapper of sorts and register that in the container instead. The usage would look something like this:

More...

Tags: , ,

.NET | Silverlight

Unity lifetime management for IDisposable, part 2

by Marcel Veldhuizen 16. February 2013 13:25

Contents:

Two New Lifetime Managers

Having explained the issue, how can we solve it?

Before starting, I should mention that my implementation is based on previous work by Rory Primrose, who wrote an extension that changes the behavior of the TransientLifetimeManager in order to dispose of objects. He does an excellent job of explaining some of the rationale behind his implementation, so be sure to read his article.

I've placed the complete source code for my article (including some quick unit tests) on GitHub.

My approach is a little different: I did not want to change the default behavior of Unity, so instead I defined two new lifetime managers to explicitly set the desired behavior with: DisposingTransientLifetimeManager and DisposingSharedLifetimeManager.

DisposingTransientLifetimeManager

This lifetime manager behaves pretty much like the built-in TransientLifetimeManager; every time a new object is created. The only difference is, that on Teardown of any object, we will call Dispose() on objects that were created as a result of the original build-up operation (provided they are using this lifetime manager, of course).

More...

Tags: , ,

.NET | Silverlight

Marcel Veldhuizen

Software Architect by profession, mostly focused on Microsoft .NET technology.

Metal enthusiast; I love going to concerts :)

 

RecentPosts

Recent Tweets

Note: For Customization and Configuration, CheckOut Recent Tweets Documentation