deft flux

A portal into the creative workings of David Meyer

Safely invoking event delegates

Yesterday, my friend and I had an interesting conversation.  He was venting about the code one of his co-workers wrote which caused a problem he spent some time tracking down.  Here's the gist of it:

void RaiseEvent(EventArgs e) { Event(this, e); }

Now most .NET developers should immediately notice what's wrong here.  I certainly hope they do.  What if Event has not been subscribed to?  Then it is null, and invoking it will cause a NullReferenceException.  So this is how I have always invoked event delegates:

if (Event != null) { Event(null, e); }

But one thing my friend pointed out, which was actually new to me, is that the above code is actually not thread-safe, because another thread can unsubscribe from Event after the check for null and before the invocation.  So to make it thread safe, you would first copy the delegate reference to a local variable:

EventHandler handler = Event; if (handler != null) { handler(this, e); }

Now I thought, "This is a lot of code to write just to raise an event.  How can I make this shorter?"  So thanks to C# 3.0 extension methods and lambda expressions, I was able to reduce it to this:

Event.SafeInvoke(d => d(this, e));

Here's the extension method:

public static void SafeInvoke<T>(this T obj, Action<T> action) where T : class { if (obj != null) { action(obj); } }

This accomplishes both objectives: 1) Copy the delegate reference.  This is implicitly done when it is passed as a method parameter.  And 2) Check the delegate for null.  Now I know calling Event.SafeInvoke if Event is null looks a little odd, because you would think it would cause a NullReferenceException, but this is actually not the case with extension methods.  You can call an extension method on null.  This is because the compiler translates this to:

SafeInvoke(Event, d => d(this, e));

Now, unfortunately, you cannot set a restraint on generic types to restrict them to the Enum or Delegate types.  (This makes absolutely no sense to me, I think you should be able to.)  So the above extension method applies to all reference types.  At first I was afraid this would clutter the IntelliSense for non-delegate types, but actually, this extension method would be useful for any reference type.  What if, for instance, you want to call a method on an object but only if it isn't null?

obj.SafeInvoke(o => o.MyMethod());

And the best part is that this will also make the check for null thread-safe if the object in question has a greater scope than a local variable!  So, to wrap up this post, here are all the extension methods I wrote to support both return values and dispatching to another thread (feel free to plagiarize!):

public static void SafeInvoke<T>(this T obj, Action<T> action) where T : class { if (obj != null) { action(obj); } } public static TResult SafeInvoke<T, TResult>(this T obj, Func<T, TResult> func) where T : class where TResult : class { return obj.SafeInvoke(func, null); } public static TResult SafeInvoke<T, TResult>(this T obj, Func<T, TResult> func, TResult defaultResult) where T : class { TResult result = defaultResult; if (obj != null) { result = func(obj); } return result; } public static void SafeDispatch<T>(this T obj, Action<T> action) { if (obj != null) { action.BeginInvoke(obj, null, null); } }

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by deftflux on Monday, August 11, 2008 9:49 AM
Permalink | Comments (4) | Post RSSRSS comment feed

Duck typing project under development

It has been quite some time since the last release...  (10 months to be precise...)  But a good friend of mine is now onboard and we're resuming development.  We have some pretty cool changes in store, and as always, suggestions are welcome.

We will be tying some loose ends for version 1.0 and rolling in some new features like "loose" duck casting where casting will always succeed, it will simply throw an exception if a member is called that is not implemented, which will more closely resemble how duck typing is implemented in most dynamic languages.  Then we'll be working on 2.0 which will include a name change to something along the lines of "dynamic typing" instead of "duck typing" to reflect the implementation of more dynamic typing concepts than just duck typing.  2.0 will also add some .NET 3.5 features like extension methods.

But I've only scratched the surface...  Just thought I'd give everybody an update!

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by deftflux on Monday, July 21, 2008 10:33 AM
Permalink | Comments (4) | Post RSSRSS comment feed

Safe execution or easier debugging?

I'm talking about exceptions here.  Which is better, avoiding throwing exceptions as much as possible by trying to safely recover from errors, or throwing exceptions that will contain useful information for debugging purposes?  I ran into this issue today...

The company I work for uses a program called Fourth Shift.  It comes with managed libraries for client access in .NET.  I am using a feature called impersonation, whereby transactions can be executed as if a different user was logged in.  There are a few things you have to do in order for this to work:

  • Grant the logged in user permission to impersonate a given user.
  • Enable impersonation when connecting the client.
  • Supply a non-null impersonation user name when processing a transaction.

I had to figure all this out because the developers of the client library decided to go with safe execution.  Here's what will happen if the above conditions are not met:

  • If the user does not have permission to impersonate the given user, the transaction will proceed normally without impersonation.  No exception will be thrown.
  • If impersonation is not enabled but a non-null impersonation user name is supplied, the transaction will proceed normally without impersonation.  No exception will be thrown.

This behavior is about as useful for debugging as the "Failed for some reason" exception message I ranted about in an earlier post, which involved the same client library I might add.  All I knew was that for some reason impersonation was not taking place.  In any case, here is the behavior I would normally expect from a .NET class library:

  • If the user does not have permission to impersonate the given user, an exception is thrown indicating this.
  • If impersonation is not enabled but a non-null impersonation user name is supplied, an exception is thrown indicating this.

Now sure, this would help debugging immensely, but won't it make the program less stable?  Well, in the case of the latter, no.  Whether or not impersonation is enabled is hard-coded and will not change at run-time.  It will either always throw an exception (not work at all) or never throw one (always work).  In the case of the former, do we want the transaction to succeed if the user does not have permission to impersonate?  Sure, if they don't, the program will fail, but at least we'll know exactly why and it's a no-brainer to fix.  Another thing to consider is security.  If impersonation does not take place, the transaction will be executed under the security context of the logged in user, which in this case, most likely has more security rights than the user that should be impersonated.

So in this case, I would say throwing exceptions would be a better approach.  But is it always?  Or is this one of those trade-offs like high cohesion vs. low coupling that needs to be weighed in every design?  Or is there a way to have both safe execution and easy debugging?

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Development
Posted by deftflux on Friday, May 09, 2008 8:50 AM
Permalink | Comments (1) | Post RSSRSS comment feed

My Take on Vista

There was a lot of negative hype surrounding Vista during its development.  It seemed that I heard nothing but bad things about it.  So naturally, I wasn't very excited for its release.  But being impartial as I am, I was willing to give it a chance.  So I asked some people who have used Vista some simple questions:  What advantage does Vista have over XP?  What are the new features besides the spiffy graphics?  The fact is that no one could give me a straight answer.  So for me, it wasn't worth spending that much money for something that really didn't seem to have any benefit.

Well, being an IT professional, I managed to get my hands on a free copy of Vista Ultimate.  Now that cost was not a factor, I installed it on my laptop.  Just as with XP SP2, I had to make numerous tweaks to get the interface right, a new one for Vista being disabling the annoying and useless "User Account Control", of course.  Besides that, I had no problems with hardware compatibility or anything else.  In fact, I made quite a surprising discovery...

Vista is fast.  I thought the extra graphical effects would slow down the interface, but in fact, it's significantly more responsive.  Programs load and close much faster.  I've even experienced faster file transfer rates over my home network.

Microsoft just might have made a believer out of me.  And if you think about it, it makes sense.  XP has been around for over 6 years, and has since been hacked to pieces and bloated with thousands of updates.  Vista seems fresh and light-weight in comparison, with many of its sub-systems rewritten to work well with modern hardware.

So why all the fuss?  Do people not like change?  Are they afraid they won't be able to do as many illegal things anymore?  Are they upset that Vista won't work with their ancient hardware?  Welcome to the world of computers.  Things change.  Get with the program and upgrade your stone-age Pentium.

I used to agree with people who criticize Microsoft's business tactics.  What I realized, though, is that all of Microsoft's competitors are doing all the same things, and nobody points the finger at them and complains.  Microsoft gets picked on because they're the biggest.  I, for one, do not use Microsoft's products because I am somehow conned into it or because it is the most popular standard.  For instance, I used Java and IBM WebSphere and Eclipse for quite some time at one job I had.  Yet, the reason I prefer .NET, C#, and Visual Studio is because they are, in my opinion and for very specific reasons, better.  So yes, Microsoft is a formidable foe for competitors because they make really, really good software, and Vista is no exception.

So in conclusion, don't knock Vista until you've tried it.

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:
Categories: General | Development
Posted by deftflux on Tuesday, April 22, 2008 2:48 PM
Permalink | Comments (1) | Post RSSRSS comment feed

Do I really have to restart my computer?

Come on, people, seriously.  You'd think that since Windows became a stand-alone operating system starting with Windows 95 some 13 years ago, they would have figured this out by now.  Why haven't any of the Windows releases since then incorporated being able to reconfigure the operating system without ever restarting?

Now it used to be that the whole "You have to restart your computer for these changes to take effect" thing was just a mild nuisance.  Unless it involved drivers, you could just click "No, I'll restart my computer later" and what do you know?  You don't even have to restart your computer half the time.

Has this improved at all in recent years?  No, in fact, it has gotten worse!  There are now artificial measures intentionally put in place to force users to restart.  For instance, after installing Windows updates, you will be prompted every 10 minutes or so that you have to restart until you do.  Or when a program is installed, it will not let you install another program until your computer is restarted.

Device drivers aside, as a developer for the past 10 years, I have never encountered a scenario where any installation step involved in installing a program could not possibly be done without restarting.  Why are users still being required to restart?  Is it because developers are too lazy to figure out how to enable the program to function without restarting?  Is it a "just in case" measure to reduce technical support calls?  Or maybe it has just become tradition.  In any case:

If your installation process requires restarting, your installation process was poorly designed and needs to be reworked.

This is, of course, unless restarting is necessitated by some external factor, in which case, said external factor (e.g. Windows) is a product of a poor design and I hope the designers (e.g. Microsoft) gets grilled for their gross negligence until they correct it.

Home users may simply find this annoying, but when you talk about servers, many of them must be kept up during certain hours, which means that some poor technician has to come in early, stay late, or spend part of his weekend performing updates to the servers, or else the company has to suffer a loss in productivity or even business during the time that the server is being restarted.  This is unacceptable when there is no reason why installing a program cannot be done without restarting.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General | Development
Posted by deftflux on Tuesday, April 15, 2008 12:53 PM
Permalink | Comments (0) | Post RSSRSS comment feed

T-Mobile Wing (HTC Atlas) hacking - controlling the LEDs

Lately, I've been customizing my Wing.  I posted a topic on XDA-Developers.com regarding my most recent obsession with controlling the LEDs on it.  If you own a Wing/Atlas or similar HTC device, check it out:

http://forum.xda-developers.com/showthread.php?p=2059151

Currently rated 2.0 by 1 people

  • Currently 2/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Development
Posted by deftflux on Wednesday, March 26, 2008 2:01 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Easily defeatable CAPTCHAs

For those who don't know what a CAPTCHA is, it's a Completely Automated Public Turing test to tell Computers and Humans Apart.  It's those images that web sites sometimes display that contain distored characters or words that you are required to enter as text in order to verify that you are, in fact, human and not a computer program.

I've always liked the idea behind CAPTCHA, being very anti-SPAM myself.  But what constantly bugs me are the dozens of different kinds of CAPTCHAs I encounter that seem so easily defeatable.  For one thing, they make the text a totally different color from the background so that it could easily be isolated from it.  Second, they usually barely distort the text.  You know, I haven't the slightest clue how OCR (optical character recognition) works, but I bet I could write from scratch a program that could defeat 90% of the CAPTCHAs I've seen on the web.  But instead of egotistically trying to prove my programming prowess, I decided to design my idea of what an undefeatable CAPTCHA would be.  So I just quickly wrote up a rough draft.

Basically, I would think that a program to defeat CAPTCHAs would try to find patterns in the image that resemble characters, right?  My idea is that a CAPTCHA should not have any patterns or follow any rules that could be programmed against.  It should be completely random.  But how could even a human recognize the image if it were completely random?  Probability. 

The idea is that every pixel in the image is a random color; however, the random number generator is designed such that there is a slightly higher probability of the random color being darker where the text is.  So any color can appear anywhere in the image, but where the text is, it's a little more likely to be a dark color, even though it could even still be white there.  Humans can easily pick up on this, because our advanced brains are infinitely more intelligent than any software ever could be.  In fact, the entire makeup of our brain is about making connections even between seemingly unrelated things, whereas computers have to deal with descrete values.

Ok, so I guess this algorithm technically creates a pattern.  But it's the most random, least pattern-like pattern I could come up with.  Anyways, I bet you're just dying to see an image of what my algorithm generated...  Here it is:

It can easily be fine-tuned.  Plus this is a draft.  I would definitely add some distortion of the text before applying the color distortion.  In any case, it may seem easy to read or even defeatable, but look at it extremely close.  No two pixels next to each other are the same color, there are equally dark pixels in the background as the foreground and equally light pixels in the foreground as the background.

Please, I encourage you to open this image in your favorite graphics program and try to isolate the text from the static.  Try using software to defeat this CAPTCHA.  I'm curious to see how easily this can be defeated.

Comments?  Criticism?

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:
Categories: General | Development
Posted by deftflux on Thursday, January 31, 2008 7:43 AM
Permalink | Comments (2) | Post RSSRSS comment feed

Comments are working now

Comments mysteriously started working now.  Huh.  Please e-mail me if you have any trouble leaving a comment now.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General
Posted by deftflux on Friday, October 19, 2007 10:37 AM
Permalink | Comments (3) | Post RSSRSS comment feed

New band page up on MySpace

I just put up a band page on MySpace to host my music.  There is currently one track up.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General | Music
Posted by deftflux on Friday, October 19, 2007 8:30 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Trick to refer to objects of generic types

I realized something while I was working on a project.  I thought it might be a useful idea, so I thought I'd write a post.

To help clarify the following, I will be using the terminology for generics as it appears in System.Reflection.  List<T> is an example of a "generic type definition", because its type arguments have not been specified.  Whereas List<string> is a "generic type".  T is a "type parameter" and string is a "type argument".

In .NET (C#), while a generic type definition can be referenced using typeof (e.g. typeof(List<>)) in order to get a Type object, you cannot declare a variable with a generic type definition type.  This is because the generic type definition isn't really a type in .NET, it's more of a template for a type.  Furthermore, generic types from the same definition do not automatically inherit from a common base class.  This presents a problem when you want to be able to reference an object of a generic type without knowing its type arguments.

I ran into this problem yesterday.  I realized, however, that since types can be distinguished by how many type parameters they have, a type that is not generic and a generic type definition with one or more type arguments can both be defined without causing a naming conflict.  This can commonly be seen with the old System.Collections classes and interfaces and the new generic System.Collection.Generic types (e.g. Stack vs. Stack<T>).

So I performed a little trick taking advantage of this in order to solve the above problem.  Here's some example code:

public abstract class TransactionField
{
    
}

public class TransactionField<T> : TransactionField
{
    private T m_Value;
    
    public T Value { get { return m_Value; } set { m_Value = value; } }
}
 

Now an object of any TransactionField<T> type can be referenced as simply TransactionField.  This is great for referencing, but what about that Value property?  What if you need to be able to access that property for any TransactionField<T> object?  Check this out:

public abstract class TransactionField
{
    public object Value { get { return _Value; } set { _Value = value; } }
    
    protected abstract object _Value { getset; }
}

public class TransactionField<T> : TransactionField
{
    private T m_Value;
    
    public new T Value { get { return m_Value; } set { m_Value = value; } }
    
    protected override object _Value { get { return Value; } set { Value = (T)value; } }
}
 

It gets a little confusing with the naming.  But basically, TransactionField defines an protected abstract property _Value so that it can access the value stored in types derived from it.  It also defines a public property Value which provides public access to the value stored in the derived type via _Value.  Finally, TransactionField<T> defines a new property with the same name Value except this one uses the type argument instead of object.  

Now at this point, you might be wondering what the point of using generics at all in this scenario is.  Well, TransactionField<T> replaces the Value property with a typesafe one.  When you deal with the generic type, you won't need to cast any values.  This approach is the best of both worlds.  The object can be dealt with as an object of a generic type or a non-generic type, depending on what is needed for the code that is using the object.

Currently rated 3.8 by 5 people

  • Currently 3.8/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Development
Posted by deftflux on Thursday, October 11, 2007 10:45 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Some descriptive exception messages, please?

Today I encountered an exception thrown from a class library I was using that had an interesting exception message.  Actually, the only thing interesting about it was how completely useless it was.  Without revealing the identity of the class library, I will paraphrase.  I was calling a method called "Initialize" on an object of a class, which I will call MyClass for ambiguity.  The exception message was...

"Failed to initialize MyClass"

Ok, let's examine this for a moment.  "Initialize" is the name of the method and, thus, what the method is supposed to do, which is what this is saying it failed to do.  Let me illustrate how meaningless this is by saying it with a slightly different wording:

"The method you just called failed to do what it is supposed to do to the object it was called on because of an error that we are going to tell you nothing about.  In fact, the original exception would have given you some useful information to go off of, but we decided to catch this exception and throw you this useless one instead, without even referencing the original as the inner exception we might add, because we enjoy frustrating our customers.  It's all part of our elaborate plan to make you contact us to help you solve the issue.  This way we appear needed to our employer even though we are lazy and continue to write crappy code.  We don't care that this wastes your time and contributes towards delaying the very time-critical project you are trying to finish while your boss rides you every day about where you are on it.  All we care about is keeping our jobs since we haven't the slightest clue what we're doing here."

The person I talked to today was lucky that I'm generally a nice guy, otherwise her day might have turned real ugly.  But, fortunately, it didn't waste too much time--if half the day doesn't count as too much time, that is.  It turns out the problem was quite simple.  The error could have easily been summarized in an exception message like "The given system name was not found on the given server."  Now would that have been so hard for the programmer who wrote that method to type that instead of "Failed for some reason"?

So next time you find yourself starting a line of code with "throw new", please, for the sake of programmers everywhere, at least say something about what the problem is, and include the original exception, if any, as the inner exception.

P.S. Comments are still not working...  Sorry.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Development
Posted by deftflux on Tuesday, October 09, 2007 2:27 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Duck Typing version 0.9.30 released

Binaries: DuckTyping_0.9.30.zip (125.01 kb)
Source: DuckTyping_0.9.30_Source.zip (36.86 kb)

The static page explaining the duck typing project can be found here.

  • Fixed: A stack overflow no longer occurs when a duck casting conversion infers the same duck casting conversion.
  • Added: Some support for generic methods, but do not expect it to be bug-free.  I had to release it in this state so that the above bug fix would be released.  It should not affect other kinds of class members, though.

Sorry, but comments still don't work...  I'm working on it...

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by deftflux on Monday, September 10, 2007 5:29 AM
Permalink | Comments (3) | Post RSSRSS comment feed

Comments not working

I have become aware that comments are not working on this site.  I was hoping to fix this quickly, but unfortunately, it may involve switching hosting providers.  In any case, I will post as soon as this is working.  Sorry for the inconvenience.

Though I haven't posted in a while since I've been busy, I am still working on the duck typing project.  I have at least one bug fix and I'm working on support for generic methods.  You can expect another release soon.  So stay tuned...

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by deftflux on Friday, September 07, 2007 5:23 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Great post by Phil Haack

Phil Haack recently posted a blog entry on duck typing.  Read it here.  It gives a very good explanation of it and some of its advantages.

He also gives a very good example of a use for duck typing using my library.  His example demonstrates a feature that I like to call variance in class members.  Specifically, when duck casting an object to an interface, the object need not even implement the interface exactly.  Rather, its members may differ from those defined in the interface as long as the parameter types, return types, property types, and event delegate types are convertible to one another, which may be so via duck typing, as in his example.  Here is an excerpt from his example: (comments mine)

public interface IHttpContext
{
    // Note that the Request property returns IHttpRequest.
    IHttpRequest Request { get;}
}

public interface IHttpRequest
{
    Uri Url { get;}
}
 

In his example, the sealed class HttpContext is duck casted to IHttpContext.  Here is what some of the code might look like for this class for the sake of demonstration:

public sealed class HttpContext
{
    // Here, however, Request returns HttpRequest.  Duck typing still works because HttpRequest
    // can be duck casted to IHttpRequest, which is actually done behind the scenes when Request
    // is called on the duck casted object through the IHttpContext interface.
        
    public HttpRequest Request { get { ... } }
    
    ...
}

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by deftflux on Monday, August 20, 2007 7:12 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Jordan Terrell's blog

A long-time friend and development mentor, Jordan Terrell, recently started a blog as well.  Very smart guy.  Be sure to subscribe to this one, as I anticipate many interesting posts.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General | Development
Posted by deftflux on Monday, August 20, 2007 2:47 AM
Permalink | Comments (0) | Post RSSRSS comment feed